Inferensys

Prompt

Bug Fix Decomposition Prompt for Coding Agents

A practical prompt playbook for using Bug Fix Decomposition Prompt for Coding Agents in production AI workflows.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and boundaries for the Bug Fix Decomposition Prompt.

This prompt is designed for coding agents that receive a bug report and must produce a structured diagnostic and fix plan before modifying any code. The core job-to-be-done is to force the agent to isolate the bug's root cause, propose candidate fix locations, define verification steps, and specify regression tests—all before a single line of code changes. This pre-execution plan serves as a reviewable artifact that a developer can inspect, challenge, and approve, reducing the risk of an agent making scattered, untargeted edits that introduce new regressions. The ideal user is an engineering lead or developer integrating an AI coding agent into a production repository where untrusted code changes are unacceptable without prior reasoning.

Use this prompt when the bug is reproducible or well-described but its root cause is unknown, when multiple files or modules could be involved, or when the fix requires careful verification to avoid side effects. It is particularly valuable in regulated or high-reliability codebases where every change must be traceable to a diagnosed cause. The prompt expects a detailed bug report as input—stack traces, reproduction steps, logs, and affected versions—and outputs a decomposition with root-cause investigation steps, candidate fix locations, verification subtasks, and regression test requirements. Do not use this prompt for feature requests, architectural redesigns, or trivial one-line fixes where the cause is already obvious. It is also inappropriate for tasks where the agent lacks access to the repository context needed to identify specific files or modules.

Before wiring this prompt into your agent harness, ensure you have a mechanism to supply the bug report as structured context and to validate that the output plan contains all required sections: investigation steps, fix candidates, verification, and regression tests. If the agent's plan skips root-cause isolation and jumps directly to a code change, the harness should reject the output and request a revised plan. In high-risk environments, route the generated plan to a human reviewer before the agent is authorized to execute any code edits. This prompt is a planning gate, not a fix generator—treat it as a required checkpoint in your agent's execution loop.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Bug Fix Decomposition Prompt works, where it fails, and what you must provide to get a reliable plan from a coding agent.

01

Good Fit: Reproducible Bugs with Stack Traces

Use when: the bug report includes a stack trace, error log, or a deterministic reproduction script. The prompt excels at mapping failure evidence to specific code locations. Guardrail: strip sensitive paths and user data from traces before they reach the model.

02

Bad Fit: Intermittent Race Conditions Without Logs

Avoid when: the bug is a non-deterministic race condition or heisenbug with no captured failure state. The decomposition will hallucinate plausible but wrong root causes. Guardrail: require at least one captured failure trace or reproduction step before invoking this prompt.

03

Required Input: Repository Context

Risk: without file paths, module boundaries, and dependency graphs, the agent invents plausible but non-existent code locations. Guardrail: always provide a repository map, relevant file contents, or a codebase index alongside the bug report. The prompt harness should reject plans that reference files not present in the provided context.

04

Operational Risk: Confident but Wrong Root Cause

Risk: the model produces a decomposition that sounds authoritative but isolates the wrong component, wasting engineering time on dead-end investigations. Guardrail: the first subtask must always be evidence collection and reproduction verification. The harness should flag any plan that jumps directly to a fix without an isolation step.

05

Operational Risk: Scope Creep in Fix Subtasks

Risk: the agent expands a targeted bug fix into a refactor or feature addition, introducing regressions. Guardrail: constrain the output with a strict rule: 'Only plan changes necessary to resolve the reported behavior. Do not refactor adjacent code.' Validate subtask descriptions against the original bug report scope.

06

Bad Fit: Bugs Requiring Visual or UX Judgment

Avoid when: the bug is a subjective UI issue ('the button feels wrong') or requires visual design judgment without measurable acceptance criteria. The decomposition will produce code-centric steps that miss the design intent. Guardrail: require a screenshot comparison or a measurable style specification before routing to this prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for decomposing a bug report into a structured diagnostic and fix plan for a coding agent.

This prompt template is designed to be pasted directly into your agent harness. It instructs a coding agent to take a raw bug report and produce a structured plan that isolates the root cause before attempting any fixes. The template uses square-bracket placeholders for all dynamic inputs, ensuring you can adapt it to your specific repository, bug tracker, and coding standards without modifying the core logic. Before using this prompt, ensure your agent has access to the necessary tools, such as file reading, code search, and a test runner.

text
You are a methodical debugging agent. Your task is to analyze a bug report and produce a structured diagnostic and fix plan. Do not write any code yet. Your goal is to understand the bug completely before proposing a solution.

