Inferensys

Prompt

Test Debt Quantification and Prioritization Prompt Template

A practical prompt playbook for using Test Debt Quantification and Prioritization Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and boundaries for the test debt quantification prompt.

This prompt is built for engineering managers and tech leads who need to move from anecdotal frustration about test suite quality to a defensible, data-backed remediation plan. It is designed to be used by a coding agent or analysis tool that has access to repository context, CI/CD history, and test infrastructure metadata. The prompt ingests raw signals—flakiness logs, coverage reports, execution duration data, assertion quality audits, and fixture staleness checks—and produces a quantified, prioritized backlog that maps each debt item to risk reduction and estimated effort. The output is not a single test fix or a generic coverage recommendation; it is a structured remediation backlog suitable for sprint planning, resource allocation, and engineering leadership review.

Use this prompt when you have access to concrete test suite data and need a prioritization framework that accounts for multiple debt dimensions simultaneously. The ideal input includes flakiness frequency and cost (time wasted on reruns), coverage gaps mapped to critical code paths, slow tests with duration trends, assertion weakness audit results, and fixture freshness reports. The prompt expects these inputs to be provided as structured context—either inline or via tool-retrieved data—so the model can reason across dimensions rather than generating plausible-sounding but ungrounded advice. Do not use this prompt when you lack quantitative data about your test suite, when you need a single test repair, or when you are looking for general testing philosophy. It is also inappropriate for teams that cannot act on a prioritized backlog due to organizational constraints; the output assumes an engineering team ready to execute remediation work.

Before running this prompt, ensure your coding agent or analysis harness has collected and normalized the required input signals. The prompt includes placeholders for [FLAKINESS_DATA], [COVERAGE_REPORT], [DURATION_DATA], [ASSERTION_AUDIT], and [FIXTURE_FRESHNESS_REPORT]. If any of these inputs are unavailable, the prompt will still produce output, but the prioritization will be skewed toward the available dimensions. For high-risk domains—such as financial systems, healthcare software, or safety-critical infrastructure—the output should be treated as a starting point for human review, not a final remediation plan. The prompt includes a [RISK_LEVEL] parameter to adjust the caution and evidence requirements in the output. After generating the backlog, validate that each debt item is traceable to a specific input signal and that effort estimates are consistent with your team's historical velocity before committing to a remediation sprint.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide whether the Test Debt Quantification and Prioritization Prompt Template is the right tool for your current situation.

01

Good Fit: Multi-Signal Debt Assessment

Use when: you have access to CI logs, test duration data, flakiness history, coverage reports, and static analysis output. The prompt synthesizes across these signals to produce a ranked backlog. Guardrail: validate that each input signal is recent (within the last 30 days) and scoped to the target repository or team.

02

Bad Fit: Single-Symptom Diagnosis

Avoid when: you are investigating a single flaky test or one slow build step. This prompt is designed for portfolio-level quantification, not root cause analysis of individual failures. Guardrail: route single-symptom investigations to the Flaky Test Root Cause Analysis or Timeout Flakiness Diagnosis prompts instead.

03

Required Inputs: Structured Evidence Feeds

Risk: the prompt produces vague or unsubstantiated rankings when given only anecdotal descriptions. Guardrail: require structured inputs—flakiness rates per test, P50/P95 durations, coverage percentages per module, and static analysis rule counts—before invoking the prompt. If structured data is unavailable, run the Test Suite Health Dashboard prompt first to generate it.

04

Operational Risk: Effort Estimates Without Historical Baselines

Risk: the prompt generates remediation effort estimates that may be optimistic or uncalibrated if the model lacks historical fix-effort data from your team. Guardrail: treat effort estimates as relative ordering signals, not sprint-commitment numbers. Override with team-provided estimates before publishing the backlog.

05

Operational Risk: Stale Data Produces Misleading Priorities

Risk: a backlog built on coverage reports from three months ago or flakiness data from a different release cycle will misdirect engineering effort. Guardrail: add a data freshness check to the prompt harness—reject inputs older than a configurable threshold and require regeneration before prioritization runs.

06

Human Review Required: Risk Reduction Projections

