# PR Review Iteration

You are iterating on PR #{PR_NUMBER} to address review feedback automatically.

## Your Process

### 1. Fetch Latest Reviews and Status Checks

**CRITICAL ORDER:**
1. **CI Status FIRST** - Check GitHub Actions before reviews
2. **Bot Reviews SECOND** - Check both copilot and claude bots explicitly
3. **Human Reviews THIRD** - Check human reviewer feedback

Gather all review feedback and CI status from multiple sources:

```bash
# ============================================================================
# STEP 1: CI/CD Status (CHECK FIRST - HIGHEST PRIORITY)
# ============================================================================

# Get check status summary
gh pr checks {PR_NUMBER}

# Get detailed check-run information including logs
gh api repos/{owner}/{repo}/commits/$(gh pr view {PR_NUMBER} --json headRefOid -q .headRefOid)/check-runs

# ============================================================================
# STEP 2: Bot Reviews (CHECK BOTH BOTS EXPLICITLY)
# ============================================================================

# ⚠️ CRITICAL: Check BOTH bot reviewers
# Fetch bot comments with timestamp filtering

# Get copilot bot comments created after LAST_CHECK
gh api repos/{owner}/{repo}/issues/{PR_NUMBER}/comments \
    --jq '[.[] | select(.user.login == "copilot-pull-request-reviewer[bot]") | select(.created_at > "$LAST_CHECK")]'

# Get claude bot comments created after LAST_CHECK
gh api repos/{owner}/{repo}/issues/{PR_NUMBER}/comments \
    --jq '[.[] | select(.user.login == "claude[bot]") | select(.created_at > "$LAST_CHECK")]'

# ============================================================================
# STEP 3: Human Reviews
# ============================================================================

# Get PR reviews (APPROVED, CHANGES_REQUESTED, COMMENTED)
gh pr view {PR_NUMBER} --json reviews -q '.reviews'

# Get review comments (line-specific code comments)
gh api repos/{owner}/{repo}/pulls/{PR_NUMBER}/comments

# Get issue comments (general PR discussion)
gh api repos/{owner}/{repo}/issues/{PR_NUMBER}/comments
```

### 2. Analyze All Feedback (CI First, Then Reviews)

**CRITICAL ORDER OF ANALYSIS:**
1. **CI failures** - MUST be fixed first, blocks merge
2. **Critical human reviews** - Security, bugs, breaking changes
3. **CI warnings** - Even if checks passed, address warnings
4. **High/medium reviews** - Architecture, testing, design
5. **Low/nitpick reviews** - Style, formatting, documentation

**CRITICAL:** Address ALL feedback, including nitpicks. No feedback is too trivial.

For CI status checks:

- **Check if ALL status checks passing**:
  - If ANY failing: Fix BEFORE addressing review comments
  - Priority: Tests > Build > Linting > Type checking > Other

- **For failing checks**:
  - Read FULL logs via check-runs API
  - Identify root cause (not just symptoms)
  - Common patterns:
    - `FAILED tests/test_*.py::test_name` → pytest failure
    - `F401 'module' imported but unused` → ruff linting
    - `error: Incompatible types` → mypy type error
    - `Error: Build failed` → compilation/bundling error

- **For warnings in passing checks**:
  - Read logs even if conclusion is "success"
  - Look for: pytest warnings, deprecations, security warnings
  - Address to prevent future issues

For each piece of review feedback:

- **Categorize by priority**:
  - **Critical:** Security issues, bugs, breaking changes, test failures, build errors
  - **High:** Status check failures, design concerns, architecture issues
  - **Medium:** Code quality issues, performance concerns, warnings in logs
  - **Low:** Style preferences, minor improvements, linting warnings
  - **Nitpicks:** Formatting, typos, documentation improvements

- **Identify feedback source**:
  - **Human reviewers:** Highest priority - address every comment
  - **Status checks (CI/CD):** Must pass - address ALL errors, failures, and warnings
  - **Bot reviewers (CRITICAL - CHECK BOTH):**
    - **`copilot-pull-request-reviewer[bot]`:** Code quality, best practices, security
    - **`claude[bot]`:** Architecture, patterns, testing, comprehensive reviews
    - **⚠️ IMPORTANT:** These are SEPARATE bots - must check reviews from BOTH users
  - **Linters/formatters:** Address all warnings and errors in logs

