# Address PR Review Comments

You authored a pull request (typically via `agdt-initiate-work-on-jira-issue-workflow`) and it
has received review comments. Evaluate each comment on its merits, implement the **best** solution
for the valid ones, capture any durable lessons, push, then reply to and resolve every thread.

The pull-request or review URL is provided as input. If no URL is provided, stop and ask for one.

Follow each phase in order. Do not skip the evaluation rigor or the sequential-delegation rules.

---

## Tooling Priority

**Always prefer `agdt-*` commands** over raw git or raw API calls. They provide centralized
state, consistent formatting, background-task tracking, and dry-run safety.

| Operation | Azure DevOps | GitHub |
|-----------|--------------|--------|
| Fetch review threads/comments | `agdt-get-pull-request-threads --pull-request-id {pull_request_id}` (then `agdt-task-wait`) | No `agdt-*` fetch command exists yet for GitHub PR review-comment bodies. Document the tooling gap and request an exported input containing `id`, `pull_request_review_id`, `path`, `line`, `body`, `in_reply_to_id`, and `diff_hunk`. |
| Reply to a thread/comment | `agdt-reply-to-pull-request-thread` (then `agdt-task-wait`; set `resolve_thread true` to reply + resolve) | `agdt-gh-reply-to-review-comments` *(requires a review ID; run per `pull_request_review_id` if needed)* |
| Resolve a thread | `agdt-resolve-thread` (then `agdt-task-wait`) | `agdt-gh-resolve-review-threads` *(use `--comment-ids` when you don’t have a single review ID)* |
| Stage + commit/amend + push | `agdt-git-save-work` (then `agdt-task-wait`) | `agdt-git-save-work` (then `agdt-task-wait`) |

---

## Phase 1 — Fetch Every Review Thread/Comment

Start by extracting the provider-specific PR identifier from the URL (`{owner}/{repo}` +
`{pr_number}` on GitHub; `pull_request_id` on Azure DevOps).

Retrieve **all** review threads/comments for that PR. Handle pagination so none are missed. On
GitHub, treat the parent review comments (`in_reply_to_id == null`) as the review-thread anchors
you will later reply to and resolve; child comments are existing replies and should be kept as
context only. For each item, capture the **comment/thread ID** (GitHub `id`, Azure DevOps
`thread_id`), file path, line, body, and surrounding diff context (GitHub: also capture
`pull_request_review_id` and `in_reply_to_id` for reply batching and parent/reply distinction).
Read child comments for context. Use **parent** comment IDs for replies, and prefer parent comment
IDs for resolve targets (allow any comment ID in the same thread only when a parent ID is not
available).

For GitHub, if review comments are not already provided as structured input, stop and report the
tooling gap (no `agdt-*` fetch command yet for GitHub review-comment bodies), then request an
exported input with `id`, `pull_request_review_id`, `path`, `line`, `body`, `in_reply_to_id`, and
`diff_hunk`.

---

## Phase 2 — Read Code Context

For each comment, read the referenced file in the working tree to understand the current state of
the code around the comment. **Understand before acting** — do not rush to change code you have
not read.

---

## Phase 3 — Evaluate Each Comment

Classify every comment and assign a confidence level.

| Decision | Criteria |
|----------|----------|
| Valid | The feedback is correct and a change will improve the code |
| Partially valid | Some of the feedback is correct; part is not |
| Invalid | False positive, already handled, out of scope, or subjective preference |

| Confidence | Meaning |
|------------|---------|
| High | Clearly correct; the fix is unambiguous |
| Medium | Reasonable but has trade-offs or uncertainty |
| Low | Subjective, context-dependent, or possibly wrong |

Principles:

- **Bias toward preserving working code.** The burden of proof is on the suggestion. If the
  existing code is correct and the comment is stylistic, lean toward Invalid.
- **Scope guard** — only consider changes to files already in this PR's diff.
- **Read intent** — a reviewer can be technically right about a pattern yet miss the local
  context; use the diff to understand what changed and why.

---

## Phase 4 — Determine the Best Solution

For every Valid or Partially-valid comment, **do not blindly accept the suggested fix.** Think
deeply and evaluate the relevant codebase to determine the **best possible** solution — which may
differ from what the reviewer proposed. Prefer the solution that is correct, minimal, and
consistent with existing conventions.

---

## Phase 5 — Implement

Apply the best solutions from Phase 4. Touch only files within the PR's scope, and keep the PR's
original goal intact.

---

## Phase 6 — Capture Durable Lessons (Documentation)

If addressing these comments surfaced a lesson that would help a **class** of future changes (not a
one-off detail), record it so it is not re-learned every time. **Only document generalizable
lessons — do not bloat the docs with trivia.** Only **add** to documentation homes — never delete
or overwrite existing instruction files.

### Documentation homes

Choose the most appropriate home, using GitHub's
[repository custom-instruction mechanisms](https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions):