Risk: the prompt may project risk reduction percentages that imply false precision. Guardrail: require an engineering lead to review and adjust risk reduction projections before the backlog is shared with stakeholders. The prompt output is a starting point for a conversation, not a contract.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that quantifies test debt across multiple dimensions and produces a prioritized remediation backlog with effort estimates and risk reduction projections.

This prompt template is designed to be wired into an automated test health pipeline or used as part of a manual engineering review. It expects structured inputs describing the current state of the test suite, including flakiness data, coverage reports, execution timing, and known issues. The model is instructed to reason across these dimensions, apply a consistent scoring rubric, and output a strictly typed JSON payload that can be ingested by dashboarding tools, ticketing systems, or CI/CD quality gates. Before using this prompt in production, ensure that all input data is recent (e.g., from the last 30 days of CI runs) and that the output schema is validated against your downstream consumer.

text
You are a test health analyst. Your task is to quantify test debt across a software test suite and produce a prioritized remediation backlog.

## INPUT DATA
- Flakiness Report: [FLAKINESS_REPORT]
- Coverage Report: [COVERAGE_REPORT]
- Test Execution Timings: [EXECUTION_TIMINGS]
- Known Issues & Stale Fixtures: [KNOWN_ISSUES]
- Team Capacity & Velocity: [TEAM_CAPACITY]

## SCORING DIMENSIONS
For each test or test group, assess debt across these dimensions on a scale of 0 (no debt) to 10 (critical debt):
1. Flakiness Cost: Failure rate * CI rerun cost * developer investigation time.
2. Coverage Gap: Critical code paths with zero or inadequate test coverage.
3. Execution Slowness: Tests exceeding [SLOW_THRESHOLD_MS]ms, multiplied by frequency of execution.
4. Assertion Weakness: Tests with over-broad matches, missing negative cases, or unverified side effects.
5. Fixture & Environment Staleness: Tests relying on outdated schemas, unrealistic data, or contaminated shared state.

## OUTPUT INSTRUCTIONS
Generate a JSON object with the following structure. Do not include any text outside the JSON.

{
  "summary": {
    "total_tests_analyzed": <int>,
    "overall_debt_score": <float 0-10>,
    "critical_issues_count": <int>,
    "estimated_remediation_weeks": <float>,
    "projected_risk_reduction_pct": <float>
  },
  "top_remediation_items": [
    {
      "rank": <int>,
      "test_or_group_name": "<string>",
      "debt_dimension": "flakiness|coverage_gap|slowness|assertion_weakness|fixture_staleness",
      "severity_score": <float 0-10>,
      "evidence": "<specific data point from input reports>",
      "suggested_fix": "<concrete, actionable remediation step>",
      "effort_estimate_hours": <float>,
      "risk_reduction_if_fixed_pct": <float>
    }
  ],
  "dimension_breakdown": {
    "flakiness_cost": { "total_items": <int>, "avg_severity": <float>, "total_effort_hours": <float> },
    "coverage_gap": { "total_items": <int>, "avg_severity": <float>, "total_effort_hours": <float> },
    "execution_slowness": { "total_items": <int>, "avg_severity": <float>, "total_effort_hours": <float> },
    "assertion_weakness": { "total_items": <int>, "avg_severity": <float>, "total_effort_hours": <float> },
    "fixture_staleness": { "total_items": <int>, "avg_severity": <float>, "total_effort_hours": <float> }
  },
  "excluded_items": [
    {
      "test_or_group_name": "<string>",
      "reason_for_exclusion": "<why this item was deprioritized or excluded>"
    }
  ]
}

## CONSTRAINTS
- Base all severity scores and evidence strictly on the provided input data. Do not invent or assume data.
- If input data is missing for a dimension, set its severity to 0 and note the absence in `excluded_items`.
- Prioritize items that block CI pipelines or cause developer toil over purely cosmetic improvements.
- For each remediation item, the `risk_reduction_if_fixed_pct` must be a reasonable estimate relative to the overall debt score.
- If team capacity data is provided, ensure `estimated_remediation_weeks` accounts for it.