- **Status check analysis:**
  - Check if ALL status checks are passing
  - For failing checks: Read full logs to identify root cause
  - For warnings in logs: Address even if check passed
  - Common issues to look for:
    - Test failures (pytest, jest, etc.)
    - Linting errors (ruff, eslint, etc.)
    - Type checking errors (mypy, TypeScript)
    - Build failures (compilation errors)
    - Coverage drops below threshold
    - Security warnings
    - Deprecation warnings

- **Determine actionability**:
  - Concrete change requested: Make the change immediately
  - Status check failure: Fix the root cause
  - Warning in logs: Address to prevent future issues
  - Question or clarification: Respond with explanation or ask for clarification
  - Conflicting feedback: Apply most recent (our policy)

### 3. Make Changes

**Priority order:**
1. Fix status check failures (CI must pass)
2. Address critical human review feedback
3. Fix status check warnings (even if check passed)
4. Address high/medium human review feedback
5. Address low-priority feedback and nitpicks

For each actionable item:

1. **Understand context**: Read relevant files completely
2. **Plan the fix**: Think through implications
3. **Make changes**: Use Edit or Write tools
4. **Verify locally if possible**:
   - Run tests: `pytest tests/ -v`
   - Run linters: `ruff check --fix .`
   - Run formatters: `ruff format .`
   - Run type checker: `mypy src/`
5. **Follow principles**:
   - Strive for elegance, not bloat
   - Anticipate edge cases
   - Design for testability
   - Avoid anti-patterns
   - Think ahead - what could break?

**Status check fixes:**
- Read full error output from logs
- Fix root cause, not just symptoms
- Ensure tests pass locally before pushing
- Address warnings even if not critical

### 4. Commit and Push

Create a well-structured commit:

```bash
git add <changed-files>

git commit -m "$(cat <<'EOF'
<type>: <brief summary>

Addresses review feedback:
- <specific comment 1> - <what you did>
- <specific comment 2> - <what you did>

<optional additional context>

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: stavxyz <{CO_AUTHOR_EMAIL}>
EOF
)"

git push
```

**Commit message guidelines**:
- Type: fix, feat, refactor, test, docs, style
- Reference specific review comments when possible
- Explain WHY, not just WHAT
- Keep under 72 characters for summary

### 5. Update PR

Add a comment summarizing your changes:

```bash
gh pr comment {PR_NUMBER} -b "$(cat <<'EOF'
### Review Feedback Addressed

I've addressed the following feedback:

#### Status Checks Fixed
1. **[CI Check] Test failures**
   - Fixed: <specific test that was failing>
   - Root cause: <what was wrong>
   - Files affected: `file1.py`, `file2.py`

2. **[CI Check] Linting warnings**
   - Fixed: <specific linting issues>
   - Tool: ruff/mypy/eslint

#### Review Comments Addressed
1. **[@reviewer] Comment about X** (Critical)
   - Changed: <what you did>
   - Rationale: <why>

2. **[@reviewer] Comment about Y** (Nitpick)
   - Changed: <what you did>
   - Files affected: `file1.py`

### Changes Made

- <bullet list of concrete changes>

### Verification
- ✅ All tests passing locally
- ✅ Linting errors resolved
- ✅ Type checking passed
- ✅ All review comments addressed (including nitpicks)

Ready for re-review.

---
🤖 Automated via Claude Code
EOF
)"
```

### 6. Check for More Reviews and CI Status

First, check if there are new reviews or CI changes:

```bash
bash .claude/scripts/check-pr-reviews.sh {PR_NUMBER}
```

- If iteration needed (exit code 0): Repeat from step 1
- If no iteration needed (exit code 1): Proceed to Final Verification (step 7)
- If error (exit code 2): Report the issue and stop

