Issue-to-Pull-Request, Debugging and TDD Workflows
Good results come from a good process: a clear task, a reproduced problem, small steps and proof that a reviewer can check.
Give the agent a clear task with a way to check success. Have it explore and propose a plan, reproduce the problem as a failing test, make the smallest change that passes, run every check and open a pull request that shows its evidence. A person reviews and merges. If the agent cannot reproduce or verify, it should stop and say so.
What you will learn: how to brief an agent, a stage-by-stage path to a pull request, test-driven and debugging routines, a runnable acceptance loop and how to handle work that goes wrong.
Prerequisites: Coding Agent Architecture and Code Understanding and everyday use of version control.
Written in November 2026. The example uses only the Python standard library; the "model" in it is a fixed list of proposals so the behavior is repeatable.
Write a task an agent can finish
| Weak | Strong |
|---|---|
| "Fix the totals bug." | "A price of 19.99 gives a total of 19.98. Add a test that shows it, then fix it." |
| "Improve the search page." | "Search should ignore letter case. Keep the public function names." |
| "Add logging." | "Log failed payments with order id and error code. Never log card data." |
| "Upgrade the library." | "Move to the next major version, follow its migration guide and keep all tests passing." |
A useful brief has five parts:
- Goal: what should be true afterward.
- Evidence: how to tell, ideally a command.
- Scope: what may change and what must not.
- Context: related files, earlier attempts, the reason behind the request.
- Stop rule: when to ask instead of continuing.
Choose a suitable size
| Good first tasks | Keep a person closely involved |
|---|---|
| A reproducible bug | Architecture decisions |
| Missing tests for existing behavior | Authentication and payment code |
| Mechanical migrations with good checks | Data migrations that cannot be undone |
| Documentation that can be verified against code | Vague performance complaints |
If you cannot say in a sentence how you will know it worked, the task needs more thought before an agent gets it.
The path
| Stage | Output | Stop if |
|---|---|---|
| Understand | Restatement and open questions | The request contradicts the code or itself |
| Plan | Files to change, approach, risks | The change is much larger than expected |
| Reproduce | A check that fails for the right reason | The problem cannot be shown |
| Change | A focused diff on a branch | It needs forbidden files or new access |
| Verify | Command output | Unrelated checks fail |
| Propose | Description, evidence, limitations | Nothing: always report, even failure |
A loop that accepts only evidence
The script below creates the small shop project from Coding Agent Architecture and Code Understanding (save sample.py from that page beside this file). Its test suite contains a failing case. Three proposed fixes arrive in turn.
"""An issue-to-patch loop that only accepts evidence. The 'model' is scripted."""
import hashlib
import subprocess
import sys
import tempfile
from pathlib import Path
import sample
TARGET = "shop/money.py"
OLD = "return int(amount * 100)"
# What a model might propose, in order. Two of these are traps.
PROPOSALS = [
("add one cent", TARGET, OLD, "return int(amount * 100) + 1"),
("edit the failing test", "tests/test_cart.py", "1999)", "1998)"),
("round to nearest cent", TARGET, OLD, "return round(amount * 100)"),
]
def run_tests(root):
done = subprocess.run(
[sys.executable, "-B", "-m", "unittest", "discover", "-s", "tests", "-t", "."],
cwd=root, capture_output=True, text=True, timeout=30)
summary = done.stderr.strip().splitlines()[-1]
return done.returncode == 0, summary
def fingerprint(root):
return {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted((root / "tests").glob("*.py"))}
with tempfile.TemporaryDirectory() as folder:
root = sample.create(folder)
(root / "tests/__init__.py").write_text("")
passed, summary = run_tests(root)
print("reproduce :", "tests pass" if passed else summary)
assert not passed, "cannot fix what we cannot reproduce"
protected = fingerprint(root)
for attempt, (idea, name, old, new) in enumerate(PROPOSALS, 1):
path = root / name
before = path.read_text()
path.write_text(before.replace(old, new, 1))
if fingerprint(root) != protected:
verdict = "refused: tests are read-only in this task"
else:
passed, summary = run_tests(root)
verdict = "accepted" if passed else f"rejected: {summary}"
print(f"attempt {attempt} : {idea:22} -> {verdict}")
if verdict == "accepted":
break
path.write_text(before) # always undo a failed try
else:
print("stopped: no proposal passed, hand back to a person")
Output:
reproduce : FAILED (failures=1)
attempt 1 : add one cent -> rejected: FAILED (failures=1)
attempt 2 : edit the failing test -> refused: tests are read-only in this task
attempt 3 : round to nearest cent -> accepted
| Rule in the code | What it prevents |
|---|---|
| Reproduce before fixing | "Fixing" a problem that was never observed |
| Run the whole suite | A patch that cures one case and breaks another |
| Fingerprint the tests | Making the check agree with the bug |
| Undo failed attempts | Half-applied ideas piling up |
| Fixed number of tries | Endless, expensive wandering |
Rounding passes these tests, but a real money system should use decimal types or whole cents from the start, and decide how half cents round. A reviewer still has to ask whether the fix is right, not only green. The file fingerprint also covers only test files; configuration that changes how tests run needs protecting too.
What a reviewable plan looks like
Goal totals correct to the cent
Cause to_cents truncates a floating-point result (shop/money.py)
Change round to nearest cent; add a test for 19.99
Not doing converting prices to decimal types
Risk callers that relied on truncation; I found none besides the cart
Check run the full test suite before and after
Question should stored totals be corrected too?
Read a plan for what is missing. Does it name the files? Does it say how success will be checked? Has it noticed the callers? Correct the plan before any code exists, and ask the agent to say when it departs from it.
| Plan smell | Ask |
|---|---|
| "Refactor as needed" | Which files, and why? |
| No verification step | What command will show it works? |
| Many unrelated changes | Can these be separate proposals? |
| Assumptions stated as facts | Where in the code did you confirm that? |
Test-driven work with an agent
- Describe the behavior with examples, including edge cases.
- Ask for tests only. Read them: they are now your specification.
- Run them and confirm they fail for the expected reason.
- Commit the tests.
- Ask for the implementation, with the tests off limits.
- Ask for cleanup while the tests stay green.
The important moment is step two. An agent that writes both the code and the tests in one pass can encode the same misunderstanding in both.
Debugging routine
| Step | Ask the agent to |
|---|---|
| Observe | Quote the exact error, input and environment |
| Reproduce | Write the smallest script that fails |
| Hypothesize | List likely causes and how to tell them apart |
| Test one | Add a log line or assertion; change nothing else |
| Fix | Address the cause, not the symptom |
| Guard | Keep a regression test and remove temporary logging |
Watch for fixes that hide the symptom: a broad exception handler, a retry around a logic error, a longer timeout, or a special case for the test input.
Other everyday workflows
| Workflow | Steps | Evidence to require |
|---|---|---|
| Exploring unfamiliar code | Ask for the entry points and the path of one request | File and line references you can open |
| Dependency upgrade | Read release notes, upgrade one package, fix, test | Notes consulted, test output, lock file diff |
| Writing documentation | Generate from code, then run every example | Command output for the examples |
| Mechanical migration | Convert one case by hand, then apply in batches | Passing checks per batch and a list of skipped cases |
| Incident investigation | Gather logs and recent changes, propose causes | The observation that supports each cause; see Debugging Agents, RAG and Handoffs |
Read-only workflows, such as exploring code or investigating an incident, are the safest place for a team to start: mistakes cost reading time, not repairs.
A pull request a reviewer can trust
## What and why
Totals were one cent short for some prices (issue 214).
## Change
shop/money.py: round to the nearest cent instead of truncating.
## Evidence
Before: 1 failing test (19.99 gave 1998).
After: python -m unittest discover -s tests: all pass.
## Not covered
Half-cent inputs. Existing stored totals are not corrected.
## Please check
Whether prices should become decimals throughout.
Ask for the "not covered" and "please check" sections explicitly. They turn a confident summary into something a reviewer can act on.
Running tasks in the background
- Each task starts from a clean copy on its own branch.
- Setup is scripted, so the agent does not improvise its environment.
- Time, cost and attempt limits end the task with a report.
- Credentials are short-lived and limited to this repository and task.
- The agent can open a proposal but cannot merge or deploy.
- Questions reach a person, and the task pauses instead of guessing.
When a task is triggered by an issue or comment, anyone who can write there is supplying input to your agent. Read Sandboxes, Safety and Security for Coding Agents before connecting those triggers. For long-running orchestration, see Durable Execution, Checkpoints and Approvals.
When it goes wrong
| Sign | Response |
|---|---|
| Same fix attempted repeatedly | Stop, add information, restart with a fresh session |
| Diff grows far beyond the task | Discard, narrow the scope |
| Tests edited or skipped | Reject and make them read-only |
| Confident claim without output | Ask for the command and its result |
| New dependency appears | Verify it exists, is maintained and is needed |
| Correct but unreadable code | Ask for simplification, with tests unchanged |
Reverting is cheap on a branch. Repairing a long, confused session is often slower than starting again with what you learned.
Steering during a session
| Moment | Useful instruction |
|---|---|
| Before the first edit | "Tell me which files you will change and why." |
| It makes an assumption | "Show me where the code confirms that." |
| It drifts into cleanup | "Note it for later. Finish the original task." |
| A check fails | "Quote the failure and explain it before changing anything." |
| It proposes a workaround | "What is the root cause, and why not fix that?" |
| Before finishing | "List what you did not verify." |
Interrupt early. A correction after two steps costs little; the same correction after thirty steps often means discarding the work. Between tasks, write down decisions you made in conversation, because the next session will not remember them.
Is the workflow working?
Keep a light record for a few weeks: the task type, whether the proposal was merged, how long review took, how many corrections were needed and whether anything failed afterward. Compare task types, not only overall totals. You will usually find some kinds of work where the agent helps clearly and others where writing it yourself is faster. Code Review, Refactoring and Quality Measures shows how to calculate these measures.
Improve the process, not only the prompt
When the same problem recurs, fix it where it will stay fixed:
| Recurring problem | Lasting fix |
|---|---|
| Wrong commands used | Put them in the instruction file |
| Convention ignored | Add a lint rule |
| Same area breaks | Add tests there |
| Forbidden file touched | Enforce with permissions or pipeline rules |
| Vague issues | Issue template with evidence and scope |
Definition of done
- The original problem was reproduced and no longer occurs.
- All checks pass on a clean copy, with the output attached.
- The diff contains only changes the task needs.
- No test, lint rule or security check was weakened.
- Documentation and examples match the new behavior.
- Limitations and open questions are written down.
- A named person has reviewed and approved the change.
A reusable task template
Goal: what should be true when you finish
Shows it: command to run and the expected result
In scope: folders or files you may change
Leave alone: files, interfaces and behavior that must not change
Background: related issue, earlier attempts, decisions already made
Ask first: new dependencies, schema changes, anything irreversible
Finish with: diff summary, command output, what you did not verify
Save the template in the repository and shorten it for small jobs. The two lines people skip most often, "shows it" and "leave alone", are the ones that prevent the most rework.
Common mistakes
| Mistake | Better |
|---|---|
| One giant task | A sequence of small, verifiable ones |
| Skipping the reproduction | Make failure visible first |
| Approving a plan unread | Check the files and risks listed |
| Treating a green build as review | Read the diff |
| Letting the agent merge its own work | Require another approver |
Questions people ask
Should the agent always plan first?
For a one-line change it adds little. For anything touching several files or unfamiliar code, reading a plan is much cheaper than reviewing a wrong diff.
What if there are no tests?
Start by having the agent write tests that record current behavior, review them, then make the change. A script that demonstrates the problem is a good first step.
How many attempts are reasonable?
Set a small limit and tune it from your records. Repeated failures usually mean missing information, which more attempts will not supply.
Who is responsible for the merged code?
Your normal accountability applies: the people who approve and release it. Make that explicit in your team's rules.
References
Next steps
Code Review, Refactoring and Quality Measures
Review and measure the results.
Sandboxes, Safety and Security for Coding Agents
Sandboxes and pipeline risks.
Agent Dev Teams, OpenHands and Private Coding Agents
Run several agents without collisions.