To adapt this template for your environment, replace each square-bracket placeholder with structured data from your test infrastructure. The [FLAKINESS_REPORT] should include per-test failure rates and CI rerun costs. The [COVERAGE_REPORT] should map uncovered code paths to specific tests or modules. Set [SLOW_THRESHOLD_MS] to your team's agreed-upon threshold (e.g., 5000ms for integration tests, 200ms for unit tests). If you lack data for a dimension, pass an explicit "NOT_AVAILABLE" string rather than omitting the placeholder, so the model can correctly populate the excluded_items array. After receiving the output, validate the JSON schema, check that all severity scores are grounded in the provided evidence, and route items with severity_score above 8 to your on-call or test-infrastructure team for immediate review.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Test Debt Quantification and Prioritization prompt. Each variable must be populated before execution to ensure reliable, grounded output.

PlaceholderPurposeExampleValidation Notes

[TEST_SUITE_METADATA]

Aggregate metrics describing the test suite's current state

{"total_tests": 4521, "flaky_rate": 0.07, "avg_duration_seconds": 340, "coverage_pct": 62}

Must be valid JSON. All numeric fields required. flaky_rate must be 0.0-1.0. coverage_pct must be 0-100.

[FLAKY_TEST_LOG]

Recent failure history for tests flagged as flaky, including timestamps and error messages

test_auth_timeout failed 12/18 runs in last 7d; error: context deadline exceeded

Each entry must include test name, failure count, total runs, time window, and error signature. Null allowed if no flaky tests exist.

[SLOW_TEST_REGISTER]

Tests exceeding duration thresholds with execution time trends

test_full_export: p95=420s, trend=+15% week-over-week

Each entry must include test name, p95 duration in seconds, and trend direction. Null allowed if no slow tests.

[COVERAGE_GAP_REPORT]

Output from coverage tool showing uncovered files, functions, and branches

src/payment/refund.go: processRefund uncovered; 3 branches missed

Must map to specific source files and symbols. Format: file path, symbol name, gap type (function/branch/line). Null allowed if coverage tool unavailable.

[ASSERTION_AUDIT_LOG]

Results from assertion weakness audit identifying tests with weak or missing assertions

test_user_create: 0 assertions on error paths; test_cache_invalidate: assert true on nil response

Each entry must include test name and weakness category. Categories: missing_negative, tautological, unverified_side_effect, over_broad_match.

[STALE_FIXTURE_REGISTER]

Fixtures that have diverged from current schema or production data distributions

fixture: user_payload_v2 missing 'preferences' field added in schema v3.1

Each entry must include fixture name, schema version mismatch, and staleness indicator. Null allowed if fixture audit unavailable.

[CI_PIPELINE_CONFIG]

Current CI pipeline configuration including test execution order, parallelism, and resource limits

parallel_workers: 8; timeout_per_suite: 30m; retry_on_failure: 2

Must include timeout settings, retry policy, and parallelism config. Used to contextualize slow test impact and quarantine feasibility.

[TEAM_CAPACITY_CONTEXT]

Available engineering capacity and current sprint commitments for remediation planning

{"qa_engineers": 2, "available_hours_per_week": 20, "current_sprint_focus": "payment reliability"}

Must be valid JSON with numeric capacity fields. Used to calibrate effort estimates and prioritization against real constraints.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the test debt quantification prompt into an application or workflow with validation, retries, and human review gates.

This prompt is designed to be called from a CI/CD pipeline, a code quality dashboard, or a scheduled analysis job—not as a one-off chat interaction. The implementation harness must collect the required inputs (test suite metadata, flakiness history, coverage reports, execution timing data, and repository context), assemble them into the prompt's [INPUT] block, and parse the structured JSON output for downstream consumption. Because the output includes effort estimates and risk reduction projections that may influence team roadmaps, the harness should treat this as a high-stakes analysis workflow with mandatory validation and human review before any remediation backlog is committed to a sprint.