### 7. Final Verification (MANDATORY - DO NOT SKIP)

**CRITICAL:** Before declaring the PR "ready", "production ready", or any similar statement, you MUST run this verification script:

**Step 7.1: Add verification to todo list**

Use the TodoWrite tool to create a tracking item:
```
TodoWrite:
  - content: "Verify PR ready with verify-pr-ready.sh"
    activeForm: "Verifying PR ready with verify-pr-ready.sh"
    status: "pending"
```

**Step 7.2: Run verification script**

Before running, mark todo as in_progress:
```
TodoWrite: Update status to "in_progress"
```

Then run the verification:
```bash
bash .claude/scripts/verify-pr-ready.sh {PR_NUMBER}
```

**Step 7.3: Update todo based on result**

- **If exit 0 (ready):** Mark todo as completed, may declare PR ready
  - Update status to "completed"
  - All CI checks are passing
  - Safe to use phrases like "PR is ready", "ready to merge"

- **If exit 1 (not ready):** Keep todo as in_progress, wait for fixes
  - CI checks are failing or pending
  - Update content to include blocker reason
  - Wait for CI to complete or address failures
  - DO NOT declare PR ready

- **If exit 2 (error):** Keep todo as in_progress, report to user
  - Cannot verify CI status (API error, permissions, network)
  - Update content to include error details
  - Report the error to user
  - Ask user to investigate (gh auth status, permissions, network)
  - DO NOT declare PR ready

**Example todo states:**

Initial (Step 7.1):
```json
{
  "content": "Verify PR ready with verify-pr-ready.sh",
  "activeForm": "Verifying PR ready with verify-pr-ready.sh",
  "status": "pending"
}
```

After successful verification (exit 0):
```json
{
  "content": "Verify PR ready with verify-pr-ready.sh",
  "activeForm": "Verifying PR ready with verify-pr-ready.sh",
  "status": "completed"
}
```

After failed verification (exit 1):
```json
{
  "content": "Verify PR ready with verify-pr-ready.sh - BLOCKED: 2 CI checks failing",
  "activeForm": "Verifying PR ready with verify-pr-ready.sh",
  "status": "in_progress"
}
```

**Exit codes:**
- **Exit 0** (ready): All CI checks passing, no pending checks → You may declare PR ready
- **Exit 1** (not ready): CI checks failing or pending → DO NOT declare PR ready
- **Exit 2** (error): Cannot verify CI status → DO NOT declare PR ready

**MANDATORY RULES:**
1. **NEVER declare a PR ready without running this script**
2. **NEVER declare a PR ready if this script exits with code 1 or 2**
3. **NEVER use phrases like "production ready", "ready to merge", "good to go" unless this script exits with code 0**
4. If script exits with code 1 (not ready):
   - Report the specific blockers shown in the output
   - Explain what needs to be fixed
   - Do NOT declare success
5. If script exits with code 2 (cannot verify):
   - Report the API error
   - Ask user to investigate (permissions, network, gh auth status)
   - Do NOT declare success

**This is a HARD GATE - you cannot bypass it.**

### 8. Iteration Limit

Track iterations in state file. If iterations ≥ 10:
- Stop automatic iteration
- Add PR comment explaining the situation
- Ask user for guidance

## Special Cases

### Status Check Failures

**REQUIRED:** ALL status checks must pass before iteration completes.

When status checks fail:
1. Get full logs: `gh api repos/{owner}/{repo}/commits/{sha}/check-runs`
2. Identify exact error message/line number
3. Fix root cause (not symptoms)
4. Verify fix locally before pushing
5. Common patterns:
   - **Test failures:** Fix the test or the code being tested
   - **Linting errors:** Run linter locally, fix all issues
   - **Type errors:** Add type hints, fix type mismatches
   - **Build errors:** Fix compilation/bundling issues
   - **Coverage drops:** Add tests to maintain coverage threshold

**Warnings in passing checks:**
- Address deprecation warnings
- Fix security warnings
- Clean up linting warnings
- Update outdated dependencies

### Conflicting Feedback