**Bug Report:**
[TITLE]: [BUG_TITLE]
[DESCRIPTION]: [BUG_DESCRIPTION]
[STEPS_TO_REPRODUCE]: [REPRODUCTION_STEPS]
[OBSERVED_BEHAVIOR]: [OBSERVED_RESULT]
[EXPECTED_BEHAVIOR]: [EXPECTED_RESULT]
[ENVIRONMENT]: [ENVIRONMENT_DETAILS]

**Repository Context:**
[REPOSITORY_MAP]: [A summary of the repository's file tree and key modules]

**Available Tools:**
[TOOLS]: [List of available tools, e.g., 'read_file', 'search_code', 'run_tests']

**Output Schema:**
Produce a JSON object with the following structure. Do not include any text outside the JSON object.
{
  "problem_statement": "A one-sentence summary of the bug.",
  "root_cause_hypotheses": [
    {
      "hypothesis": "A clear statement of a potential root cause.",
      "confidence": "low|medium|high",
      "investigation_steps": ["Step 1 to validate this hypothesis", "Step 2..."]
    }
  ],
  "diagnostic_plan": [
    {
      "step_id": 1,
      "action": "A specific, executable action using available tools, e.g., 'search_code for the error message'.",
      "expected_result": "What you expect to find if this step is successful.",
      "purpose": "How this step helps isolate the root cause."
    }
  ],
  "candidate_fix_locations": [
    {
      "file_path": "The relative path to the file.",
      "function_or_component": "The specific function or component.",
      "rationale": "Why this location is a candidate for the fix."
    }
  ],
  "verification_plan": [
    {
      "step_id": 1,
      "action": "A specific action to verify the fix, e.g., 'run the test suite for the user module'.",
      "expected_result": "The expected outcome that confirms the fix."
    }
  ],
  "regression_risk_areas": ["Module A", "Feature B"],
  "required_tests": [
    {
      "type": "unit|integration|e2e",
      "description": "A description of the test to be added or modified.",
      "target_file": "The file where the test should live."
    }
  ]
}

**Constraints:**
[CONSTRAINTS]: [E.g., 'Do not modify database schemas.', 'All fixes must be backwards compatible.', 'Prioritize the hypothesis with the highest confidence first.']

To adapt this template, replace each square-bracket placeholder with data from your bug tracking system and agent context. The [REPOSITORY_MAP] is critical for grounding the agent; provide a concise summary of the codebase structure. The [TOOLS] list must exactly match the functions your agent harness exposes. The [CONSTRAINTS] section is your primary lever for enforcing safety and policy, such as preventing database changes or requiring human approval for certain file modifications. After the agent returns the JSON plan, your harness should validate it against the schema before allowing the agent to proceed to the execution phase.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Bug Fix Decomposition Prompt. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of incomplete or hallucinated fix plans.

PlaceholderPurposeExampleValidation Notes

[BUG_REPORT]

The raw bug report text, including title, description, steps to reproduce, expected behavior, and actual behavior.

Title: NullPointerException on checkout. Steps: Add item to cart, proceed to checkout. Expected: Order confirmation. Actual: 500 error.

Must be non-empty. Check for minimum length of 20 characters. If the report contains only a title, flag for human enrichment before decomposition.

[REPOSITORY_CONTEXT]

A summary of the relevant codebase structure, including file paths, module boundaries, and key dependencies.

src/checkout/OrderService.java, src/cart/CartManager.java, pom.xml: spring-boot 3.2, junit 5.

Must contain at least one file path. Validate that referenced paths exist in the repository index. If null, the decomposition must include a repository exploration step as its first subtask.

[ERROR_LOGS]

Stack traces, error messages, log excerpts, or monitoring alerts associated with the bug.

java.lang.NullPointerException at com.store.checkout.OrderService.process(OrderService.java:142)

Optional but strongly recommended. If null, the first diagnostic step must be log collection. If provided, validate that the log format matches known application logging patterns.

[AGENT_TOOLS]

The list of tools available to the coding agent, such as file read, search, test runner, or linter.

["read_file", "search_code", "run_tests", "git_diff", "list_directory"]

Must be a valid JSON array of tool names. Each tool must exist in the agent's tool registry. The decomposition must not reference tools outside this list.

[CONSTRAINTS]

Boundary conditions such as files that must not be modified, deployment freezes, or required reviewers.

Do not modify database migration files. All changes require a PR against main. Must pass existing CI pipeline.

Optional. If provided, every subtask must be checked against these constraints. If a subtask violates a constraint, the decomposition is invalid.

[OUTPUT_SCHEMA]

The expected JSON schema for the decomposition output, defining the structure of subtasks, dependencies, and verification steps.

{"root_cause_hypotheses": [], "diagnostic_steps": [], "fix_candidates": [], "verification_steps": [], "regression_tests": []}

Must be a valid JSON Schema or example structure. Validate that the schema includes fields for diagnostic steps before fix steps. Reject schemas that allow fixes without prior diagnosis.

[KNOWN_ISSUES]

Previously identified related bugs, recent changes, or flaky tests in the same area of the codebase.

Related: BUG-1423 Cart session timeout. Recent commit: a1b2c3d refactored OrderService.

Optional. If provided, the decomposition must cross-reference these known issues to avoid duplicate fix plans. Validate that known issue IDs match the project's issue tracker format.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Bug Fix Decomposition prompt into a coding agent's diagnostic and planning pipeline.

The Bug Fix Decomposition prompt is designed to be the first step in a coding agent's fix workflow, transforming an unstructured bug report into a structured, verifiable plan. It should be invoked immediately after a bug is triaged and assigned, before any file is read or edited. The prompt's output is a JSON plan that serves as the contract for downstream execution steps: root-cause investigation, candidate fix location, verification, and regression testing. The harness must enforce that the agent does not skip to code changes before the decomposition is complete and validated.

To integrate this prompt, wrap it in a function that accepts the bug report text, repository context (file tree, recent commits, relevant logs), and any known constraints (e.g., 'do not modify the database schema'). The function should call a capable model (such as GPT-4o or Claude 3.5 Sonnet) with a low temperature (0.0–0.2) to maximize deterministic planning. The output must be parsed as JSON and validated against a strict schema: the plan must contain root_cause_hypotheses (array of objects with hypothesis, evidence, investigation_steps), candidate_fix_locations (array of file paths with reasoning), verification_steps (ordered list of manual or automated checks), and regression_test_requirements (list of test cases to add or run). If parsing fails, retry once with a stronger format instruction; if it fails again, log the raw output and escalate for human review. This is a high-stakes workflow—an incorrect fix plan can introduce new bugs—so never silently proceed with a malformed plan.

After validation, the harness should store the plan as a structured artifact in the agent's state, keyed by the bug ID. Each step in the plan should be executed by a separate tool-calling agent that reads files, runs diagnostic commands, or applies patches, but only within the boundaries defined by the decomposition. Implement a state machine that tracks which investigation steps are complete, which hypotheses are confirmed or rejected, and whether the verification steps pass before marking the fix as resolved. Log every transition, including model inputs, outputs, and tool calls, to enable traceability and post-mortem analysis. Avoid the temptation to let the agent 'fix while investigating'—the decomposition prompt's primary value is enforcing diagnostic discipline before action.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure, types, and validation rules for the JSON output produced by the Bug Fix Decomposition Prompt. Use this contract to build a parser and validator in your agent harness.

Field or ElementType or FormatRequiredValidation Rule

plan_id

string (UUID v4)

Must match UUID v4 regex. Reject if missing or malformed.

bug_report_summary

string

Must be a non-empty string under 500 chars. Must not contradict the [BUG_REPORT] input.

root_cause_hypothesis

object

Must contain 'primary_hypothesis' (string) and 'confidence' (float 0.0-1.0). Reject if confidence is above 0.9 without a 'blocking_evidence' field.

investigation_steps

array of objects

Array length must be >= 1. Each object must have 'step_id' (string), 'action' (string), 'expected_finding' (string), and 'is_blocking' (boolean). Reject if any 'action' is empty.

candidate_fix_locations

array of objects

Array length must be >= 1. Each object must have 'file_path' (string), 'function_or_component' (string), and 'rationale' (string). Reject if any 'file_path' is not a valid relative path.

verification_subtasks

array of objects

Array length must be >= 1. Each object must have 'subtask_id' (string), 'description' (string), and 'depends_on' (array of string step_ids). Reject if any 'depends_on' ID does not exist in 'investigation_steps'.

regression_test_requirements

array of strings

Array length must be >= 1. Each string must describe a specific test case or area. Reject if any string is empty or a generic placeholder like 'test everything'.

fix_sequencing_notes

string

If present, must be under 300 chars. Null is allowed. Reject if it contains instructions to skip verification.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when coding agents decompose bug reports into fix plans, and how to prevent each failure before it reaches execution.

01

Fix Attempt Before Root Cause Isolation

What to watch: The model jumps directly to a candidate fix in the first file it suspects, skipping diagnostic steps. This produces patches that mask symptoms without addressing the underlying bug. Guardrail: Require the output to include a root_cause_hypothesis section with supporting evidence from logs, stack traces, or reproduction steps before any candidate_fix section appears. Validate that the hypothesis references specific code paths, not vague descriptions.

02

Hallucinated File Paths and Code Locations

What to watch: The decomposition references files, functions, or line numbers that do not exist in the repository. The agent invents plausible-sounding paths based on naming conventions rather than actual codebase structure. Guardrail: Pair the prompt with a repository map or file-tree context. Add a post-generation validation step that checks every referenced file path against the actual repo. Flag any path that does not resolve before the plan proceeds to execution.

03

Missing Verification Subtasks

What to watch: The plan includes diagnostic and fix steps but omits verification subtasks such as running the existing test suite, writing a regression test, or confirming the fix resolves the original reproduction case. Guardrail: Add a hard constraint in the output schema requiring a verification_steps array. Each step must specify an observable success condition. Validate that at least one step reproduces the original bug scenario and confirms it no longer occurs.

04

Single-Fix Assumption for Multi-Cause Bugs

What to watch: The decomposition assumes a single root cause and produces a linear fix plan, even when the bug report describes symptoms that could stem from multiple interacting components. Guardrail: Prompt the model to enumerate alternative hypotheses before selecting a primary one. Include a differential_diagnosis section that lists other possible causes and explains why each is less likely. If confidence is low, the plan should branch into parallel investigation subtasks.

05

Ignoring Side Effects and Regression Risk

What to watch: The fix plan changes a shared utility, base class, or configuration without assessing downstream impact. The decomposition treats the change as isolated when it affects multiple callers, tests, or deployment environments. Guardrail: Require an impact_assessment field for each candidate fix that lists affected callers, dependent tests, and configuration surfaces. Add a subtask to run the full test suite, not only the file under change.

06

Ambiguous or Non-Reproducible Bug Descriptions

What to watch: The bug report lacks a clear reproduction case, expected behavior, or environment details. The decomposition proceeds with assumptions that may be wrong, producing a plan that solves a different problem than the reporter experienced. Guardrail: Add a clarification_needed field to the output schema. If the bug report is underspecified, the decomposition should list specific questions before generating fix steps. Gate execution on human answers to those questions.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of a bug fix decomposition plan before allowing a coding agent to execute it. Each criterion targets a known failure mode in automated debugging workflows.

CriterionPass StandardFailure SignalTest Method

Root-Cause Isolation

Plan requires diagnostic evidence collection before any fix attempt

Plan proposes a code change in the first step without a preceding investigation step

Parse the step list; assert that at least one step labeled 'investigation' or 'diagnosis' precedes any step labeled 'fix' or 'patch'

Fix Location Specificity

Every proposed fix step references a specific file path and function or class name

A fix step contains only a module-level or generic description like 'fix the auth bug'

Regex match for file-path patterns and function/class identifiers in each fix step's description field

Verification Subtask Coverage

Plan includes at least one verification step per proposed fix that confirms the bug is resolved

A fix step has no corresponding verification step that references the same bug ID or symptom

Count fix steps and verification steps; assert count(verification_steps) >= count(fix_steps) and each fix has a linked verification

Regression Test Requirement

Plan explicitly requests addition or update of at least one automated regression test

Plan contains no mention of test addition, test update, or regression coverage

Keyword scan for 'test', 'spec', 'regression', 'assert' in the plan's test-related steps; assert at least one match

Dependency Ordering Validity

All steps respect prerequisite relationships: diagnosis before fix, fix before verification, verification before close

A verification step appears before its corresponding fix step in the execution order

Build a dependency graph from step IDs and prerequisite fields; run topological sort and assert no ordering violations

Scope Containment

Plan addresses only the reported bug and does not propose unrelated refactors, feature additions, or style changes

Plan includes steps labeled 'refactor', 'cleanup', 'optimize', or 'add feature' that are not required to fix the bug

Keyword filter on step descriptions; flag any step with non-fix intent keywords; require explicit justification if present

Rollback and Safety

Plan includes a rollback or revert strategy for each irreversible change, or explicitly states that changes are safely reversible

Plan proposes a database migration, API change, or config update with no rollback step and no reversibility note

Scan for high-risk action keywords ('migration', 'schema change', 'API change'); assert each has a paired rollback step or an explicit 'reversible: true' annotation

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model and minimal validation. Focus on getting a reasonable decomposition before adding strict schema enforcement. Replace the structured output schema with a looser markdown format if you're iterating in a chat UI.

code
Analyze the following bug report and produce a diagnostic and fix plan.

Bug Report:
[BUG_REPORT]

Repository Context:
[REPO_CONTEXT]

Produce a plan with:
- Root-cause investigation steps
- Candidate fix locations
- Verification subtasks
- Regression test requirements

Watch for

  • Plans that jump to fixes without isolating the root cause first
  • Missing verification steps that would catch an incomplete fix
  • Overly broad investigation steps that don't reference specific files or logs
  • No distinction between diagnostic steps and fix steps
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.