This prompt is designed for CI/CD pipeline integration at pull request creation time. It analyzes changed file paths, module ownership, static analysis hints, and a runtime budget to produce a minimal yet sufficient test subset. The output includes a confidence score for every skipped test, making the selection auditable for release managers and SDETs who need to defend why certain tests were not executed. Use this when your full regression suite exceeds your PR pipeline time budget and you need a data-driven, repeatable method for test selection that does not rely on a single engineer's intuition.
Prompt
Pull Request Test Suite Optimization Prompt Template

When to Use This Prompt
Defines the job-to-be-done, ideal user, required context, and boundaries for the Pull Request Test Suite Optimization Prompt Template.
The prompt requires structured inputs: a list of changed file paths from the git diff, a module ownership map linking paths to teams, any available static analysis results (lint warnings, complexity scores, security scan findings), and a hard runtime budget in minutes. Without these inputs, the model cannot produce a defensible selection. The output schema must be strictly enforced—expect a JSON array of test suites to execute, each with a rationale, and a separate array of skipped suites with confidence scores and risk justifications. Wire this into your CI system so that the prompt runs before test execution, and the output directly feeds your test runner's filter or tag mechanism.
Do not use this prompt for hotfixes that bypass normal PR pipelines, for repositories with fewer than 50 test suites where full runs are cheap, or when the runtime budget is so tight that even a minimal selection cannot complete. The prompt is not a substitute for flaky test quarantine—combine it with a flaky test exclusion list if your suite has known instability. Always log the full prompt input and output as a build artifact so release managers can audit selection decisions post-hoc. If a skipped test's confidence score falls below your team's threshold, configure the pipeline to escalate for human review rather than silently omitting it.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Pull Request Test Suite Optimization Prompt fits your workflow, and what operational risks to manage before integrating it into your CI/CD pipeline.
Good Fit: CI/CD Pipeline Integration
Use when: the prompt is triggered automatically on PR creation or push, with access to git diff, changed file paths, and ownership metadata. Guardrail: ensure the prompt receives a structured diff summary and a complete test inventory, not raw source code, to stay within context limits and produce a reliable selection.
Bad Fit: Greenfield Projects Without Test History
Avoid when: the repository has no existing test suite, no historical failure data, and no ownership mapping. The prompt relies on change-to-test traceability; without it, the confidence score becomes meaningless. Guardrail: fall back to a full test run or a manual smoke test checklist until sufficient test history exists.
Required Inputs: Diff, Test Inventory, and Ownership Map
What to watch: the prompt needs a structured change summary, a list of available tests with paths and tags, and a module-to-team ownership map. Missing any of these degrades selection accuracy. Guardrail: validate inputs before calling the prompt; if ownership data is incomplete, flag skipped tests as 'unverified' rather than 'safe to skip.'
Operational Risk: False-Negative Test Skips
Risk: the prompt may recommend skipping a test that would have caught a regression, especially for indirect dependency changes or shared utility modules. Guardrail: always run a mandatory smoke test subset regardless of the prompt's recommendation, and log every skip decision with the confidence score for post-release audit.
Operational Risk: Runtime Budget Overruns
Risk: the selected subset may still exceed the CI/CD pipeline's time budget, causing queue delays or timeouts. Guardrail: include a hard runtime constraint in the prompt and request a Pareto breakdown of coverage gained per minute. If the budget is exceeded, implement a secondary cutoff that drops the lowest-ranked tests.
Human Review: High-Risk or Compliance-Gated Changes
Risk: for changes touching authentication, payment, PII handling, or compliance-critical paths, an automated skip decision is not defensible. Guardrail: route any PR that modifies files in designated high-risk directories to a manual review queue, and require explicit approval before skipping tests in those areas.
Copy-Ready Prompt Template
A reusable prompt template for generating a minimal, risk-justified test subset from a pull request's code changes, ready for CI/CD integration.
This prompt template is designed to be pasted directly into your CI/CD pipeline configuration, an AI gateway, or a test orchestration script. It instructs the model to act as a test architect, analyzing a pull request's diff, file paths, and ownership metadata to produce a JSON output that specifies exactly which tests to run, which to skip, and why. The template uses square-bracket placeholders for all dynamic inputs, ensuring you can replace them with data from your version control system, test management platform, and static analysis tools before each invocation.
markdownYou are a senior test architect optimizing a regression test suite for a pull request. Your goal is to minimize execution time while maintaining acceptable risk coverage. ## Input Data - **PR Diff:** [DIFF] - **Changed File Paths:** [CHANGED_FILES] - **Module Dependency Graph (Mermaid or JSON):** [DEPENDENCY_GRAPH] - **Test Suite Catalog (Test Name, Path, Tags, Avg Runtime, Owner):** [TEST_CATALOG] - **Historical Failure Data (Test Name, Failure Rate, Last Failed Commit):** [FAILURE_DATA] - **Code Ownership Map (Path Pattern -> Team):** [OWNERSHIP_MAP] ## Constraints - **Runtime Budget:** [RUNTIME_BUDGET_MINUTES] minutes. - **Mandatory Tests (must always run):** [MANDATORY_TESTS] - **Flaky Test Quarantine List (do not select):** [QUARANTINE_LIST] - **Risk Threshold:** Acceptable risk of a missed regression is [RISK_THRESHOLD]%. ## Task 1. Analyze the changed files and dependency graph to identify all directly and transitively impacted modules. 2. Cross-reference impacted modules with the test suite catalog to find candidate tests. 3. Prioritize candidates using a risk score derived from: code churn size, historical failure rate of the test, and criticality of the owning team's module. 4. Select a subset of tests that fits within the [RUNTIME_BUDGET_MINUTES]-minute budget, maximizing risk coverage. 5. For every test NOT selected, provide a specific, auditable reason for skipping it. ## Output Schema Return a single valid JSON object with this exact structure: { "analysis_summary": { "impacted_modules": ["string"], "total_candidate_tests": "integer", "estimated_runtime_all_candidates_minutes": "float" }, "selected_tests": [ { "test_name": "string", "risk_score": "float (0-100)", "selection_reason": "string" } ], "skipped_tests": [ { "test_name": "string", "skip_reason": "string", "risk_if_skipped": "low | medium | high", "confidence_in_skip": "float (0-100)" } ], "total_estimated_runtime_minutes": "float", "coverage_risk_assessment": "string" }
To adapt this template, replace each [PLACEHOLDER] with data from your ecosystem. The [DIFF] can be a unified diff from git diff main...HEAD. The [DEPENDENCY_GRAPH] can be generated by tools like madge or your build system. The [TEST_CATALOG] should be a JSON array exported from your test management system. Crucially, the [RUNTIME_BUDGET_MINUTES] and [RISK_THRESHOLD] are policy decisions you must supply. After replacing the variables, send the prompt to a capable model (like GPT-4o or Claude 3.5 Sonnet) and validate the JSON output against the schema before using it to orchestrate your test runner. For high-risk deployments, route the skipped_tests list with a high risk rating to a human reviewer for final approval before the pipeline proceeds.
Prompt Variables
Inputs the prompt needs to work reliably. Validate these before sending the prompt to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CHANGED_PATHS] | List of file paths modified in the pull request | src/auth/login.ts, src/auth/token.ts, package.json | Must be a non-empty list of relative file paths. Validate each path exists in the repository tree at the target commit SHA. |
[DEPENDENCY_GRAPH] | Module dependency map showing which files import or depend on which other files | {"src/auth/login.ts": ["src/utils/crypto.ts", "src/db/users.ts"], ...} | Must be valid JSON with string keys and string array values. Reject if circular references exceed depth limit or if graph is empty for any changed path. |
[TEST_CATALOG] | Inventory of available test suites with metadata: file path, estimated runtime, historical pass rate, and tags | [{"path": "tests/auth/login.test.ts", "runtime_s": 12.3, "pass_rate": 0.98, "tags": ["auth", "unit"]}, ...] | Must be a JSON array with at least one entry. Each entry requires path, runtime_s (positive number), pass_rate (0.0-1.0), and tags (non-empty string array). Reject if any test path does not exist. |
[RUNTIME_BUDGET_SECONDS] | Maximum total execution time allowed for the selected test subset | 600 | Must be a positive integer. If null or 0, treat as unbounded. Reject negative values. Validate against CI pipeline timeout configuration. |
[CHANGE_RISK_PROFILE] | Risk classification per changed path based on static analysis or historical defect density | {"src/auth/login.ts": "high", "package.json": "medium"} | Must be valid JSON mapping each changed path to one of: low, medium, high, critical. Reject if any changed path is missing from the mapping. |
[FLAKY_TEST_LIST] | Set of test paths known to be flaky with quarantine status | ["tests/network/retry.test.ts", "tests/ui/animation.test.ts"] | Must be a JSON array of test paths. Each path must exist in the test catalog. Flaky tests should be excluded from selection or flagged with a confidence override. |
[OWNERSHIP_MAP] | Mapping of file paths or directories to responsible teams or individuals | {"src/auth/": "team-identity", "src/db/": "team-platform"} | Must be valid JSON. Used to include ownership-relevant tests even when dependency graph coverage is thin. Reject if ownership zones overlap ambiguously. |
[HISTORICAL_DEFECT_DATA] | Past defect records linked to specific files or modules with severity and occurrence count | [{"file": "src/auth/login.ts", "defects": 4, "severity": "high"}, ...] | Must be a JSON array. Each entry requires file (string), defects (non-negative integer), and severity (low, medium, high, critical). Used to weight risk. Reject if file references don't match repository structure. |
Implementation Harness Notes
How to wire the PR Test Suite Optimization prompt into a CI/CD pipeline with validation, retries, and audit logging.
This prompt is designed to be called programmatically during pull request creation or update events. The implementation harness should treat the prompt as a deterministic component of a larger pipeline: it receives structured inputs from the PR event, produces a structured JSON output, and that output must be validated before any test-skipping decisions are executed. The harness is responsible for providing the prompt with the correct [CHANGED_PATHS], [DEPENDENCY_GRAPH], [TEST_CATALOG], [HISTORICAL_FAILURE_DATA], and [RUNTIME_BUDGET] placeholders. These inputs should be assembled from your version control system (e.g., git diff --name-only origin/main...HEAD), your test management database, your CI flakiness tracker, and your pipeline configuration respectively.
The harness must enforce a validation gate on the model's output before acting on it. Parse the JSON response and check that every recommended test exists in your test catalog, that the sum of estimated runtimes does not exceed the [RUNTIME_BUDGET], and that the skipped_tests array includes a non-empty rationale and confidence_score for each entry. If validation fails, retry the prompt once with the validation errors appended to the [CONSTRAINTS] input. If the retry also fails, fall back to running the full test suite and log the incident for prompt improvement. Never skip a test based on an unvalidated or low-confidence recommendation (e.g., confidence_score < 0.85) without human review.
For model choice, use a model with strong JSON mode and reasoning capabilities. Temperature should be set to 0 or near-zero to maximize output determinism. Implement structured logging that captures the PR identifier, input change set, raw prompt, raw response, validation result, and final test execution decision. This audit trail is critical for post-incident review and for tuning the prompt's risk thresholds over time. Wire the harness into your CI platform (GitHub Actions, GitLab CI, Jenkins) as a gate that runs before the test matrix is dispatched, and ensure the test orchestrator can dynamically include or exclude tests based on the validated, approved output of this prompt.
Expected Output Contract
Fields, format, and validation rules for the model response. Use this contract to parse, validate, and integrate the output into a CI/CD pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selected_tests | Array of objects | Schema check: each object must contain test_id, suite, priority, and estimated_duration_seconds. Array must not be empty unless no tests match. | |
selected_tests[].test_id | String | Format check: must match pattern [PROJECT]-[SUITE]-[NUMBER] (e.g., AUTH-LOGIN-004). Parse check: must exist in the provided [TEST_CATALOG]. | |
selected_tests[].priority | String enum | Enum check: must be one of P0, P1, P2. P0 reserved for smoke tests and changed-path direct coverage. P1 for adjacent module tests. P2 for regression depth. | |
selected_tests[].selection_rationale | String | Content check: must cite a specific changed file, dependency edge, or risk rule from [CHANGE_CONTEXT]. Must not be generic (e.g., 'high risk' alone fails). | |
skipped_tests | Array of objects | Schema check: each object must contain test_id, confidence_score, and skip_reason. Array may be empty if all tests are selected. | |
skipped_tests[].confidence_score | Number (0.0-1.0) | Range check: must be between 0.0 and 1.0. Threshold check: scores above 0.85 require explicit override justification in skip_reason. | |
total_estimated_runtime_seconds | Integer | Constraint check: must be sum of selected_tests[].estimated_duration_seconds. Budget check: must not exceed [RUNTIME_BUDGET_SECONDS] unless an override flag is set and justified. | |
risk_coverage_percentage | Number (0.0-100.0) | Calculation check: must equal (sum of risk weights of selected tests) / (sum of risk weights of all tests in [TEST_CATALOG]) * 100. Audit check: must be accompanied by a risk_weight_source field citing the origin of weights. |
Common Failure Modes
When optimizing a test suite for a pull request, these are the most common ways the prompt fails in production. Each card explains the failure and how to prevent it.
Silent Omission of Critical Tests
What to watch: The model excludes a test that covers the exact changed function or a tightly coupled dependency, often because the static analysis hints are incomplete or the dependency graph is stale. The confidence score looks high, but the test is missing. Guardrail: Implement a hard rule that any test with a direct file-path match to the diff cannot be excluded. Add a post-processing step that diffs the selected test list against a simple git diff --name-only grep of test files.
Budget Over-Optimization
What to watch: When a strict runtime budget is provided, the model drops high-risk integration tests to fit within the time limit, prioritizing fast unit tests that provide less systemic confidence. Guardrail: Tier the budget constraint. Define a non-negotiable 'safety floor' of tests that must run regardless of time, and a separate 'extended' budget for the remaining risk-ranked tests. Validate that the safety floor is always present in the output.
Confidence Score Inflation
What to watch: The model assigns a high confidence score to skipping a test based on weak or irrelevant reasoning, such as 'module not directly modified' when a shared utility function was changed. Guardrail: Require the model to output a specific, verifiable reason for each skipped test. Run an eval that checks if the reason cites a concrete file path or dependency edge. Flag any skipped test where the reason is generic or purely probabilistic.
Ignoring Environmental and Configuration Changes
What to watch: The prompt focuses exclusively on source code diffs and misses changes to configuration files, environment variables, Dockerfiles, or infrastructure-as-code that can break the application at runtime. Guardrail: Expand the input context to include a diff of non-source-code files. Add a specific instruction to select smoke tests and deployment verification tests whenever configuration or infrastructure files are modified.
Stale Dependency Graph Poisoning
What to watch: The provided dependency graph is out of date, causing the model to miss transitive dependencies that have changed. The model trusts the provided graph absolutely and makes incorrect exclusion decisions. Guardrail: Add a metadata field for the graph's last-updated timestamp. Instruct the model to treat dependency edges older than a threshold as uncertain and to default to including tests for uncertain edges. Flag the output if the graph age exceeds the threshold.
Flaky Test Contamination
What to watch: The model includes a known flaky test in the critical path, causing a false-positive CI failure that blocks the PR merge. The prompt lacks awareness of the test's flakiness history. Guardrail: Provide a flaky-test quarantine list as a hard input constraint. Instruct the model to never include a quarantined test in the 'must-run' set. If a flaky test is the only coverage for a change, escalate with a warning instead of silently including it.
Evaluation Rubric
Criteria for evaluating the quality and safety of the PR test suite optimization output before integrating it into your CI/CD pipeline. Each criterion maps to a concrete pass standard, a failure signal, and a test method suitable for automated eval or manual review.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Test Selection Traceability | Every recommended test is mapped to at least one changed file or dependency from the PR diff | A recommended test has no associated changed file or dependency in the justification | Parse output JSON; assert that each entry in the test list has a non-empty |
Runtime Budget Compliance | Total estimated runtime of selected tests is less than or equal to the [RUNTIME_BUDGET] constraint | Sum of | Calculate sum of |
Skipped Test Justification | Every skipped test includes a | A skipped test entry is missing | Schema validation against expected output contract; enum check on |
Confidence Score Validity | Every skipped test has a | A | Parse output; assert 0.0 <= |
Critical Path Coverage | All tests tagged as | A test with | Cross-reference output selected/skipped lists against input inventory; assert no critical_path test is skipped without |
No Hallucinated Test Names | All test names in the output match exactly a test name from the input test inventory | A test name in the output does not appear in the provided test inventory list | String match each output test name against the input inventory; flag any unmatched names as hallucinations |
Risk Disclosure Completeness | Output includes a |
| Check that |
Output Schema Conformance | Output is valid JSON matching the expected schema with all required fields present | Output is not valid JSON, or is missing required top-level fields such as | Validate output against JSON schema; assert all required fields are present and types match expected contract |
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
Add structured inputs for ownership, dependency graph, historical failure data, and a runtime budget. Require a schema with confidence scores, skip rationale, and estimated execution time per test.
codeGiven: - PR diff: [PR_DIFF] - Changed paths: [CHANGED_PATHS] - Test-to-source mapping: [TEST_MAP] - Dependency graph (module->dependents): [DEP_GRAPH] - Historical failure rate per test: [FAILURE_HISTORY] - Runtime budget: [BUDGET_SECONDS] seconds Return JSON: { "selected_tests": [ { "test_path": string, "risk_score": 0-1, "estimated_runtime_seconds": number, "selection_rationale": string } ], "skipped_tests": [ { "test_path": string, "skip_confidence": 0-1, "skip_rationale": string } ], "total_estimated_runtime_seconds": number, "coverage_gaps": [string] }
Watch for
- Schema drift: validate output shape before pipeline ingestion
- Stale dependency graphs: outdated graphs produce false skips
- Budget overruns: enforce hard runtime ceiling in post-processing

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