Input Assembly: Build a data collection step that gathers: (1) test execution history from your CI system (at least 30 days of runs with pass/fail/duration per test), (2) code coverage reports in a machine-readable format (e.g., LCOV, JaCoCo XML, or Istanbul JSON), (3) test file paths and sizes, (4) assertion counts per test if available, (5) fixture or mock file modification dates, and (6) a module-to-team ownership map. Serialize this into a structured JSON block that becomes the [INPUT] placeholder. For large codebases, pre-filter to the top N modules by churn or failure rate to stay within context windows. Model Choice: Use a model with strong structured output capabilities and a context window large enough for your assembled input—Claude 3.5 Sonnet, GPT-4o, or Gemini 1.5 Pro are appropriate. For very large repositories, consider a two-pass approach: first pass identifies high-debt areas, second pass deep-dives on those areas with full context. Output Validation: Parse the model's JSON response and validate against a schema that requires: dimensions (array of debt categories with name, severity, affected_tests, cost_estimate_hours), prioritized_backlog (array of remediation items with rank, description, effort_days, risk_reduction_score, blocked_by), and summary (object with total_estimated_debt_hours, highest_risk_dimension, quick_wins). Reject outputs missing required fields, containing circular dependencies in blocked_by, or with risk_reduction_score values outside 0-1 range. On validation failure, retry once with the validation errors appended to the prompt as [CONSTRAINTS] feedback.

Human Review Gate: The validated output must route to a review queue—typically a GitHub issue, Linear ticket, or internal dashboard—where an engineering manager or tech lead can accept, reject, or adjust each backlog item before it becomes actionable work. The harness should render the output as a readable summary with expandable detail per dimension, not just raw JSON. Logging and Traceability: Log the full prompt input, model response, validation results, and reviewer decisions. This creates an audit trail for comparing debt assessments over time and measuring whether remediation efforts actually reduced the quantified debt. What to Avoid: Do not auto-create tickets or assign work from this prompt's output without human review—effort estimates and risk scores are model judgments that need engineering calibration. Do not run this on every commit; schedule it weekly or per-release to avoid noise and token costs. If your test suite has fewer than 100 tests or less than 14 days of execution history, the signal-to-noise ratio will be too low for meaningful quantification—use a simpler health check prompt instead.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the model's output against this contract before routing the remediation backlog into your project management or CI pipeline. Each field must pass the stated validation rule or trigger a retry or human review.

Field or ElementType or FormatRequiredValidation Rule

debt_items

Array of objects

Array length must be >= 1. If empty, retry with explicit instruction to return at least one debt item or a null reason.

debt_items[].id

String (slug)

Must match pattern ^[a-z0-9-]+$. No duplicates across the array.

debt_items[].category

Enum string

Must be one of: flakiness_cost, coverage_gap, slow_test, missing_assertion, stale_fixture, or other. If other, the notes field is required.

debt_items[].severity

Enum string

Must be one of: critical, high, medium, low. If critical, the risk_exposure field must be populated.

debt_items[].effort_estimate

Object

Must contain effort_hours (number, >= 0) and confidence (enum: low, medium, high). If confidence is low, a retry with more context is recommended.

debt_items[].risk_reduction

String

Must be a non-empty string describing the projected risk reduction. A null or empty string triggers a retry.

debt_items[].evidence

Array of strings

Each string must reference a concrete file path, test name, or CI log line. If empty, flag for human review before accepting.

prioritized_backlog

Array of strings (IDs)

Must be an ordered list of debt_item IDs. Every ID must exist in debt_items. If the list is empty, retry.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when quantifying test debt and how to guard against it.

01

Vague Prioritization Without Cost Data

Risk: The model produces a generic backlog sorted by intuition instead of data-driven cost estimates. Without concrete flakiness cost, failure frequency, or developer time impact, prioritization becomes arbitrary. Guardrail: Require structured input data (CI failure logs, coverage reports, flakiness history) and constrain the output to include explicit cost dimensions—developer hours lost, CI retry minutes, and risk of missed regressions.

02

Hallucinated Effort Estimates

Risk: The model invents plausible-sounding but ungrounded remediation effort estimates (e.g., '2 hours to fix') without access to codebase complexity, team velocity, or dependency constraints. Guardrail: Force the prompt to request effort as relative sizing (XS/S/M/L/XL) with explicit assumptions, and flag any absolute time estimates for human review before inclusion in a backlog.

03

Coverage Gap Overstatement

Risk: The model conflates uncovered code paths with meaningful test gaps, inflating debt scores for dead code, generated code, or intentionally untested error handlers. Guardrail: Require the prompt to cross-reference coverage data with code annotations (e.g., @Generated, no cover pragmas) and production call frequency before scoring a gap as actionable debt.