- **Repository-wide** → `.github/copilot-instructions.md` (applies to every Copilot request in the repo).
- **Path / area-specific** → a path-specific instructions file under `.github/instructions/` named
  `NAME.instructions.md`, with YAML frontmatter `applyTo:` set to one or more comma-separated globs
  (e.g. `applyTo: "agentic_devtools/cli/**/*.py"`). These **stack on top of** the repo-wide file and
  are read by **both Copilot code review and the cloud agent**; add `excludeAgent: "code-review"` or
  `excludeAgent: "cloud-agent"` to scope to one consumer.
- **Agent-facing** → the nearest `AGENTS.md` in the directory tree (nearest wins), or a root
  `CLAUDE.md` / `GEMINI.md`.

### A. For future implementing agents

These are agents started via `agdt-initiate-work-on-jira-issue-workflow`. Add concise guidance to
the **most specific** home that applies: a path-specific `.github/instructions/NAME.instructions.md`
whose `applyTo` glob matches the code; the nearest `copilot-instructions.md` / `AGENTS.md`; or a
shared conventions doc such as `docs/development/code-change-guidance.md` or
`docs/development/codebase-conventions.md` (create one only if a shared home is genuinely warranted
and none already fits).

### B. For future reviewing agents

These are agents started via `agdt-initiate-pull-request-review-workflow` (and GitHub Copilot code
review). Append the lesson to the repo's **review focus-areas** file — resolve the path from
`.github/agdt-config.json` → `review.focus-areas-file`. If that key is not configured, prefer adding
and configuring a repo-local focus areas file (for example `.github/review-focus-areas.md`). And/or add a path-specific
`.github/instructions/NAME.instructions.md` whose `applyTo` glob matches the relevant code (Copilot
code review reads these from the PR base branch), and/or reinforce the concept in the most specific
doc that applies.

---

## Phase 7 — Save Your Work

1. Stage, amend, rebase, and push in one step:

   ```bash
   agdt-git-save-work
   agdt-task-wait
   ```

   This amends the existing single commit (keeping the PR at one commit), rebases onto `main`,
   and force-pushes. Update the commit message if the scope changed
   (`--overwrite-commit-message-title "..."` for the title; edit `commit-body.md` for the body).

2. **Push-fix-push loop** — if a pre-push hook rejects the push, read `.pre-push-output.log`
   (and `check-output-condensed.txt` if present), fix the issues, and re-run `agdt-git-save-work`.
   Never bypass with `--no-verify`. See `.github/instructions/pre-push-hook.instructions.md`.

3. **Verify the push landed** — confirm the remote head SHA now matches your local commit
   **before** you reply that a thread was `addressed in <short-sha>`:

   ```bash
   agdt-gh-pr-state --pr {pr_number} --repo {owner}/{repo}   # GitHub: compare github.head_ref_oid to your local SHA
   git rev-parse HEAD
   ```

   On Azure DevOps, confirm the PR's latest commit matches your local `HEAD`.

---

## Phase 8 — Reply to and Resolve Every Unresolved Thread

For **each** unresolved thread/comment, post a reply explaining the outcome, then resolve it:

- For implemented comments, reference the commit and note if your solution **differs** from the
  suggestion and why.
- For Invalid comments, explain clearly why no change was made.

Use the provider's `agdt-*` reply/resolve commands from the Tooling Priority table. On Azure
DevOps you can reply and resolve in one call by setting `resolve_thread true`.

For GitHub, group the **parent** review comments (`in_reply_to_id == null`) by
`pull_request_review_id` (captured in Phase 1). For each unique `pull_request_review_id`, create
a separate replies JSON file containing only the reply payloads **you** plan to send for that
review's parent comments. Use those parent comment IDs for resolving too; if needed, you may pass a
reply comment ID that belongs to the same thread:

```json
[
  {
    "commentId": 123456789,
    "body": "Addressed in <short-sha>."
  }
]
```

```bash
# Repeat once per unique pull_request_review_id (from Phase 1):
agdt-gh-reply-to-review-comments --pr {pr_number} --repo {owner}/{repo} \
  --review-id {pull_request_review_id} --replies-file ./replies-{pull_request_review_id}.json
agdt-gh-resolve-review-threads --pr {pr_number} --repo {owner}/{repo} \
  --comment-ids {comment_id_1},{comment_id_2}
```

> **⚠️ CRITICAL — Delegate reply/resolve work SEQUENTIALLY, never in parallel.**
>
> If you hand the reply/resolve work to subagents, run them **strictly one at a time** — each
> subagent must fully complete before the next one starts. **Never run them in parallel.**
>
> All `agdt-*` commands share a single per-worktree `state.json`. Parallel subagents each call
> `agdt-set thread_id ...` / `agdt-set content ...` concurrently and **overwrite each other's
> state**, which posts replies to the wrong threads or drops them entirely. The safest approach is
> to **do the replies yourself in a sequential loop** rather than delegating them at all.

---

## Phase 9 — Recap

Give a structured recap:

- A table of each comment: id, file, decision (valid/partial/invalid), confidence, what you did
  and the best-solution rationale, commit.
- The final commit SHA and the PR link.
- Anything left for a human to handle.