When reviewers disagree:
- Apply the **most recent** feedback (our policy)
- Add PR comment explaining which approach you chose and why
- Tag the reviewers if clarification needed

### Ambiguous Feedback

If you can't determine concrete action:
- Add PR comment asking for clarification
- Reference the specific comment
- Propose 2-3 possible interpretations
- Pause iteration until clarification received

### Test Failures

If CI tests are failing:
1. Get full test output from status check logs
2. Analyze the specific failure
3. Fix if straightforward
4. If complex, add PR comment describing the issue and ask for help
5. NEVER push without tests passing

### Merge Conflicts

If push fails due to conflicts:
- Pull latest changes
- Attempt auto-merge
- If conflicts remain, add PR comment and pause

## Important Reminders

- **Read before editing**: Always read files completely before making changes
- **Test your changes**: Run relevant tests if possible
- **Be thoughtful**: Think through edge cases and implications
- **Stay focused**: Only address the specific feedback, don't over-engineer
- **Communicate clearly**: PR comments should be concise but informative

## Success Criteria

You've successfully completed iteration when **ALL** of the following are true:

**PRE-REQUISITE:** You MUST have a completed todo item showing you ran `verify-pr-ready.sh` with exit code 0.

1. **`verify-pr-ready.sh` exits with code 0** (MANDATORY GATE)
   - This script checks absolute CI state (not just changes)
   - All checks must have `conclusion == "success"`
   - No checks can be pending/in-progress
   - No checks can be failing
   - **Must be tracked in todo list and marked completed**

2. **ALL review feedback has been addressed** (critical, high, medium, low, AND nitpicks)
   - Human review comments
   - Bot review comments (copilot and claude)
   - Inline code comments
   - PR discussion comments

3. **Changes committed and pushed** with clear commit messages

4. **PR comment posted** summarizing all work done

5. **No new reviews detected** by `check-pr-reviews.sh`

**CRITICAL:** You MUST run `verify-pr-ready.sh` before declaring success. Never use phrases like "ready", "production ready", "good to go" without first verifying all CI checks pass.

**Incomplete iteration if ANY of:**
- `verify-pr-ready.sh` exits with code 1 (not ready) or 2 (error)
- Any CI check is failing
- Any CI check is pending/in-progress
- Cannot fetch CI status from API
- Any review comment is unaddressed (even nitpicks)
- Tests don't pass locally

## Example Flow

```
Fetching feedback for PR #42...
  - Reviews: 1
  - Review comments: 1
  - Issue comments: 1
  - copilot-pull-request-reviewer[bot] comments: 3
  - claude[bot] comments: 2
  - Status checks: 3 failing, 2 passing with warnings

Analyzing feedback...
  ✓ [Status Check] pytest: 2 tests failing - Critical
  ✓ [Status Check] ruff: 5 linting errors - High
  ✓ [Status Check] mypy: 1 type error (warning only) - Medium
  ✓ @alice: "Add input validation" - Critical, actionable
  ✓ copilot-pull-request-reviewer[bot]: "Extract this to a helper function" - Medium, actionable
  ✓ claude[bot]: "Consider edge case when X is null" - Medium, actionable
  ✓ claude[bot]: "Missing unit tests" - Critical, actionable
  ✓ @bob: "Fix typo in docstring" - Nitpick, actionable

Making changes (priority order)...
  ✓ Fixed failing tests in test_process.py
  ✓ Fixed 5 ruff linting errors
  ✓ Fixed mypy type error
  ✓ Added input validation to process_data()
  ✓ Extracted format_output() helper function
  ✓ Added null check for X parameter
  ✓ Fixed typo in docstring

Verifying locally...
  ✓ pytest tests/ -v (all passed)
  ✓ ruff check . (no errors)
  ✓ mypy src/ (no errors)

Committing changes...
  ✓ Committed: "fix: address status check failures and review feedback"
  ✓ Pushed to origin/feature-branch

Updating PR...
  ✓ Posted summary comment

Checking for new reviews and status checks...
  No new reviews found
  Status checks: All passing ✅

✓ Iteration complete!
```
