Claude Code Root-Cause Bug Investigation with Failing Test and Minimal Patch

Directs Claude Code to reproduce a bug, trace it to a root cause using repository evidence, write a failing regression test, and apply the smallest safe fix. Ends with a verified diff, risks, and next actions.

You get: Working code with an explanation

More like this

The prompt

claude-code-root-cause-bug-investigation-with-failing-test-and-minimal-patch.md
Role: You are Claude Code acting as a senior debugging engineer working inside the repository at {repo_path}. You investigate before you edit, and you only report results you actually observed.

Context: A defect has been reported. The decision this work supports is whether the fix is safe to merge now, needs more investigation, or should be escalated. Read CLAUDE.md, README, and contributing docs first to learn build, test, lint, and style conventions.

Task: Reproduce the bug, identify the root cause, add a failing regression test, implement the minimal fix, and verify it.

Inputs (ask for anything missing before editing; list assumptions separately):
- Bug description: {bug_description}
- Expected behavior: {expected_behavior}
- Actual behavior and error output: {actual_behavior}
- Reproduction steps or failing command: {repro_command}
- Suspected area (optional): {suspected_area}
- Test command: {test_command}
- Files or directories that must not change: {protected_paths}

Constraints:
- Do not edit code until you have stated a hypothesis and the evidence for it.
- Use Grep, Glob, and Read to trace the call path. Use Bash only for reproduction, tests, git log, and git blame.
- Never claim a test passed unless you ran it in this session. If you cannot run it, say so and give the exact command for the user.
- Keep the diff minimal. No drive-by refactors, formatting churn, or dependency changes.
- Do not touch secrets, .env files, or {protected_paths}.
- Ask before running destructive or networked commands.

Workflow:
1. Restate the bug and list assumptions and missing information.
2. Reproduce: run {repro_command}. Record the exact output. If it does not reproduce, stop and report what you tried.
3. Trace: map the execution path from entry point to failure. Form at most three ranked hypotheses with file:line evidence.
4. Falsify: run a targeted check (log, assertion, or narrow test) to eliminate hypotheses until one remains.
5. Write a regression test that fails for the right reason. Run it and confirm failure.
6. Implement the smallest fix. Re-run the regression test, then the nearest related test suite, then {test_command}.
7. Check git log and git blame on the changed lines for prior intent, and search for sibling code with the same flaw.
8. Review git diff for scope creep.

Output format:
## Summary (3 sentences max)## Assumptions and Missing Information
## Reproduction Evidence (command, output)
## Root Cause (file:line, mechanism, why it was missed)
## Hypothesis Table (hypothesis | evidence | verdict)
## Changes Made (table: file | change | reason)
## Verification (command | result | actually run: yes/no)## Risks and Side Effects
## Merge Recommendation (merge / needs work / escalate, with reason)
## Next Actions (ordered checklist)

Acceptance criteria:
- The bug is reproduced before the fix and not reproduced after it, with output shown.
- A regression test fails before the fix and passes after it.
- The diff touches only files needed for the fix.
- The root cause is explained with file and line references, not guesses.
- Every verification claim is marked as run or not run.

Quality checks before finishing:
- Did I confirm the test fails for the intended reason?
- Did I search for the same pattern elsewhere?
- Are there untested edge cases, such as null input, concurrency, or large data?
- Is anything in my report inferred rather than observed? Label it as inferred.

Example output

AI-written example

Summary

Mid-month upgrades in February 2024 were prorated against a 28-day month because proration.py uses a hardcoded days-per-month table. I replaced the table lookup with calendar.monthrange and added a regression test that failed before the fix and passes after it. The full suite passes, and I recommend merging.

Assumptions and Missing Information

  • Assumed proration should use the calendar days of the billing period's start month (confirmed by docs/billing.md, line 22).
  • Assumed legacy/ is protected, per protected_paths. I did not touch it.
  • Missing: whether invoices already issued for Feb 2024 need correction. This is outside the code change.

Reproduction Evidence

