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.

BeginnerIntermediateExpert · 11 min read · Last updated:

In short

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.

Versions used

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.

Beginner Ask well

Write a task an agent can finish

WeakStrong
"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:

  1. Goal: what should be true afterward.
  2. Evidence: how to tell, ideally a command.
  3. Scope: what may change and what must not.
  4. Context: related files, earlier attempts, the reason behind the request.
  5. Stop rule: when to ask instead of continuing.

Choose a suitable size

Good first tasksKeep a person closely involved
A reproducible bugArchitecture decisions
Missing tests for existing behaviorAuthentication and payment code
Mechanical migrations with good checksData migrations that cannot be undone
Documentation that can be verified against codeVague performance complaints
The one-sentence test

If you cannot say in a sentence how you will know it worked, the task needs more thought before an agent gets it.

Intermediate From issue to pull request

The path

1. Understandread the issue and related code; ask questions
2. Plana person approves anything non-trivial
3. Reproducea failing test or script
4. Changesmallest edit that solves it
5. Verifyall checks, on a clean copy
6. Proposepull request with evidence; a person merges
StageOutputStop if
UnderstandRestatement and open questionsThe request contradicts the code or itself
PlanFiles to change, approach, risksThe change is much larger than expected
ReproduceA check that fails for the right reasonThe problem cannot be shown
ChangeA focused diff on a branchIt needs forbidden files or new access
VerifyCommand outputUnrelated checks fail
ProposeDescription, evidence, limitationsNothing: 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 codeWhat it prevents
Reproduce before fixing"Fixing" a problem that was never observed
Run the whole suiteA patch that cures one case and breaks another
Fingerprint the testsMaking the check agree with the bug
Undo failed attemptsHalf-applied ideas piling up
Fixed number of triesEndless, expensive wandering
Passing is not proof

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 smellAsk
"Refactor as needed"Which files, and why?
No verification stepWhat command will show it works?
Many unrelated changesCan these be separate proposals?
Assumptions stated as factsWhere in the code did you confirm that?

Test-driven work with an agent

  1. Describe the behavior with examples, including edge cases.
  2. Ask for tests only. Read them: they are now your specification.
  3. Run them and confirm they fail for the expected reason.
  4. Commit the tests.
  5. Ask for the implementation, with the tests off limits.
  6. 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

StepAsk the agent to
ObserveQuote the exact error, input and environment
ReproduceWrite the smallest script that fails
HypothesizeList likely causes and how to tell them apart
Test oneAdd a log line or assertion; change nothing else
FixAddress the cause, not the symptom
GuardKeep 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

WorkflowStepsEvidence to require
Exploring unfamiliar codeAsk for the entry points and the path of one requestFile and line references you can open
Dependency upgradeRead release notes, upgrade one package, fix, testNotes consulted, test output, lock file diff
Writing documentationGenerate from code, then run every exampleCommand output for the examples
Mechanical migrationConvert one case by hand, then apply in batchesPassing checks per batch and a list of skipped cases
Incident investigationGather logs and recent changes, propose causesThe 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.

Advanced Background and automated work

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

SignResponse
Same fix attempted repeatedlyStop, add information, restart with a fresh session
Diff grows far beyond the taskDiscard, narrow the scope
Tests edited or skippedReject and make them read-only
Confident claim without outputAsk for the command and its result
New dependency appearsVerify it exists, is maintained and is needed
Correct but unreadable codeAsk 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

MomentUseful 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 problemLasting fix
Wrong commands usedPut them in the instruction file
Convention ignoredAdd a lint rule
Same area breaksAdd tests there
Forbidden file touchedEnforce with permissions or pipeline rules
Vague issuesIssue 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

MistakeBetter
One giant taskA sequence of small, verifiable ones
Skipping the reproductionMake failure visible first
Approving a plan unreadCheck the files and risks listed
Treating a green build as reviewRead the diff
Letting the agent merge its own workRequire 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