04

Stale Fixture Blindness

Risk: The model quantifies test debt from coverage and flakiness signals but misses stale fixtures that silently erode test value—fixtures that no longer match production schemas or data distributions. Guardrail: Include a fixture freshness audit step in the prompt that compares fixture schemas against current migrations and production sampling before debt scoring.

05

Single-Dimension Debt Scoring

Risk: The model reduces test debt to a single number (e.g., 'coverage score') and ignores compounding factors like flakiness cost, slow execution, and missing assertions that together make a test suite unreliable. Guardrail: Require a multi-axis debt rubric in the output schema—flakiness cost, coverage gap severity, execution duration waste, assertion weakness, and fixture staleness—with a weighted composite score and per-axis breakdown.

06

Remediation Ordering Without Dependency Awareness

Risk: The model suggests fixing tests in isolation without recognizing that some fixes depend on refactoring shared fixtures, updating mocks, or resolving upstream flakiness first. Guardrail: Require the output to include a dependency graph or ordering constraints between remediation items, flagging items that must be sequenced together or that block other fixes.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the test debt quantification output before integrating it into a prioritization workflow or sharing it with stakeholders. Each criterion targets a specific failure mode common to AI-generated debt analysis.

CriterionPass StandardFailure SignalTest Method

Debt Item Grounding

Every debt item references a specific file path, test name, or CI failure log excerpt

Vague references like 'some tests are slow' or 'coverage is low in the auth module' without concrete evidence

Parse output for [FILE_PATH], [TEST_NAME], or [LOG_EXCERPT] tokens; flag any debt item missing all three

Cost Estimate Reasonableness

Flakiness cost uses wall-clock failure rate × CI rerun minutes; slow test cost uses duration × frequency

Arbitrary cost numbers without derivation, or all costs rounded to identical values

Extract cost calculation fields; verify formula presence for each cost type; flag if standard deviation of costs is near zero

Coverage Gap Specificity

Each gap identifies the uncovered function, branch, or error path with line numbers

Generic gaps like 'need more error handling tests' or 'add integration tests' without code-level targets

Check each gap entry for [FUNCTION_NAME] or [LINE_RANGE]; fail if more than 20% lack code-level targets

Prioritization Logic Transparency

Backlog order includes explicit scoring on at least two dimensions (e.g., risk × effort) with weights stated

Items sorted without explanation, or all items assigned identical priority scores

Validate that each item has a [PRIORITY_SCORE] field with visible sub-scores; reject if scores are uniform

Effort Estimate Calibration

Effort estimates use t-shirt sizes or story points with a defined mapping to hours or complexity tiers

All items estimated as 'medium' or effort field contains only 'TBD' or null values

Check [EFFORT_ESTIMATE] field against allowed enum values; fail if more than 30% are identical or missing

Risk Reduction Projection Plausibility

Projected risk reduction includes a directional impact (high/medium/low) tied to a specific failure mode

Risk reduction claims like '100% improvement' or 'eliminates all flakiness' without qualification

Scan [RISK_REDUCTION] fields for percentage claims above 90% or absolute language; flag for human review

Stale Fixture Detection Evidence

Stale fixture claims include schema version mismatch, last update timestamp, or production data divergence metric

Fixture staleness asserted without comparison data or timestamp evidence

Verify each stale fixture finding contains [SCHEMA_VERSION] or [LAST_UPDATED] field; fail if evidence fields are empty

Actionable Remediation Step Presence

Every backlog item includes at least one concrete next action: write test, refactor, quarantine, or investigate

Items that describe the problem but offer no remediation step, or use 'consider reviewing' as the only action

Check [REMEDIATION_ACTION] field is non-null and matches an allowed action enum; fail if any item lacks a concrete verb

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single repository snapshot. Remove the effort estimation and risk projection sections. Focus only on flakiness cost and coverage gap detection. Use a lightweight output schema with just findings and severity fields.

Watch for

  • Overly broad findings without file-level evidence
  • Missing severity calibration (everything marked critical)
  • No distinction between test debt types (flaky vs. slow vs. missing)
Prasad Kumkar

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.