$ pytest tests/test_proration.py::test_upgrade_feb_2024 -q
E   assert Decimal('10.71') == Decimal('10.34')
1 failed in 0.18s

Expected: 15/29 of $20.00 = $10.34. Actual: 15/28 of $20.00 = $10.71.

Root Cause

billing/proration.py:41: DAYS_IN_MONTH[period_start.month] returns 28 for February regardless of year. The table was added in the initial commit and never year-aware. The existing tests only covered 2023, so the bug was missed.

Hypothesis Table

HypothesisEvidenceVerdict
Hardcoded February lengthproration.py:41; a debug print showed days=28Confirmed
Off-by-one in remaining-days calculationproration.py:44; the 15 remaining days are correctRejected
Decimal rounding modeproration.py:48; the result matches ROUND_HALF_UP for 15/28Rejected

Changes Made

FileChangeReason
billing/proration.pyUse calendar.monthrange instead of the tableLeap-year correctness
tests/test_proration.pyAdd test_upgrade_feb_2024 and test_upgrade_feb_2023Regression coverage
--- a/billing/proration.py
+++ b/billing/proration.py
@@ -1,4 +1,5 @@
+import calendar
 from decimal import Decimal, ROUND_HALF_UP
@@ -38,7 +39,7 @@ def prorate(plan_price, period_start, change_date):
Generated from this prompt by AI. Your results will vary.

Tips and common edits

Run from the repository root in Claude Code. Provide a concrete repro command when possible; the prompt performs best with a deterministic failure. For large repos, ask Claude Code to use subagents for parallel searches. Review the Verification table to confirm which commands were actually executed.

Questions about this prompt

More in Claude Code

Failing Test First Bug Fix

Reproduces a bug with a failing test, finds the root cause, applies the smallest fix and shows the test passing.

Cursor Agent Bug Triage: Reproduce, Root-Cause, Fix, and Regression Test

Guides Cursor Agent through reproducing a bug, isolating the root cause with evidence, applying a minimal diff, and adding a regression test, ending with a verification checklist and risks.

Claude Code Behavior-Preserving Refactor with Characterization Tests and Staged Commits

Guides Claude Code to refactor a module safely by first pinning current behavior with characterization tests, then applying small reversible steps with verification after each. Delivers a diff, risk register, and rollback plan.

Claude Code Feature Implementation Plan and Build from a Ticket with Repo Convention Discovery

Has Claude Code investigate how similar features are built in the repository, produce an implementation plan with acceptance tests, then implement it in verified increments. Surfaces risks, open questions, and next actions before and after coding.

Debug an Error From the Message and the Code Around It

Finds the most likely cause of an error from the message and the relevant code, ranks other possible causes, and gives the smallest fix plus a way to prove it worked.

Root Cause Analysis from Stack Trace and Logs

Turns an error report, stack trace, and logs into ranked root-cause hypotheses. Includes the cheapest checks to confirm each one, a fix proposal, and a regression test plan.

Agent Run Post-Mortem: Trace Root Cause and Prompt or Tool Fixes

Analyzes a pasted agent trace to find the first real failure and proposes exact prompt rewrites or tool changes, each with a test.

Characterization Tests Before a Refactor

Writes tests that lock in a module's current behavior, including edge cases and quirks, so you can refactor safely.

Checkpoint and Rollback Manager with Compensation Steps and Failure Injection Tests

Guides Claude Code to implement checkpoint snapshots, rollback modes, and compensating actions for side-effecting agent phases, then prove them with failure-injection tests. Helps you decide the rollback strategy per phase.

Claude Code Hook Writer: Auto-Run Lint, Typecheck or Tests After Edits

Produces a PostToolUse hook entry for settings.json, the script it calls and a concrete procedure to test that the check runs after file edits.

Claude Code Plan-Then-Implement a Feature With Approval Checkpoints

Makes Claude Code explore the repo, write a step-by-step plan for your approval, then build the feature in small verified steps, stopping at each checkpoint for your go-ahead.

Codebase Tour for a Specific Task

Explores a repo through the lens of your task and explains the architecture, key files and data flow, then says where to start.