From 5e533d252961bedbe7c422f94c7fd38ec016556f Mon Sep 17 00:00:00 2001 From: Gage Krumbach Date: Wed, 11 Mar 2026 12:18:34 -0500 Subject: [PATCH] refactor: overhaul both workflows with structured output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New per-PR output structure: summary.json — one-read overview (metadata, CI, comments, reviews) comments/ — overview.json + chronological numbered files with IDs ci/ — overview.json + logs/ (opt-in via --with-logs, truncated 200 lines) diff.json — single file with overview + patches reviews/ — overview.json with approval state analysis.json — written separately by analyze-prs.py Scripts: - structure-pr-data.py: takes raw API JSON, produces clean directory (duplicated in each workflow since they run in isolation) - fetch-pr.sh: parallel API calls, --with-logs for CI failure output - fetch-prs.sh: loops all PRs, uses local structure-pr-data.py - analyze-prs.py: reads summary.json, writes analysis.json + queue.json CLAUDE.md files simplified: goal, scripts, judgment calls, constraints. Deleted: merge-comments.py, test-merge-order.sh Co-Authored-By: Claude Opus 4.6 (1M context) --- internal-workflows/pr-fixer/CLAUDE.md | 278 +----- .../pr-fixer/scripts/fetch-pr.sh | 160 +-- .../pr-fixer/scripts/merge-comments.py | 154 --- .../pr-fixer/scripts/structure-pr-data.py | 238 +++++ internal-workflows/pr-overview/CLAUDE.md | 413 ++------ .../pr-overview/scripts/analyze-prs.py | 943 ++++-------------- .../pr-overview/scripts/fetch-prs.sh | 190 +--- .../pr-overview/scripts/structure-pr-data.py | 238 +++++ .../pr-overview/scripts/test-merge-order.sh | 156 --- 9 files changed, 866 insertions(+), 1904 deletions(-) delete mode 100755 internal-workflows/pr-fixer/scripts/merge-comments.py create mode 100755 internal-workflows/pr-fixer/scripts/structure-pr-data.py create mode 100755 internal-workflows/pr-overview/scripts/structure-pr-data.py delete mode 100755 internal-workflows/pr-overview/scripts/test-merge-order.sh diff --git a/internal-workflows/pr-fixer/CLAUDE.md b/internal-workflows/pr-fixer/CLAUDE.md index df874abd..177d72fb 100644 --- a/internal-workflows/pr-fixer/CLAUDE.md +++ b/internal-workflows/pr-fixer/CLAUDE.md @@ -1,263 +1,85 @@ -# PR Fixer — Agent Instructions +# PR Fixer -You are an agent that fixes a single pull request. You rebase it to resolve conflicts, evaluate and address reviewer comments, run lints and tests, and push clean commits. +You fix a single pull request. You're given a repo and PR number. -## Prerequisites +## What You Do -You need: +1. **Fetch the PR data** using the script +2. **Rebase** if there are merge conflicts +3. **Address reviewer feedback** — fix valid issues, respond to invalid ones +4. **Fix CI failures** — read the actual logs, don't guess +5. **Push** when everything is clean +6. **Post a fix report** as a comment on the PR -- **Repo**: `owner/repo` (e.g., `ambient-code/platform`) -- **PR number**: the PR to fix -- **Repo clone**: the repo must be cloned locally (you'll work in a branch) - -If these aren't provided, ask for them before starting. - -## Task Checklist - -1. **Fetch PR data** — run `fetch-pr.sh` to collect all PR details, comments, and diff -2. **Assess PR state** — read the fetched data to understand what needs fixing -3. **Rebase onto base branch** — resolve any merge conflicts first -4. **Evaluate reviewer comments** — read all comments, decide which are valid -5. **Fix valid issues** — make code changes to address legitimate feedback -6. **Respond to invalid concerns** — comment back on issues that aren't valid, explaining why -7. **Run lints and tests** — make sure everything passes -8. **Push fixes** — push the branch with fix commits -9. **Post fix report** — comment on the PR summarizing what was done - -## Workflow - -### Phase 1: Fetch PR Data - -Run the fetch script to collect all data for the PR: +## Fetch Script ```bash -./scripts/fetch-pr.sh --repo --pr --output-dir artifacts/pr-fixer/ +./scripts/fetch-pr.sh --repo --pr --with-logs ``` -This produces: - -- `artifacts/pr-fixer/{number}/summary.md` — **read this first** — compact overview with mergeable status, CI summary, comment counts, and author breakdown -- `artifacts/pr-fixer/{number}/pr.json` — PR metadata (title, body, labels, branch, mergeable status, etc.) -- `artifacts/pr-fixer/{number}/comments.json` — unified chronological comment stream (all comments merged — may be large) -- `artifacts/pr-fixer/{number}/comments/01.json`, `02.json`, ... — **individual comment files** (read these instead of the full `comments.json` to stay under token limits) -- `artifacts/pr-fixer/{number}/diff-index.txt` — **tab-separated file listing** (status, additions, deletions, filename) — read this to see what files changed -- `artifacts/pr-fixer/{number}/diffs/{filename}.json` — **per-file diff** with patch — read individual files as needed -- `artifacts/pr-fixer/{number}/diff.json` — all diffs in one array (**do not read directly** — may exceed token limits) -- `artifacts/pr-fixer/{number}/ci.json` — check run results - -### Phase 2: Assess PR State - -**Start by reading `summary.md`** — it gives you the full picture in ~20 lines: mergeable status, CI failures, comment counts, who commented. - -Then drill into details only as needed: - -1. **Merge conflicts** — summary.md shows mergeable status. If `CONFLICTING`, rebase is needed first. -2. **CI status** — summary.md lists failing checks. Read `ci.json` only if you need the full check run details. -3. **Review comments** — summary.md shows counts and authors. Read individual comment files (`comments/01.json`, `02.json`, etc.) **newest first** — start from the highest number. Don't read `comments.json` directly (it may exceed token limits). -4. **Diff** — read `diff-index.txt` to see all changed files. Then read individual file diffs from `diffs/{filename}.json` as needed. **Never read `diff.json` directly** — it may exceed token limits. - -Determine the fix order: -1. Rebase first (if conflicts exist) — everything else depends on a clean base -2. Address reviewer feedback next — code changes -3. Run lints/tests last — verify everything is clean - -### Phase 3: Rebase - -If the PR has merge conflicts, rebase it onto the base branch. - -```bash -# Clone the repo if not already cloned -gh repo clone /workspace/repos/ -- --depth=50 - -cd /workspace/repos/ - -# Fetch the PR branch -gh pr checkout - -# Rebase onto base branch (usually main) -git fetch origin main -git rebase origin/main -``` - -If rebase has conflicts: -1. Look at each conflicting file -2. Read the upstream changes and the PR's changes to understand the intent -3. Resolve the conflict by keeping the PR's intent while incorporating upstream changes -4. `git add ` and `git rebase --continue` -5. Repeat for each conflict - -**Do NOT just accept theirs/ours blindly.** Understand what both sides are doing and merge the intent. - -After rebase: -- Verify the code still makes sense (read the changed files) -- Do NOT force-push yet — wait until all fixes are done - -### Phase 4: Evaluate Reviewer Comments - -Read the individual comment files in `comments/` **newest first** (highest number first). Each comment file has: - -```json -{ - "source": "pr_comment|review|inline_comment", - "author": "username", - "timestamp": "2026-02-20T...", - "body": "comment text...", - "state": "APPROVED|CHANGES_REQUESTED", - "path": "path/to/file.go" -} +Output goes to `artifacts/{number}/`: + +```text +artifacts/{number}/ +├── summary.json # Start here — PR metadata, mergeable, CI status, comment counts +├── comments/ +│ ├── overview.json # Comment counts, has_agent_prompts flag, authors +│ └── 01.json, 02.json... # Each comment chronologically (with id for replying) +├── ci/ +│ ├── overview.json # Pass/fail/pending check lists +│ └── logs/ +│ └── failure.txt # Actual CI failure output (last 200 lines) +├── diff.json # Changed files with patches +└── reviews/ + └── overview.json # Approvals, changes requested, review decision ``` -For each comment/review, decide: - -**Is this valid feedback that should be fixed?** -- Security issues, bugs, incorrect logic — always valid, fix them -- Missing error handling on critical paths — valid -- Breaking API changes without migration — valid -- Performance issues with real impact — valid - -**Is this a style/preference issue?** -- Naming suggestions — fix if the reviewer is a maintainer, otherwise use your judgment -- Code organization preferences — fix if it's clearly better, skip if it's subjective -- "Nit" comments — fix them, they're usually quick - -**Is this invalid or outdated?** -- Comment refers to code that no longer exists (stale review on old commit) — skip, but note it -- Suggestion would introduce a bug or break something — comment back explaining why -- Factually incorrect concern — comment back with the correction -- Already addressed in a subsequent commit — skip +**Read `summary.json` first.** It tells you what's wrong and where to dig deeper. -### Phase 5: Fix Valid Issues +## Handling Comments -For each valid issue identified in Phase 4: +Read `comments/overview.json` to see what's there, then read the individual comment files. -1. Read the relevant file(s) -2. Understand the surrounding code context -3. Make the fix -4. Commit with a clear message explaining what was fixed and why +**Bot reviews (CodeRabbit, etc.) often include structured agent prompts.** Look for `Prompt for AI Agents` blocks — these give you the exact file, line range, and what to fix. Use these as your primary task list. Always verify against the current code first. -**Commit style:** -- Make all fixes as unstaged changes — do NOT commit as you go -- After all fixes and lint/test passes, create a **single commit** with all changes -- Set the commit author to the bot identity: - ```bash - git add -A - git commit --author="ambient-code[bot] " \ - -m "fix: address review feedback +Prioritize by severity: Critical > Major > Minor/Nitpick. - +For human comments, use your judgment: fix real issues, fix nits if quick, push back on things that are wrong. - Co-Authored-By: Claude " - ``` - -### Phase 6: Respond to Invalid Concerns - -For comments you determined are invalid or outdated: - -- Post a reply on the PR explaining your reasoning -- Be respectful and specific — don't just say "this is wrong" -- If a bot review raised the concern, explain why the bot's analysis doesn't apply - -```bash -gh pr comment --repo --body "$(cat <<'EOF' -Regarding the concern about [specific issue]: - -[Your explanation of why this doesn't apply / is already handled / would cause a regression] -EOF -)" -``` - -For inline comments, respond on the specific review thread if possible: +**When you fix an inline comment, reply on that thread:** ```bash gh api "repos/{owner}/{repo}/pulls/{number}/comments/{comment_id}/replies" \ - -f body="[Your response]" + -f body="Fixed — [what you did]" ``` -### Phase 7: Run Lints and Tests +**When you disagree, reply explaining why** — don't ignore it. -After all code changes, verify everything is clean: +## Fixing CI Failures -1. **Identify the project's lint/test commands** — check for: - - `Makefile` targets (`make lint`, `make test`) - - `package.json` scripts (`npm test`, `npm run lint`) - - `pyproject.toml` / `setup.cfg` (`pytest`, `ruff`, `mypy`) - - `.golangci.yml` (`golangci-lint run`) - - CI workflow files (`.github/workflows/`) — see what CI runs - -2. **Run lints first** — fix any issues found - -3. **Run tests** — if tests fail: - - Read the test failure output - - Determine if the failure is from your changes or pre-existing - - Fix failures caused by your changes - - For pre-existing failures, note them in the fix report - -4. **Do NOT commit yet** — lint/test fixes are included in the single final commit with all other changes - -### Phase 8: Push - -Once all fixes are in a single commit and lints/tests pass, push immediately — **do not ask for confirmation**: +**Do not guess.** Read `ci/logs/failure.txt` for the actual error. If the log file doesn't exist or isn't enough, fetch more: ```bash -git push --force-with-lease origin HEAD +gh run view {run_id} --repo {owner/repo} --log-failed ``` -Use `--force-with-lease` (not `--force`) to avoid overwriting changes someone else may have pushed. +Read the error, find the failing test, read the test code, fix the root cause. -### Phase 9: Post Fix Report as PR Comment +## Pushing -Post a summary comment on the PR so the author and reviewers can see what was done. Use the `` marker for identification. +Use `git push --force-with-lease`. Show what you're pushing before you push. -First, find and delete any existing fix report comment: +## Fix Report -```bash -OLD_COMMENT_ID=$(gh api "repos/{owner}/{repo}/issues/{number}/comments" \ - --jq '.[] | select(.body | contains("")) | .id') +Post a comment on the PR summarizing what you did. Delete any previous report first. -if [ -n "$OLD_COMMENT_ID" ]; then - gh api -X DELETE "repos/{owner}/{repo}/issues/comments/${OLD_COMMENT_ID}" -fi -``` +Use `` marker so old reports can be found and replaced. -Then post the new report: - -```bash -gh api "repos/{owner}/{repo}/issues/{number}/comments" \ - -f body="${COMMENT_BODY}" -``` - -Comment format: - -```markdown -### PR Fixer Report - -**Date:** {date} - -#### What Was Done - -**Rebase** -- [Rebased onto main / No rebase needed] -- [Conflicts resolved in: file1.go, file2.go / No conflicts] - -**Reviewer Feedback Addressed** -- [List each issue fixed with a brief description] - -**Reviewer Feedback Responded To** -- [List each comment responded to and why it wasn't fixed] - -**Lints & Tests** -- [All passing / Fixed N lint issues / Tests status] - -#### Commit -- `abc1234` fix: address review feedback - - -``` +The report should cover: what was rebased, what feedback was addressed, what was responded to, CI status, commits pushed. -## Important Notes +## Constraints -- **Never force push without `--force-with-lease`** — it protects against overwriting others' work -- **Push automatically** — do not ask for confirmation, the workflow is designed to run unattended -- **Single commit** — all fixes go in one commit authored by `ambient-code[bot]` -- **Preserve the PR author's intent** — when resolving conflicts, keep the PR's changes where they make sense -- **Don't over-fix** — only address issues that were actually raised. Don't refactor surrounding code or add improvements the reviewer didn't ask for. +- **Don't over-fix** — only address what was raised +- **Preserve the author's intent** when resolving conflicts +- **Never force push without `--force-with-lease`** +- **Don't push without showing what will be pushed first** diff --git a/internal-workflows/pr-fixer/scripts/fetch-pr.sh b/internal-workflows/pr-fixer/scripts/fetch-pr.sh index 1b5e0a36..47731b54 100755 --- a/internal-workflows/pr-fixer/scripts/fetch-pr.sh +++ b/internal-workflows/pr-fixer/scripts/fetch-pr.sh @@ -1,14 +1,9 @@ #!/usr/bin/env bash # -# fetch-pr.sh — Fetch all data for a single PR into structured JSON files. +# fetch-pr.sh — Fetch all data for a single PR and structure it. # # Usage: -# ./scripts/fetch-pr.sh --repo owner/repo --pr 123 [--output-dir artifacts/pr-fixer/123] -# -# Requirements: -# - gh CLI installed and authenticated -# - jq installed -# - python3 installed +# ./scripts/fetch-pr.sh --repo owner/repo --pr 123 [--output-dir artifacts/123] [--with-logs] # set -euo pipefail @@ -16,139 +11,94 @@ set -euo pipefail REPO="" PR_NUM="" OUTPUT_DIR="" +WITH_LOGS=false SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" while [[ $# -gt 0 ]]; do case "$1" in - --repo) - REPO="$2" - shift 2 - ;; - --pr) - PR_NUM="$2" - shift 2 - ;; - --output-dir) - OUTPUT_DIR="$2" - shift 2 - ;; - -h|--help) - echo "Usage: $0 --repo owner/repo --pr 123 [--output-dir artifacts/pr-fixer/123]" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - exit 1 - ;; + --repo) REPO="$2"; shift 2 ;; + --pr) PR_NUM="$2"; shift 2 ;; + --output-dir) OUTPUT_DIR="$2"; shift 2 ;; + --with-logs) WITH_LOGS=true; shift ;; + -h|--help) echo "Usage: $0 --repo owner/repo --pr 123 [--output-dir artifacts/123] [--with-logs]"; exit 0 ;; + *) echo "Unknown argument: $1" >&2; exit 1 ;; esac done -if [[ -z "$REPO" || -z "$PR_NUM" ]]; then - echo "Error: --repo and --pr are required" >&2 - exit 1 -fi - -if [[ -z "$OUTPUT_DIR" ]]; then - OUTPUT_DIR="artifacts/pr-fixer/${PR_NUM}" -fi +[[ -z "$REPO" || -z "$PR_NUM" ]] && { echo "Error: --repo and --pr required" >&2; exit 1; } +[[ -z "$OUTPUT_DIR" ]] && OUTPUT_DIR="artifacts/${PR_NUM}" for cmd in gh jq python3; do - if ! command -v "$cmd" &>/dev/null; then - echo "Error: ${cmd} is not installed." >&2 - exit 1 - fi + command -v "$cmd" &>/dev/null || { echo "Error: ${cmd} not installed" >&2; exit 1; } done - -if ! gh auth status &>/dev/null; then - echo "Error: gh CLI is not authenticated." >&2 - exit 1 -fi +gh auth status &>/dev/null || { echo "Error: gh not authenticated" >&2; exit 1; } OWNER="${REPO%%/*}" REPO_NAME="${REPO##*/}" - -mkdir -p "${OUTPUT_DIR}" TMPDIR=$(mktemp -d) trap 'rm -rf "$TMPDIR"' EXIT -echo "Fetching PR #${PR_NUM} from ${REPO}..." >&2 - -# -- Fetch PR metadata, reviews, review comments, and diff in parallel -- DETAIL_FIELDS="number,title,author,createdAt,updatedAt,labels,isDraft,baseRefName,headRefName,headRefOid,url,state,additions,deletions,changedFiles,mergeable,body,reviewDecision,statusCheckRollup,comments,assignees,milestone,files,isCrossRepository,headRepositoryOwner" -echo " Fetching PR data (parallel)..." >&2 +echo "Fetching PR #${PR_NUM} from ${REPO}..." >&2 +# -- Parallel API calls -- gh pr view "$PR_NUM" --repo "$REPO" --json "$DETAIL_FIELDS" \ - 2>/dev/null > "${OUTPUT_DIR}/pr.json" & + > "${TMPDIR}/pr.json" 2>"${TMPDIR}/pr.err" & PID_PR=$! gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/reviews" \ - --paginate 2>/dev/null > "${TMPDIR}/reviews.json" & + --paginate > "${TMPDIR}/reviews.json" 2>"${TMPDIR}/reviews.err" & PID_REVIEWS=$! gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/comments" \ - --paginate 2>/dev/null > "${TMPDIR}/review_comments.json" & + --paginate > "${TMPDIR}/review_comments.json" 2>"${TMPDIR}/rc.err" & PID_RC=$! gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/files" \ - --paginate 2>/dev/null \ + --paginate 2>"${TMPDIR}/diff.err" \ | jq '[.[] | {filename, status, additions, deletions, patch}]' \ - > "${OUTPUT_DIR}/diff.json" & + > "${TMPDIR}/diff_files.json" & PID_DIFF=$! -# Wait for all parallel fetches, handling failures -wait "$PID_PR" 2>/dev/null || echo '{}' > "${OUTPUT_DIR}/pr.json" -wait "$PID_REVIEWS" 2>/dev/null || echo '[]' > "${TMPDIR}/reviews.json" -wait "$PID_RC" 2>/dev/null || echo '[]' > "${TMPDIR}/review_comments.json" -wait "$PID_DIFF" 2>/dev/null || echo '[]' > "${OUTPUT_DIR}/diff.json" - -# -- Fetch check runs (depends on PR metadata for HEAD_SHA) -- -echo " Fetching CI status..." >&2 -HEAD_SHA=$(jq -r '.headRefOid // empty' "${OUTPUT_DIR}/pr.json" 2>/dev/null || true) +wait "$PID_PR" 2>/dev/null || { cat "${TMPDIR}/pr.err" >&2; echo '{}' > "${TMPDIR}/pr.json"; } +wait "$PID_REVIEWS" 2>/dev/null || { cat "${TMPDIR}/reviews.err" >&2; echo '[]' > "${TMPDIR}/reviews.json"; } +wait "$PID_RC" 2>/dev/null || { cat "${TMPDIR}/rc.err" >&2; echo '[]' > "${TMPDIR}/review_comments.json"; } +wait "$PID_DIFF" 2>/dev/null || { cat "${TMPDIR}/diff.err" >&2; echo '[]' > "${TMPDIR}/diff_files.json"; } -echo '[]' > "${OUTPUT_DIR}/ci.json" +# -- Check runs (needs HEAD_SHA from pr.json) -- +HEAD_SHA=$(jq -r '.headRefOid // empty' "${TMPDIR}/pr.json" 2>/dev/null || true) +echo '[]' > "${TMPDIR}/check_runs.json" if [[ -n "$HEAD_SHA" ]]; then gh api "repos/${OWNER}/${REPO_NAME}/commits/${HEAD_SHA}/check-runs" \ --paginate 2>/dev/null \ - | jq '.check_runs // []' > "${OUTPUT_DIR}/ci.json" 2>/dev/null || echo '[]' > "${OUTPUT_DIR}/ci.json" + | jq '.check_runs // []' > "${TMPDIR}/check_runs.json" 2>/dev/null || echo '[]' > "${TMPDIR}/check_runs.json" +fi + +# -- Structure the data -- +python3 "${SCRIPT_DIR}/structure-pr-data.py" \ + --pr-json "${TMPDIR}/pr.json" \ + --reviews-json "${TMPDIR}/reviews.json" \ + --review-comments-json "${TMPDIR}/review_comments.json" \ + --check-runs-json "${TMPDIR}/check_runs.json" \ + --diff-json "${TMPDIR}/diff_files.json" \ + --output-dir "${OUTPUT_DIR}" + +# -- Fetch CI failure logs (optional) -- +if [[ "$WITH_LOGS" == "true" && -n "$HEAD_SHA" ]]; then + mkdir -p "${OUTPUT_DIR}/ci/logs" + FAILING=$(jq -r '.failing[]?.name // empty' "${OUTPUT_DIR}/ci/overview.json" 2>/dev/null) + if [[ -n "$FAILING" ]]; then + echo " Fetching CI failure logs..." >&2 + RUN_ID=$(gh api "repos/${OWNER}/${REPO_NAME}/actions/runs?head_sha=${HEAD_SHA}&status=failure" \ + --jq '.workflow_runs[0].id' 2>/dev/null || true) + if [[ -n "$RUN_ID" && "$RUN_ID" != "null" ]]; then + gh run view "$RUN_ID" --repo "$REPO" --log-failed 2>/dev/null \ + | tail -200 > "${OUTPUT_DIR}/ci/logs/failure.txt" 2>/dev/null || true + echo " Wrote failure logs (last 200 lines)" >&2 + fi + fi fi -# -- Build unified comment stream using shared script -- -echo " Building unified comment stream..." >&2 -python3 "${SCRIPT_DIR}/merge-comments.py" \ - --pr-json "${OUTPUT_DIR}/pr.json" \ - --reviews "${TMPDIR}/reviews.json" \ - --review-comments "${TMPDIR}/review_comments.json" \ - --output "${OUTPUT_DIR}/comments.json" - -# -- Generate per-file diffs and index (for large diffs) -- -echo " Splitting diff into per-file diffs..." >&2 -mkdir -p "${OUTPUT_DIR}/diffs" -jq -r '.[] | "\(.status)\t\(.additions)\t\(.deletions)\t\(.filename)"' \ - "${OUTPUT_DIR}/diff.json" 2>/dev/null > "${OUTPUT_DIR}/diff-index.txt" || true - -# Write each file's diff as a separate JSON file (filename sanitized to path-safe name) -python3 -c " -import json, os, re -with open('${OUTPUT_DIR}/diff.json') as f: - files = json.load(f) -for df in files: - fname = df.get('filename', 'unknown') - safe = re.sub(r'[^a-zA-Z0-9._-]', '_', fname) - with open(os.path.join('${OUTPUT_DIR}/diffs', safe + '.json'), 'w') as out: - json.dump(df, out, indent=2) -" 2>/dev/null || true - -# -- Summary -- -COMMENT_COUNT=$(jq 'length' "${OUTPUT_DIR}/comments.json" 2>/dev/null || echo "0") -DIFF_COUNT=$(jq 'length' "${OUTPUT_DIR}/diff.json" 2>/dev/null || echo "0") -CI_COUNT=$(jq 'length' "${OUTPUT_DIR}/ci.json" 2>/dev/null || echo "0") -MERGEABLE=$(jq -r '.mergeable // "unknown"' "${OUTPUT_DIR}/pr.json" 2>/dev/null || echo "unknown") - -echo "" -echo "Fetch complete for PR #${PR_NUM}:" -echo " Mergeable: ${MERGEABLE}" -echo " Comments: ${COMMENT_COUNT} (unified stream + per-comment files)" -echo " Diff files: ${DIFF_COUNT} (index: diff-index.txt)" -echo " CI checks: ${CI_COUNT}" -echo " Output: ${OUTPUT_DIR}/" +echo "" >&2 +echo "Fetch complete for PR #${PR_NUM}: ${OUTPUT_DIR}/" >&2 diff --git a/internal-workflows/pr-fixer/scripts/merge-comments.py b/internal-workflows/pr-fixer/scripts/merge-comments.py deleted file mode 100755 index da0d3383..00000000 --- a/internal-workflows/pr-fixer/scripts/merge-comments.py +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env python3 -""" -Merge all comment sources for a PR into a single chronological stream. - -Usage: - python3 merge-comments.py --pr-json pr.json --reviews reviews.json \ - --review-comments review_comments.json --output comments.json - -Reads PR comments from pr.json (nested under .comments[]), -formal reviews from reviews.json, and inline review comments -from review_comments.json. Outputs a single sorted JSON array. -""" - -import argparse -import json -import sys - - -def merge_comments(pr_path, reviews_path, review_comments_path): - """Load comment sources from files and merge chronologically. - - This mirrors merge_comment_sources() in analyze-prs.py. - Keep them in sync. - """ - all_comments = [] - - with open(pr_path) as f: - pr = json.load(f) - for c in pr.get("comments", []): - all_comments.append( - { - "source": "pr_comment", - "author": c.get("author", {}).get("login", ""), - "timestamp": c.get("createdAt", ""), - "body": c.get("body", ""), - } - ) - - with open(reviews_path) as f: - reviews = json.load(f) - for r in reviews: - body = r.get("body", "") - if not body or not body.strip(): - continue - all_comments.append( - { - "source": "review", - "author": r.get("user", {}).get("login", ""), - "state": r.get("state", ""), - "timestamp": r.get("submitted_at", ""), - "body": body, - } - ) - - with open(review_comments_path) as f: - rc_list = json.load(f) - for rc in rc_list: - body = rc.get("body", "") - if not body or not body.strip(): - continue - all_comments.append( - { - "source": "inline_comment", - "author": rc.get("user", {}).get("login", ""), - "path": rc.get("path", ""), - "timestamp": rc.get("created_at", ""), - "body": body, - } - ) - - all_comments.sort(key=lambda c: c.get("timestamp", "")) - return all_comments - - -def main(): - parser = argparse.ArgumentParser(description="Merge PR comment sources") - parser.add_argument("--pr-json", required=True) - parser.add_argument("--reviews", required=True) - parser.add_argument("--review-comments", required=True) - parser.add_argument("--output", required=True) - args = parser.parse_args() - - comments = merge_comments(args.pr_json, args.reviews, args.review_comments) - - with open(args.output, "w") as f: - json.dump(comments, f, indent=2, ensure_ascii=False) - - # Write per-comment files for tiered reading (avoids 25K token limit) - comments_dir = args.output.replace(".json", "") - import os - os.makedirs(comments_dir, exist_ok=True) - - for i, comment in enumerate(comments, 1): - with open(os.path.join(comments_dir, f"{i:02d}.json"), "w") as f: - json.dump(comment, f, indent=2, ensure_ascii=False) - - # Write summary markdown - pr_data = {} - with open(args.pr_json) as f: - pr_data = json.load(f) - - mergeable = pr_data.get("mergeable", "unknown") - title = pr_data.get("title", "") - author = (pr_data.get("author") or {}).get("login", "unknown") - branch = pr_data.get("headRefName", "") - base = pr_data.get("baseRefName", "main") - additions = pr_data.get("additions", 0) - deletions = pr_data.get("deletions", 0) - changed_files = pr_data.get("changedFiles", 0) - - # Count comment types - review_count = sum(1 for c in comments if c["source"] == "review") - inline_count = sum(1 for c in comments if c["source"] == "inline_comment") - pr_comment_count = sum(1 for c in comments if c["source"] == "pr_comment") - - # CI summary - ci_path = os.path.join(os.path.dirname(args.output), "ci.json") - ci_summary = "unknown" - if os.path.exists(ci_path): - with open(ci_path) as f: - checks = json.load(f) - failing = [c.get("name", "?") for c in checks - if c.get("conclusion") in ("failure", "timed_out", "cancelled")] - if failing: - ci_summary = f"FAIL: {', '.join(failing[:3])}" - else: - ci_summary = "all passing" - - summary_path = os.path.join(os.path.dirname(args.output), "summary.md") - with open(summary_path, "w") as f: - f.write(f"# PR: {title}\n\n") - f.write(f"- **Author:** {author}\n") - f.write(f"- **Branch:** {branch} → {base}\n") - f.write(f"- **Size:** {changed_files} files (+{additions}/-{deletions})\n") - f.write(f"- **Mergeable:** {mergeable}\n") - f.write(f"- **CI:** {ci_summary}\n") - f.write(f"- **Comments:** {len(comments)} total " - f"({review_count} reviews, {inline_count} inline, {pr_comment_count} PR comments)\n") - if comments: - f.write(f"\n## Comment Authors\n\n") - authors = {} - for c in comments: - a = c.get("author", "unknown") - authors[a] = authors.get(a, 0) + 1 - for a, count in sorted(authors.items(), key=lambda x: -x[1]): - f.write(f"- @{a}: {count} comments\n") - - print(f"{len(comments)} comments merged into unified stream", file=sys.stderr) - print(f"Per-comment files: {comments_dir}/01.json ... {len(comments):02d}.json", file=sys.stderr) - print(f"Summary: {summary_path}", file=sys.stderr) - - -if __name__ == "__main__": - main() diff --git a/internal-workflows/pr-fixer/scripts/structure-pr-data.py b/internal-workflows/pr-fixer/scripts/structure-pr-data.py new file mode 100755 index 00000000..90443387 --- /dev/null +++ b/internal-workflows/pr-fixer/scripts/structure-pr-data.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +""" +Structure raw PR API data into a clean directory layout. + +Takes raw JSON files from GitHub API and produces: + {output-dir}/summary.json + {output-dir}/comments/overview.json + 01.json, 02.json, ... + {output-dir}/ci/overview.json + {output-dir}/diff.json + {output-dir}/reviews/overview.json + +Usage: + python3 structure-pr-data.py \ + --pr-json raw/pr.json \ + --reviews-json raw/reviews.json \ + --review-comments-json raw/review_comments.json \ + --check-runs-json raw/check_runs.json \ + --diff-json raw/diff_files.json \ + --output-dir artifacts/123 +""" + +import argparse +import json +import os +import sys + + +def build_comments(pr_comments, reviews, review_comments): + """Merge all comment sources chronologically, filter empty bodies.""" + all_comments = [] + + for c in pr_comments: + all_comments.append({ + "source": "pr_comment", + "id": c.get("id", ""), + "author": c.get("author", {}).get("login", ""), + "timestamp": c.get("createdAt", ""), + "body": c.get("body", ""), + }) + + for r in reviews: + body = r.get("body", "") + if not body or not body.strip(): + continue + all_comments.append({ + "source": "review", + "id": r.get("id", ""), + "author": r.get("user", {}).get("login", ""), + "state": r.get("state", ""), + "timestamp": r.get("submitted_at", ""), + "body": body, + }) + + for rc in review_comments: + body = rc.get("body", "") + if not body or not body.strip(): + continue + all_comments.append({ + "source": "inline_comment", + "id": rc.get("id", ""), + "author": rc.get("user", {}).get("login", ""), + "path": rc.get("path", ""), + "line": rc.get("line"), + "timestamp": rc.get("created_at", ""), + "body": body, + }) + + all_comments.sort(key=lambda c: c.get("timestamp", "")) + return all_comments + + +def build_ci(check_runs): + """Categorize check runs into passing/failing/pending.""" + passing, failing, pending = [], [], [] + for cr in check_runs: + name = cr.get("name", "unknown") + status = cr.get("status", "") + conclusion = cr.get("conclusion", "") + if status != "completed": + pending.append({"name": name, "status": status}) + elif conclusion in ("failure", "timed_out", "cancelled", "action_required"): + failing.append({ + "name": name, + "conclusion": conclusion, + "run_id": cr.get("id", ""), + "html_url": cr.get("html_url", ""), + }) + else: + passing.append(name) + return passing, failing, pending + + +def build_reviews(reviews, review_decision): + """Extract review state per user.""" + user_states = {} + for r in reviews: + login = r.get("user", {}).get("login", "") + state = r.get("state", "") + if login: + user_states[login] = state + + approvals = [{"user": u, "state": s} for u, s in user_states.items() if s == "APPROVED"] + changes_requested = [{"user": u, "state": s} for u, s in user_states.items() if s == "CHANGES_REQUESTED"] + + return { + "decision": review_decision, + "approvals": approvals, + "changes_requested": changes_requested, + "total_reviews": len(reviews), + } + + +def main(): + parser = argparse.ArgumentParser(description="Structure raw PR data") + parser.add_argument("--pr-json", required=True) + parser.add_argument("--reviews-json", required=True) + parser.add_argument("--review-comments-json", required=True) + parser.add_argument("--check-runs-json", required=True) + parser.add_argument("--diff-json", required=True) + parser.add_argument("--output-dir", required=True) + args = parser.parse_args() + + out = args.output_dir + os.makedirs(f"{out}/comments", exist_ok=True) + os.makedirs(f"{out}/ci", exist_ok=True) + os.makedirs(f"{out}/reviews", exist_ok=True) + + with open(args.pr_json) as f: + pr = json.load(f) + with open(args.reviews_json) as f: + reviews = json.load(f) + with open(args.review_comments_json) as f: + review_comments = json.load(f) + with open(args.check_runs_json) as f: + check_runs = json.load(f) + with open(args.diff_json) as f: + diff_files = json.load(f) + + # -- Comments -- + all_comments = build_comments(pr.get("comments", []), reviews, review_comments) + inline_threads = [c for c in all_comments if c["source"] == "inline_comment"] + has_agent_prompts = any("Prompt for AI Agents" in c.get("body", "") for c in all_comments) + + comments_overview = { + "total": len(all_comments), + "by_source": { + "review": sum(1 for c in all_comments if c["source"] == "review"), + "inline_comment": len(inline_threads), + "pr_comment": sum(1 for c in all_comments if c["source"] == "pr_comment"), + }, + "has_agent_prompts": has_agent_prompts, + "latest_activity": all_comments[-1]["timestamp"] if all_comments else "", + "authors": sorted(set(c["author"] for c in all_comments if c["author"])), + } + with open(f"{out}/comments/overview.json", "w") as f: + json.dump(comments_overview, f, indent=2, ensure_ascii=False) + for i, c in enumerate(all_comments, 1): + with open(f"{out}/comments/{i:02d}.json", "w") as f: + json.dump(c, f, indent=2, ensure_ascii=False) + + # -- CI -- + passing, failing, pending = build_ci(check_runs) + ci_overview = {"total": len(check_runs), "passing": passing, "failing": failing, "pending": pending} + with open(f"{out}/ci/overview.json", "w") as f: + json.dump(ci_overview, f, indent=2, ensure_ascii=False) + + ci_status = "pass" + if failing: + ci_status = "failing" + elif pending: + ci_status = "pending" + + # -- Diff -- + diff_data = { + "total_files": len(diff_files), + "additions": sum(df.get("additions", 0) for df in diff_files), + "deletions": sum(df.get("deletions", 0) for df in diff_files), + "files": diff_files, + } + with open(f"{out}/diff.json", "w") as f: + json.dump(diff_data, f, indent=2, ensure_ascii=False) + + # -- Reviews -- + reviews_overview = build_reviews(reviews, pr.get("reviewDecision", "")) + with open(f"{out}/reviews/overview.json", "w") as f: + json.dump(reviews_overview, f, indent=2, ensure_ascii=False) + + # -- Summary (written last, includes rollups) -- + author = (pr.get("author") or {}).get("login", "unknown") + summary = { + "number": pr.get("number"), + "title": pr.get("title", ""), + "author": author, + "url": pr.get("url", ""), + "branch": pr.get("headRefName", ""), + "base": pr.get("baseRefName", "main"), + "isDraft": pr.get("isDraft", False), + "isFork": pr.get("isCrossRepository", False), + "forkOwner": (pr.get("headRepositoryOwner") or {}).get("login", ""), + "mergeable": pr.get("mergeable", "UNKNOWN"), + "headSha": pr.get("headRefOid", ""), + "createdAt": pr.get("createdAt", ""), + "updatedAt": pr.get("updatedAt", ""), + "labels": [lb.get("name", "") for lb in (pr.get("labels") or [])], + "size": { + "files": pr.get("changedFiles", 0) or 0, + "additions": pr.get("additions", 0) or 0, + "deletions": pr.get("deletions", 0) or 0, + }, + "body": pr.get("body", ""), + "comments": { + "total": comments_overview["total"], + "inline_threads": len(inline_threads), + "has_agent_prompts": has_agent_prompts, + }, + "ci": { + "status": ci_status, + "failing": [f["name"] for f in failing], + "passing_count": len(passing), + "pending_count": len(pending), + }, + "reviews": { + "decision": reviews_overview["decision"], + "approvals": len(reviews_overview["approvals"]), + "changes_requested_by": [cr["user"] for cr in reviews_overview["changes_requested"]], + }, + } + with open(f"{out}/summary.json", "w") as f: + json.dump(summary, f, indent=2, ensure_ascii=False) + + print(f"Structured PR #{summary['number']} -> {out}/", file=sys.stderr) + print(f" Comments: {comments_overview['total']} ({len(inline_threads)} inline)", file=sys.stderr) + print(f" CI: {len(passing)} pass, {len(failing)} fail, {len(pending)} pending", file=sys.stderr) + print(f" Diff: {diff_data['total_files']} files (+{diff_data['additions']}/-{diff_data['deletions']})", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/internal-workflows/pr-overview/CLAUDE.md b/internal-workflows/pr-overview/CLAUDE.md index bebe0496..a148210c 100644 --- a/internal-workflows/pr-overview/CLAUDE.md +++ b/internal-workflows/pr-overview/CLAUDE.md @@ -1,385 +1,92 @@ -# Review Queue — Agent Instructions +# Review Queue -You are an agent that evaluates open pull requests and generates a prioritized review queue — an ordered list of what needs human attention, ranked by urgency and type. +You evaluate all open PRs in a repo and produce a prioritized review queue — what needs human attention, ranked by type and urgency. -## Task Checklist +## What You Do -Create these as your todo items at the start. Mark each one as you complete it — do not stop until all are done. +1. **Fetch all PR data** using the script +2. **Analyze PRs** using the script (blocker checks, type classification) +3. **Evaluate each PR's comments** via sub-agents +4. **Manage the "Review Queue" milestone** — add clean PRs, remove blocked ones +5. **Comment on blocked PRs** with blocker summaries +6. **Write the review queue report** and update the milestone description +7. **Self-evaluate** using `.ambient/rubric.md` -1. **Run fetch-prs.sh** — collect all PR data into artifacts/pr-review/ -2. **Run analyze-prs.py** — produce analysis.json with blocker statuses, type classification, and review order -3. **Evaluate PRs via sub-agents** — spawn parallel sub-agents to deeply read each PR's full comment stream and return verdicts -4. **Find or create Review Queue milestone** — get the milestone number -5. **Sync PRs to milestone** — add clean PRs, remove ones with blockers -6. **Comment on blocked PRs** — post blocker summaries on PRs not in the queue (only if PR was updated since last comment) -7. **Write the review queue report** — fill the template with all data -8. **Update milestone description** — overwrite with the final report -9. **Self-evaluate execution** — read `.ambient/rubric.md` and score your own efficiency (5 criteria, 25 points total) +## Scripts -**Do not stop until all 9 items are done.** The self-evaluation is the final step. - -## Workflow - -### Phase 1: Fetch Data - -Run the fetch script to collect all PR data: +### Fetch ```bash ./scripts/fetch-prs.sh --repo --output-dir artifacts/pr-review ``` -This produces: - -- `artifacts/pr-review/index.json` — summary of all open PRs -- `artifacts/pr-review/prs/{number}.json` — detailed data per PR (**do not read directly** — these can exceed token limits. Use the analysis and summary files instead.) - -### Data Structure Reference - -Each `prs/{number}.json` file has this top-level structure (for reference — the analyze script reads these, you don't need to): - -```json -{ - "pr": { - "number": 123, - "title": "...", - "author": { "login": "username" }, - "isDraft": false, - "isCrossRepository": true, - "headRepositoryOwner": { "login": "fork-owner" }, - "mergeable": "MERGEABLE", - "updatedAt": "2026-02-20T...", - "headRefName": "feat/branch-name", - "body": "PR description text...", - "additions": 42, - "deletions": 18, - "changedFiles": 5, - "labels": [{ "name": "bug" }], - "milestone": { "title": "Review Queue" }, - "statusCheckRollup": [...], - "comments": [...], - "reviewDecision": "APPROVED", - "files": [...] - }, - "reviews": [...], - "review_comments": [...], - "check_runs": [...], - "diff_files": [...] -} +Produces per-PR directories: + +```text +artifacts/pr-review/ +├── index.json # List of all open PRs +├── queue.json # Ranked queue (written by analyze step) +└── {number}/ + ├── summary.json # PR metadata, CI status, comment counts + ├── analysis.json # Blocker statuses, type, fail_count (written by analyze) + ├── comments/ + │ ├── overview.json # Comment counts, has_agent_prompts flag + │ └── 01.json, 02.json... # Chronological comment stream + ├── ci/ + │ └── overview.json # Pass/fail/pending check lists + ├── diff.json # Changed files with patches + └── reviews/ + └── overview.json # Approvals, changes requested ``` -### Phase 2: Analyze PRs - -Run the analysis script to evaluate every PR against the blocker checklist and classify by type: +### Analyze ```bash python3 ./scripts/analyze-prs.py --output-dir artifacts/pr-review ``` -This produces: - -- `artifacts/pr-review/analysis.json` — compact summary with stats, review order, overlap data, and a `pr_index` (one line per PR with number, rank, title, author, type, fail_count, review_status). -- `artifacts/pr-review/analysis/{number}.json` — full per-PR analysis (all blocker statuses, type classification, details). -- `artifacts/pr-review/summaries/{number}.md` — **agent-friendly markdown summary** per PR with blocker table, comment counts, and notes. Read these instead of the raw JSON for quick triage. -- `artifacts/pr-review/reviews/{number}/` — unified chronological comment stream per PR: - - `meta.json` — PR number, title, author, total comment count - - `01.json`, `02.json`, ... — each comment in chronological order with timestamp, author, body, and source hint - -### Phase 3: Sequential PR Evaluation - -Evaluate PRs **one at a time**, starting with the **most recently updated** PR. This avoids context overload and produces more accurate verdicts than bulk processing. - -**Sort the `needs_review` list by `updatedAt` descending** (most recent first). Then for each PR: - -1. **Read the summary:** `artifacts/pr-review/summaries/{number}.md` — gives you the blocker table and comment counts at a glance. -2. **Read review meta:** `artifacts/pr-review/reviews/{number}/meta.json` — check `total_comments`. If 0, verdict is `ready` (no review comments = needs first review, not blocked). -3. **Read comments newest-first:** Start from the highest-numbered file (`05.json`, `04.json`, etc.). -4. **Skip resolved inline comments:** If an inline comment was addressed by a later commit or reply, treat it as resolved. Only flag genuinely unresolved concerns. -5. **Stop early:** Once you've found the latest bot review and have enough context, stop reading older comments. -6. **Record verdict** with these fields: - - **number**: PR number - - **verdict**: `ready` (no blockers), `almost` (1 minor issue), `blocked` (real blockers), `stale` (abandoned) - - **review_summary**: 1-2 sentences — who reviewed, what was raised, whether addressed - - **action_needed**: What a human should do next - - **action_owner**: `@author`, `@reviewer`, `@maintainer`, or specific username - - **blockers_from_comments**: List of genuine blockers (empty if none) - -**Key judgment calls:** -- A bot review from weeks ago on a different commit is stale — note but don't block -- `CHANGES_REQUESTED` + author pushed fix + no re-approval = needs reviewer re-review, not a comment blocker -- "nit" or style suggestions with `CHANGES_REQUESTED` = not a real blocker -- No comments at all = `ready` (needs first review, not blocked) -- Resolved inline threads = ignore - -**Do not rewrite the analysis script.** If you need to adjust a deterministic check, edit `scripts/analyze-prs.py` directly. - -## PR Type Classification - -The analysis script classifies each PR into a type based on labels, branch name, title, and diff shape: - -| Type | Signals | Priority | -|------|---------|----------| -| `bug-fix` | `bug`/`fix` labels, `fix/`/`bugfix/`/`hotfix/` branch, `fix:` title prefix | Highest | -| `feature` | `feature`/`enhancement` labels, `feat/` branch, `feat:` title prefix | High | -| `refactor` | `refactor`/`cleanup` labels, `refactor/` branch, `refactor:` prefix | Medium | -| `chore` | `chore` label, `chore/` branch, CI/config-only changes | Medium | -| `docs` | `docs` label, `docs/` branch, markdown-only changes | Lower | -| `unknown` | No clear signals — sub-agent should refine based on diff content | Lowest | - -The sub-agent can override the script's classification if the diff tells a different story. - -## Blocker Checklist - -For **every** open PR, evaluate each of these categories. Each is either clear or a blocker/warning. - -### 1. CI - -- Check `check_runs` (primary) and `statusCheckRollup` (fallback). -- **Clear:** all completed check runs have conclusion `success` or `neutral` (ignore `skipped`). -- **Warn:** check runs still in progress (`status` is `queued` or `in_progress`) — CI hasn't finished yet. -- **Blocker:** any completed check run with `failure`, `timed_out`, `cancelled`, or `action_required`. List the failing check names. - -### 2. Merge Conflicts - -- Check the `mergeable` field. -- **Clear:** `MERGEABLE`. -- **Warn:** `UNKNOWN` — GitHub hasn't computed mergeability yet. Not a blocker. -- **Blocker:** `CONFLICTING`. Note which files overlap with other open PRs if detectable. - -### 3. Review Comments - -The script handles one deterministic check automatically: -- **CHANGES_REQUESTED** without a subsequent APPROVED or DISMISSED → `FAIL` - -**Inline review comments are NOT blockers.** Most are resolved or addressed by subsequent commits. The script notes them for context but does not count them toward `fail_count`. - -Everything else — bot reviews, human discussion, comment arcs — is evaluated sequentially in Phase 3. When marking a PR as FAIL in the report, include a brief explanation of the actual issue so the team can act on it. - -### 4. Jira Hygiene - -- Scan the PR **title**, **body**, and **branch name** (`headRefName`) for Jira ticket patterns: - - Primary: `RHOAIENG-\d+` - - General: `[A-Z]{2,}-\d+` — but **exclude** non-Jira prefixes: `CVE`, `GHSA`, `HTTP`, `API`, `URL`, `PR`, `WIP` -- **Clear:** at least one Jira reference found. -- **Blocker:** no Jira reference detected. This is a hygiene issue — it should not prevent merging on its own but must be flagged. - -### 5. Fork PR — No Agent Review - -- Check the `is_fork` field in the per-PR analysis. -- **Fork PRs do not receive automated agent reviews** (the Amber review bot only runs on internal branches). -- If `is_fork` is `true`: mark as `warn` with "Fork PR — no automated agent review". This is not a merge blocker, but the report must flag it so a maintainer knows manual review is required. - -### 6. Staleness - -The analysis script flags PRs older than 30 days and detects potential supersession (newer PRs with similar branches/titles). Use your judgment beyond the script's output — the script provides `days_since_update`, `recommend_close`, and `superseded_by` fields as signals, not final verdicts. - -Consider recommending closure for PRs that show multiple signs of abandonment: -- Draft PR + merge conflicts + no activity in 3+ weeks -- Multiple blockers + no updates in 30+ days -- Superseded by a newer PR from the same author -- Very old (60+ days) regardless of other signals - -Use the condensed "Recommend Closing" table instead of a full blocker breakdown for these. - -## Ranking Logic - -Produce a single ranked list of all open PRs, ordered by what needs human attention first: - -1. **PR type** — bug fixes before features before refactors before docs/chores. Unknown types sort after features. -2. **Blocker count** — within the same type, PRs with zero blockers first. -3. **Readiness** — PRs that just need a human approval rank above PRs that need author work. -4. **Size (smaller first)** — PRs with fewer changed files and smaller diffs rank higher. Small PRs are faster to review. -5. **Priority labels** — `priority/critical`, `bug`, `hotfix` labels boost rank within their tier. -6. **Dependency chains** — if a PR's branch is based on another PR's branch, the base PR must rank higher. Note these explicitly. -7. **Draft PRs last** — drafts always sort to the bottom regardless of other signals. - -## Status Indicators - -Use these in the **Status** column of the per-PR blocker table: - -| Status | Meaning | -|--------|---------| -| `pass` | No issues detected | -| `FAIL` | Blocker — must be resolved before merge | -| `warn` | Hygiene / informational issue — does not block merge | - -## Output Format - -Use the template at `templates/review-queue.md`. Populate it from `analysis.json` and sub-agent verdicts. - -### Dates - -Use absolute dates in `YYYY-MM-DD` format (e.g., `2026-02-27`). Do not use relative dates like "2 days ago" — the report is stored in the milestone description and becomes stale. - -### At a Glance - -A 2-3 sentence summary at the top of the report. Mention how many PRs are ready for review, call out the top 3-4 by number and type, and flag any notable concerns (e.g., "3 PRs recommended for closure", "6 PRs blocked by merge conflicts"). +Reads each `summary.json`, writes `analysis.json` per PR and `queue.json` at top level. -### Ready for Review (condensed table) +## Sub-Agent Evaluation -PRs with `fail_count == 0` and `isDraft == false` go in the condensed summary table — one row per PR. List them in review order (bug fixes first, smallest first). +The analyze script handles mechanical checks. Sub-agents handle the nuanced part — reading comment conversations and making judgment calls. -For fork PRs (`is_fork == true`), add "Fork — no agent review" to the Notes column. +Spawn sub-agents in parallel (batches of ~10). Each reads `summary.json` + `comments/` for its PRs and returns: -The **Action Needed** column: what a human reviewer should do (from sub-agent verdict). +- **verdict**: ready / almost / blocked / stale +- **review_summary**: who reviewed, what was raised, was it addressed +- **action_needed**: what a human should do next +- **action_owner**: who needs to act -### PRs With Blockers (full tables) +Key judgment calls: +- Stale bot review on old commit = not blocking +- Author pushed a fix but no re-approval = needs reviewer, not a blocker +- "nit" with CHANGES_REQUESTED state = not a real blocker +- Unresolved substantive disagreement = blocked -PRs with `fail_count > 0` and `isDraft == false` get the full blocker table. PRs flagged with `recommend_close == true` go in the "Recommend Closing" table instead. +## Ranking -### Fork PRs +Bug fixes > features > refactors > docs. Fewer blockers first. Smaller first. Drafts last. -Fork PRs are **not** separated into their own section. They appear in the same Ready for Review or PRs With Blockers tables as internal PRs, based on their blocker count. +## Milestone -To signal that a PR is from a fork, add "Fork (`fork_owner`) — no agent review" to the **Notes** column. +Find or create **"Review Queue"** milestone (also check for "Merge Queue"). Add clean PRs, remove blocked ones. Overwrite description with the report. -### Recommend Closing +## Blocker Comments -PRs flagged by the script (`recommend_close == true`) or that you judge to be abandoned. One-row-per-PR table with: PR link, author, reason, last updated. +Post on PRs with `fail_count > 0` using `` marker. Skip if unchanged since last comment. Skip drafts and recommend-close PRs. -## Phase 4: Milestone Management +## Report -Manage the **"Review Queue"** milestone. This milestone acts as a living bucket of ready-to-review PRs — no due date, never closed, updated every run. The milestone description stores the report. +Use `templates/review-queue.md`. Ready PRs in a condensed table, blocked PRs with full blocker tables, recommend-close PRs in a separate table. -**Important: complete milestone sync BEFORE writing the final report** so that `{{MILESTONE_COUNT}}` in the report is accurate. - -### Step 1: Find or create the milestone - -```bash -# Find existing milestone (check both names for backward compat) -MILESTONE_NUM=$(gh api "repos/{owner}/{repo}/milestones" --jq '.[] | select(.title=="Review Queue" or .title=="Merge Queue") | .number') - -# If not found, create it -if [ -z "$MILESTONE_NUM" ]; then - MILESTONE_NUM=$(gh api "repos/{owner}/{repo}/milestones" \ - -f title="Review Queue" \ - -f state=open \ - -f description="Auto-managed by Review Queue workflow" \ - --jq '.number') -fi -``` - -### Step 2: Sync PRs to the milestone - -First, get the list of PRs currently in the milestone: - -```bash -gh api "repos/{owner}/{repo}/issues?milestone=${MILESTONE_NUM}&state=all&per_page=100" \ - --jq '.[] | {number: .number, state: .state, pull_request: .pull_request.merged_at}' -``` - -Then sync: - -- **Remove** PRs that are merged, closed, or now have blockers: - ```bash - gh api -X PATCH "repos/{owner}/{repo}/issues/{number}" -F milestone=null - ``` -- **Add** open PRs with **0 blockers** (all statuses are `pass` or `warn`, no `FAIL`): - ```bash - gh api -X PATCH "repos/{owner}/{repo}/issues/{number}" -F milestone=${MILESTONE_NUM} - ``` -- **Never** add draft PRs to the milestone. - -**Note:** Use the REST API (`gh api -X PATCH .../issues/{number}`) instead of `gh pr edit --milestone`, which requires `read:org` scope that runners typically lack. - -After syncing, count the PRs now in the milestone — this is `{{MILESTONE_COUNT}}` for the report. - -### Step 3: Reorder PRs in the milestone to match review order - -GitHub supports reordering issues within a milestone via a GraphQL mutation. After syncing, reorder the PRs to match the `review_order` from the analysis. - -```bash -# Get milestone node ID -MILESTONE_NODE_ID=$(gh api "repos/{owner}/{repo}/milestones/${MILESTONE_NUM}" --jq '.node_id') - -# Get PR node IDs (for each PR in review_order) -PR_NODE_ID=$(gh api "repos/{owner}/{repo}/pulls/{number}" --jq '.node_id') - -# Reorder -gh api graphql -f query=' - mutation { - reprioritizeMilestoneIssue(input: { - id: "{pr_node_id}", - milestoneId: "{milestone_node_id}", - prevId: "{previous_pr_node_id}" - }) { - clientMutationId - } - } -' -``` - -For the first PR in the order, omit `prevId`. If the mutation fails, skip silently. - -### Step 4: Write the final report - -Now that milestone sync is complete and `{{MILESTONE_COUNT}}` is known, write the final report to `artifacts/pr-review/review-queue-{YYYY-MM-DD}.md` using the template. - -### Step 5: Update milestone description with the report - -```bash -REPORT=$(cat artifacts/pr-review/review-queue-{date}.md) -TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC') -DESCRIPTION="**Last updated:** ${TIMESTAMP} - -${REPORT}" - -gh api -X PATCH "repos/{owner}/{repo}/milestones/${MILESTONE_NUM}" \ - -f description="${DESCRIPTION}" -``` - -### Milestone constraints - -- The milestone has **no due date** — it persists as a running bucket. -- Do **NOT** close the milestone — it is reused across runs. -- The description is **overwritten** each run (not appended). -- Always include the `Last updated` timestamp at the top. - -## Phase 6: Comment on Blocked PRs - -After milestone sync, post a blocker summary comment on each PR that has blockers (`fail_count > 0`) and was **not** added to the Review Queue. - -**All comments are identified by a hidden HTML marker:** `` at the end of the comment body. - -### Noise reduction rules - -1. **Find existing comment:** Look for one containing `` (also check for legacy `` marker). -2. **Check freshness:** Compare the PR's `updatedAt` with the comment's `created_at`. - - If the PR was **not updated** since the last comment — **skip**. - - If the PR **was updated** — **delete** the old comment, then **post** a new one. -3. **No existing comment:** Post a new comment. - -### Comment format - -```markdown -### Review Queue — Blockers Found - -| Check | Status | Detail | -|-------|--------|--------| -| CI | FAIL | `build` failed | -| Merge conflicts | pass | --- | -| Review comments | FAIL | Changes requested by @reviewer | -| Jira hygiene | pass | RHOAIENG-1234 | -| Staleness | pass | --- | -| Diff overlap risk | pass | --- | - -**Action needed:** Author needs to fix CI and address review comments. - -> This comment is auto-generated by the Review Queue workflow and will be updated when the PR changes. - - -``` - -Include the **Action needed** line from the sub-agent verdict when available. - -### What to skip - -- **Clean PRs** (fail_count == 0) — no comment needed, they're in the queue. -- **Draft PRs** — don't comment on drafts. -- **PRs recommended for closing** — don't comment, they'll be flagged in the report. - -## Important Notes +## Blocker Checklist -- Do NOT approve or merge any PRs. This workflow is read-only (except for milestone management and blocker comments). -- If the fetch script fails, report the error clearly and stop. -- Always include the PR URL as a link: `[#123](url)`. -- Size format: `X files (+A/-D)` where A = additions, D = deletions. +| Check | Clear | Warn | Blocker | +|-------|-------|------|---------| +| CI | All pass | In progress | Any failed | +| Conflicts | MERGEABLE | UNKNOWN | CONFLICTING | +| Reviews | No issues | — | CHANGES_REQUESTED, sub-agent FAIL | +| Jira | Reference found | No reference | — | +| Fork | Internal | Fork (no bot review) | — | +| Staleness | < 30 days | — | > 30 days | diff --git a/internal-workflows/pr-overview/scripts/analyze-prs.py b/internal-workflows/pr-overview/scripts/analyze-prs.py index e833c05e..d0a8263b 100755 --- a/internal-workflows/pr-overview/scripts/analyze-prs.py +++ b/internal-workflows/pr-overview/scripts/analyze-prs.py @@ -1,27 +1,23 @@ #!/usr/bin/env python3 """ -Analyze all fetched PR data against the blocker checklist and produce analysis.json. +Analyze structured PR data and produce per-PR analysis + ranked queue. + +Reads: {output-dir}/{number}/summary.json (and diff.json for overlaps) +Writes: {output-dir}/{number}/analysis.json + {output-dir}/queue.json Usage: python3 scripts/analyze-prs.py --output-dir artifacts/pr-review - -Input: {output-dir}/index.json and {output-dir}/prs/{number}.json -Output: {output-dir}/analysis.json """ import argparse import json import os import re -import sys -from collections import defaultdict -from datetime import datetime, timedelta, timezone - +from datetime import datetime, timezone -# -- Jira exclusions -- JIRA_EXCLUDE = {"CVE", "GHSA", "HTTP", "API", "URL", "PR", "WIP"} -# -- PR type priority (lower = higher priority in the queue) -- TYPE_SIGNALS = { "bug-fix": { "labels": {"bug", "bugfix", "fix"}, @@ -50,840 +46,255 @@ }, } -TYPE_PRIORITY = { - "bug-fix": 0, - "feature": 1, - "unknown": 2, - "refactor": 3, - "chore": 4, - "docs": 5, -} - - -def parse_date(s): - if not s: - return None - try: - return datetime.fromisoformat(s.replace("Z", "+00:00")) - except Exception: - return None - +TYPE_PRIORITY = {"bug-fix": 0, "feature": 1, "unknown": 2, "refactor": 3, "chore": 4, "docs": 5} -# -- PR type classification -- - - -def classify_pr_type(title, branch, labels, diff_files=None): - """Classify a PR by type based on available signals.""" - label_names = {lb.lower() for lb in labels} - branch_lower = (branch or "").lower() - title_lower = (title or "").lower().strip() +def classify_type(summary): + labels = {lb.lower() for lb in summary.get("labels", [])} + branch = (summary.get("branch") or "").lower() + title = (summary.get("title") or "").lower().strip() for pr_type, signals in TYPE_SIGNALS.items(): - if label_names & signals["labels"]: + if labels & signals["labels"]: return pr_type - for pr_type, signals in TYPE_SIGNALS.items(): - if any(branch_lower.startswith(p) for p in signals["branches"]): + if any(branch.startswith(p) for p in signals["branches"]): return pr_type - for pr_type, signals in TYPE_SIGNALS.items(): - if any(title_lower.startswith(p) for p in signals["titles"]): + if any(title.startswith(p) for p in signals["titles"]): return pr_type - - # Heuristic: if diff is available, check file types - if diff_files: - filenames = [df.get("filename", "") for df in diff_files] - md_count = sum(1 for f in filenames if f.endswith(".md")) - ci_count = sum( - 1 - for f in filenames - if ".github/" in f - or f.endswith((".yml", ".yaml")) - or f in ("Makefile", "Dockerfile", ".dockerignore", ".gitignore") - ) - - if md_count == len(filenames) and len(filenames) > 0: - return "docs" - if ci_count == len(filenames) and len(filenames) > 0: - return "chore" - - # Check title keywords as last resort - if title_lower: - if any(w in title_lower for w in ("fix ", "fixed ", "fixes ", "bug")): - return "bug-fix" - + if title and any(w in title for w in ("fix ", "fixed ", "fixes ", "bug")): + return "bug-fix" return "unknown" -# -- Blocker checks -- - - -def check_ci(check_runs, status_rollup): - """Evaluate CI status. Returns (status, detail).""" - if check_runs: - failing = [ - cr - for cr in check_runs - if cr.get("status") == "completed" - and cr.get("conclusion") - in ("failure", "timed_out", "cancelled", "action_required") - ] - if failing: - names = [cr.get("name", "unknown") for cr in failing[:3]] - extra = len(failing) - 3 - detail = ", ".join(names) - if extra > 0: - detail += f" (+{extra} more)" - return "FAIL", f"Failing: {detail}" - - in_progress = [ - cr - for cr in check_runs - if cr.get("status") in ("queued", "in_progress") - ] - if in_progress: - names = [cr.get("name", "unknown") for cr in in_progress[:3]] - return "warn", f"CI in progress: {', '.join(names)}" - - return "pass", "\u2014" - - if status_rollup: - failing = [ - s - for s in status_rollup - if s.get("conclusion", "").upper() - in ("FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED") - or s.get("state", "").upper() in ("FAILURE", "ERROR") - ] - if failing: - names = [ - s.get("name", "") or s.get("context", "unknown") for s in failing[:3] - ] - extra = len(failing) - 3 - detail = ", ".join(names) - if extra > 0: - detail += f" (+{extra} more)" - return "FAIL", f"Failing: {detail}" - - pending = [ - s - for s in status_rollup - if s.get("state", "").upper() in ("PENDING", "EXPECTED") - ] - if pending: - return "warn", "CI pending" - +def check_ci(summary): + ci = summary.get("ci", {}) + failing = ci.get("failing", []) + if ci.get("status") == "failing": + detail = ", ".join(failing[:3]) + if len(failing) > 3: + detail += f" (+{len(failing) - 3} more)" + return "FAIL", f"Failing: {detail}" + if ci.get("status") == "pending": + return "warn", "CI in progress" return "pass", "\u2014" -def check_conflicts(mergeable): - if mergeable == "MERGEABLE": +def check_conflicts(summary): + m = summary.get("mergeable", "UNKNOWN") + if m == "MERGEABLE": return "pass", "\u2014" - elif mergeable == "CONFLICTING": + if m == "CONFLICTING": return "FAIL", "Has merge conflicts" - elif mergeable == "UNKNOWN": + if m == "UNKNOWN": return "warn", "Merge status not yet computed" - else: - return "FAIL", f"Conflict status: {mergeable or 'unknown'}" - - -def check_reviews(reviews, review_comments, pr_comments, fetch_ok=True): - """Handle deterministic review checks only. Comment evaluation is the sub-agent's job. - - Returns (status, detail, has_comments). - """ - if not fetch_ok: - return "FAIL", "PR data incomplete \u2014 fetch may have failed", True - - issues = [] - - # Check for unresolved CHANGES_REQUESTED - user_states = {} - for r in reviews: - login = r.get("user", {}).get("login", "") - state = r.get("state", "") - if state == "CHANGES_REQUESTED": - user_states[login] = "CHANGES_REQUESTED" - elif state in ("APPROVED", "DISMISSED"): - if user_states.get(login) == "CHANGES_REQUESTED": - user_states[login] = state - - unresolved = [u for u, s in user_states.items() if s == "CHANGES_REQUESTED"] - if unresolved: - issues.append( - f"CHANGES_REQUESTED from {', '.join('@' + u for u in unresolved)}" - ) - - # Note inline review comments (informational, not a blocker — most are resolved) - if review_comments: - paths = set(c.get("path", "") for c in review_comments if c.get("path")) - if paths: - # Don't add to issues — inline comments are not blockers. - # They're noted in the summary but don't contribute to fail_count. - pass - - # Check if there are any comments worth reviewing - has_comments = bool(pr_comments) or any(r.get("body") for r in reviews) - - if issues: - return "FAIL", "; ".join(issues), has_comments - if has_comments: - return "needs_review", "Has comments \u2014 sub-agent to evaluate", True - return "pass", "\u2014", False - - -def check_jira(title, body, branch): - text = (title or "") + " " + (body or "") + " " + (branch or "") + return "FAIL", f"Conflict status: {m}" + + +def check_reviews(summary): + reviews = summary.get("reviews", {}) + comments = summary.get("comments", {}) + cr_by = reviews.get("changes_requested_by", []) + if cr_by: + return "FAIL", f"CHANGES_REQUESTED from {', '.join('@' + u for u in cr_by)}" + if comments.get("inline_threads", 0) > 0: + return "needs_review", f"{comments['inline_threads']} inline threads" + if comments.get("total", 0) > 0: + return "needs_review", "Has comments" + return "pass", "\u2014" + + +def check_jira(summary): + text = " ".join([summary.get("title", ""), summary.get("body", ""), summary.get("branch", "")]) if re.search(r"RHOAIENG-\d+", text): return "pass", "\u2014" for m in re.finditer(r"([A-Z]{2,})-\d+", text): - prefix = m.group(1) - if prefix not in JIRA_EXCLUDE: + if m.group(1) not in JIRA_EXCLUDE: return "pass", "\u2014" return "warn", "No Jira reference found" -def check_staleness(updated_at_str, now): - if not updated_at_str: - return "FAIL", "No updatedAt date found", {"days_old": None} - updated = parse_date(updated_at_str) +def check_staleness(summary, now): + updated = summary.get("updatedAt", "") if not updated: - return "FAIL", "Cannot parse date", {"days_old": None} - days_old = (now - updated).days - if days_old > 30: - return ( - "FAIL", - f"Last updated {updated.date()} \u2014 {days_old} days ago", - {"days_old": days_old}, - ) - return "pass", "\u2014", {"days_old": days_old} - - -# -- Superseded PR detection -- - - -def detect_superseded(results, index_map): - pr_files = {} - for r in results: - num = r["number"] - idx = index_map.get(num, {}) - pr_files[num] = { - "branch": r["branch"], - "title": r["title"].lower(), - "created": idx.get("createdAt", ""), - "updated": r["updatedAt"], - "is_draft": r["isDraft"], - "changed_files": idx.get("changedFiles", 0), - } - - superseded = {} - - for r in results: - num = r["number"] - info = pr_files[num] - - for other in results: - other_num = other["number"] - if other_num == num: - continue - other_info = pr_files[other_num] - - if other_info["created"] <= info["created"]: - continue - - if ( - info["branch"] - and other_info["branch"] - and info["branch"] in other_info["branch"] - and info["branch"] != other_info["branch"] - ): - superseded[num] = other_num - break - - if ( - len(info["title"]) > 15 - and len(other_info["title"]) > 15 - and ( - info["title"] in other_info["title"] - or other_info["title"] in info["title"] - ) - and info["created"] < other_info["created"] - ): - superseded[num] = other_num - break - - return superseded - - -# -- Diff hunk overlap analysis -- + return "FAIL", "No updatedAt date", None + try: + dt = datetime.fromisoformat(updated.replace("Z", "+00:00")) + except Exception: + return "FAIL", "Cannot parse date", None + days = (now - dt).days + if days > 30: + return "FAIL", f"Last updated {dt.date()} \u2014 {days} days ago", days + return "pass", "\u2014", days def parse_hunks(patch): if not patch: return [] - hunks = [] - for m in re.finditer(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", patch): - start = int(m.group(1)) - count = int(m.group(2)) if m.group(2) is not None else 1 - hunks.append((start, start + count - 1)) - return hunks - - -def hunks_overlap(h1, h2): - return h1[0] <= h2[1] and h2[0] <= h1[1] + return [ + (int(m.group(1)), int(m.group(1)) + int(m.group(2) or 1) - 1) + for m in re.finditer(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", patch) + ] -def compute_overlaps(pr_file_hunks): - nums = sorted(pr_file_hunks.keys()) +def compute_overlaps(pr_hunks): + nums = sorted(pr_hunks.keys()) overlaps = [] - shared_no_overlap = [] - - for i, num_a in enumerate(nums): - for num_b in nums[i + 1 :]: - files_a = set(pr_file_hunks[num_a].keys()) - files_b = set(pr_file_hunks[num_b].keys()) - shared = files_a & files_b - - if not shared: - continue - - has_overlap = False + for i, a in enumerate(nums): + for b in nums[i + 1:]: + shared = set(pr_hunks[a]) & set(pr_hunks[b]) for fname in shared: - for ha in pr_file_hunks[num_a][fname]: - for hb in pr_file_hunks[num_b][fname]: - if hunks_overlap(ha, hb): - overlaps.append( - { - "pr_a": num_a, - "pr_b": num_b, - "file": fname, - "range_a": list(ha), - "range_b": list(hb), - } - ) - has_overlap = True - - if not has_overlap: - shared_no_overlap.append( - {"pr_a": num_a, "pr_b": num_b, "shared_files": list(shared)} - ) - - return overlaps, shared_no_overlap - - -# -- Review order computation -- - - -def compute_review_order(results, overlaps, pr_file_hunks): - """Compute a recommended review/merge sequence for clean, mergeable PRs.""" - clean_mergeable = [ - r["number"] - for r in results - if not r["isDraft"] and r["fail_count"] == 0 and r["conflict_status"] == "pass" - ] - - if not clean_mergeable: - return [] - - overlap_graph = defaultdict(set) - for o in overlaps: - if o["pr_a"] in clean_mergeable and o["pr_b"] in clean_mergeable: - overlap_graph[o["pr_a"]].add(o["pr_b"]) - overlap_graph[o["pr_b"]].add(o["pr_a"]) - - pr_map = {r["number"]: r for r in results} - ordered = [] - remaining = set(clean_mergeable) - - while remaining: - best = min( - remaining, - key=lambda n: ( - TYPE_PRIORITY.get(pr_map[n]["pr_type"], 99), - len(overlap_graph.get(n, set()) & remaining), - 0 if pr_map[n]["has_priority"] else 1, - pr_map[n]["size_score"], - ), - ) - ordered.append(best) - remaining.remove(best) - - return ordered - - -# -- Unified comment stream extraction -- - - -def merge_comment_sources(pr_comments, reviews, review_comments): - """Merge all comment sources into a single chronological list. - - This is the shared implementation — pr-fixer/scripts/merge-comments.py - has an identical copy for CLI use. Keep them in sync. - """ - all_comments = [] - - for c in pr_comments: - all_comments.append( - { - "source": "pr_comment", - "author": c.get("author", {}).get("login", ""), - "timestamp": c.get("createdAt", ""), - "body": c.get("body", ""), - } - ) - - for r in reviews: - body = r.get("body", "") - if not body or not body.strip(): - continue - all_comments.append( - { - "source": "review", - "author": r.get("user", {}).get("login", ""), - "state": r.get("state", ""), - "timestamp": r.get("submitted_at", ""), - "body": body, - } - ) - - for rc in review_comments: - body = rc.get("body", "") - if not body or not body.strip(): - continue - all_comments.append( - { - "source": "inline_comment", - "author": rc.get("user", {}).get("login", ""), - "path": rc.get("path", ""), - "timestamp": rc.get("created_at", ""), - "body": body, - } - ) - - all_comments.sort(key=lambda c: c.get("timestamp", "")) - return all_comments - - -def extract_unified_comments(pr_data): - """Extract and merge all comments from a PR data dict.""" - return merge_comment_sources( - pr_data.get("pr", {}).get("comments", []), - pr_data.get("reviews", []), - pr_data.get("review_comments", []), - ) - - -# -- Main -- + for ha in pr_hunks[a][fname]: + for hb in pr_hunks[b][fname]: + if ha[0] <= hb[1] and hb[0] <= ha[1]: + overlaps.append({"pr_a": a, "pr_b": b, "file": fname}) + return overlaps def main(): - parser = argparse.ArgumentParser(description="Analyze PRs for review readiness") - parser.add_argument( - "--output-dir", - default="artifacts/pr-review", - help="Directory with fetched PR data", - ) + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", default="artifacts/pr-review") args = parser.parse_args() - output_dir = args.output_dir now = datetime.now(timezone.utc) - with open(os.path.join(output_dir, "index.json")) as f: - index = json.load(f) - index_map = {pr["number"]: pr for pr in index} - - results = [] - pr_file_hunks = {} - pr_data_cache = {} # stash pr_data for needs_review PRs to avoid re-reading - - for idx_pr in index: - num = idx_pr["number"] - pr_file = os.path.join(output_dir, "prs", f"{num}.json") - - pr_data = {} - fetch_ok = False - try: - with open(pr_file) as f: - pr_data = json.load(f) - fetch_ok = bool(pr_data.get("pr")) - except (FileNotFoundError, json.JSONDecodeError): - pass - - pr = pr_data.get("pr", {}) - reviews = pr_data.get("reviews", []) - review_comments = pr_data.get("review_comments", []) - check_runs = pr_data.get("check_runs", []) - diff_files = pr_data.get("diff_files", []) - - title = pr.get("title") or idx_pr.get("title", "") - author = (pr.get("author") or idx_pr.get("author", {})).get("login", "unknown") - is_draft = pr.get("isDraft", idx_pr.get("isDraft", False)) - mergeable = pr.get("mergeable") or idx_pr.get("mergeable", "UNKNOWN") - updated_at = pr.get("updatedAt") or idx_pr.get("updatedAt", "") - created_at = pr.get("createdAt") or idx_pr.get("createdAt", "") - branch = pr.get("headRefName") or idx_pr.get("headRefName", "") - body = pr.get("body") or idx_pr.get("body", "") - url = pr.get("url") or idx_pr.get("url", "") - additions = pr.get("additions", idx_pr.get("additions", 0)) or 0 - deletions = pr.get("deletions", idx_pr.get("deletions", 0)) or 0 - changed_files = pr.get("changedFiles", idx_pr.get("changedFiles", 0)) or 0 - labels = [ - lb.get("name", "") for lb in (pr.get("labels") or idx_pr.get("labels", [])) - ] - is_fork = pr.get( - "isCrossRepository", idx_pr.get("isCrossRepository", False) - ) - fork_owner = ( - pr.get("headRepositoryOwner") - or idx_pr.get("headRepositoryOwner") - or {} - ).get("login", "") - milestone = pr.get("milestone") - milestone_title = milestone.get("title", "") if milestone else "" - pr_comments = pr.get("comments", []) - status_rollup = pr.get("statusCheckRollup", []) - - # Classify PR type - pr_type = classify_pr_type(title, branch, labels, diff_files) - - # Run blocker checks - ci_status, ci_detail = check_ci(check_runs, status_rollup) - conflict_status, conflict_detail = check_conflicts(mergeable) - review_status, review_detail, has_comments = check_reviews( - reviews, review_comments, pr_comments, fetch_ok - ) - if review_status == "needs_review": - pr_data_cache[num] = pr_data - jira_status, jira_detail = check_jira(title, body, branch) - stale_status, stale_detail, staleness_data = check_staleness(updated_at, now) - - fail_count = sum( - 1 - for s in [ci_status, conflict_status, review_status, stale_status] - if s == "FAIL" - ) - - has_priority = any( - lb in ("priority/critical", "bug", "hotfix", "priority/high") - for lb in labels - ) - - size_score = additions + deletions + changed_files * 10 - size_str = f"{changed_files} files (+{additions}/-{deletions})" - - if not is_draft and mergeable == "MERGEABLE" and diff_files: - file_hunks = {} - for df in diff_files: - fname = df.get("filename", "") - patch = df.get("patch", "") - hunks = parse_hunks(patch) - if fname and hunks: - file_hunks[fname] = hunks - if file_hunks: - pr_file_hunks[num] = file_hunks - - results.append( - { - "number": num, - "rank": 0, - "title": title, - "url": url, - "author": author, - "isDraft": is_draft, - "is_fork": is_fork, - "fork_owner": fork_owner, - "pr_type": pr_type, - "size": size_str, - "size_score": size_score, - "updatedAt": updated_at[:10] if updated_at else "", - "createdAt": created_at[:10] if created_at else "", - "branch": branch, - "labels": labels, - "milestoneCurrently": milestone_title, - "ci_status": ci_status, - "ci_detail": ci_detail, - "conflict_status": conflict_status, - "conflict_detail": conflict_detail, - "review_status": review_status, - "review_detail": review_detail, - "has_comments": has_comments, - "jira_status": jira_status, - "jira_detail": jira_detail, - "stale_status": stale_status, - "stale_detail": stale_detail, - "days_since_update": staleness_data["days_old"], - "overlap_status": "\u2014", - "overlap_detail": "\u2014", - "notes": "", - "fail_count": fail_count, - "has_priority": has_priority, - "superseded_by": None, - "recommend_close": False, - "recommend_close_reason": "", - } - ) - - # Detect superseded PRs - superseded = detect_superseded(results, index_map) - for r in results: - if r["number"] in superseded: - r["superseded_by"] = superseded[r["number"]] - r["notes"] = f"May be superseded by #{superseded[r['number']]}" - - # Compute diff overlaps - overlaps, shared_no_overlap = compute_overlaps(pr_file_hunks) - - # Set overlap status per PR - pr_map = {r["number"]: r for r in results} - overlap_prs = set() - warn_prs = set() - - for o in overlaps: - overlap_prs.add(o["pr_a"]) - overlap_prs.add(o["pr_b"]) + pr_dirs = [ + e for e in os.listdir(output_dir) + if os.path.isdir(os.path.join(output_dir, e)) + and os.path.exists(os.path.join(output_dir, e, "summary.json")) + ] + if not pr_dirs: + print("No PR data found.") + return - for s in shared_no_overlap: - if s["pr_a"] not in overlap_prs: - warn_prs.add(s["pr_a"]) - if s["pr_b"] not in overlap_prs: - warn_prs.add(s["pr_b"]) + summaries = {} + for d in pr_dirs: + with open(os.path.join(output_dir, d, "summary.json")) as f: + summaries[d] = json.load(f) + results = [] + pr_hunks = {} + + for pr_dir, s in summaries.items(): + num = s["number"] + pr_type = classify_type(s) + ci_status, ci_detail = check_ci(s) + conflict_status, conflict_detail = check_conflicts(s) + review_status, review_detail = check_reviews(s) + jira_status, jira_detail = check_jira(s) + stale_status, stale_detail, days_old = check_staleness(s, now) + + if not s.get("isDraft") and s.get("mergeable") == "MERGEABLE": + diff_path = os.path.join(output_dir, pr_dir, "diff.json") + try: + with open(diff_path) as f: + diff_data = json.load(f) + fh = {} + for df in diff_data.get("files", []): + hunks = parse_hunks(df.get("patch", "")) + if df.get("filename") and hunks: + fh[df["filename"]] = hunks + if fh: + pr_hunks[num] = fh + except (FileNotFoundError, json.JSONDecodeError): + pass + + size = s.get("size", {}) + has_priority = any(lb in ("priority/critical", "bug", "hotfix", "priority/high") for lb in s.get("labels", [])) + + results.append({ + "number": num, "title": s.get("title", ""), "url": s.get("url", ""), + "author": s.get("author", ""), "isDraft": s.get("isDraft", False), + "isFork": s.get("isFork", False), "forkOwner": s.get("forkOwner", ""), + "pr_type": pr_type, + "size": f"{size.get('files', 0)} files (+{size.get('additions', 0)}/-{size.get('deletions', 0)})", + "size_score": size.get("additions", 0) + size.get("deletions", 0) + size.get("files", 0) * 10, + "updatedAt": (s.get("updatedAt") or "")[:10], "createdAt": (s.get("createdAt") or "")[:10], + "branch": s.get("branch", ""), "labels": s.get("labels", []), + "ci_status": ci_status, "ci_detail": ci_detail, + "conflict_status": conflict_status, "conflict_detail": conflict_detail, + "review_status": review_status, "review_detail": review_detail, + "jira_status": jira_status, "jira_detail": jira_detail, + "stale_status": stale_status, "stale_detail": stale_detail, + "days_since_update": days_old, + "overlap_status": "\u2014", "overlap_detail": "\u2014", + "fail_count": 0, "has_priority": has_priority, + "recommend_close": False, "recommend_close_reason": "", + }) + + overlaps = compute_overlaps(pr_hunks) + overlap_prs = {o["pr_a"] for o in overlaps} | {o["pr_b"] for o in overlaps} for r in results: num = r["number"] - if r["isDraft"] or r["conflict_status"] == "FAIL": - r["overlap_status"] = "\u2014" - r["overlap_detail"] = "\u2014" - elif num in overlap_prs: - partners = set() - files = set() + if not r["isDraft"] and r["conflict_status"] != "FAIL" and num in overlap_prs: + partners, files = set(), set() for o in overlaps: - if o["pr_a"] == num: - partners.add(o["pr_b"]) - files.add(o["file"]) - elif o["pr_b"] == num: - partners.add(o["pr_a"]) - files.add(o["file"]) - partner_str = ", ".join(f"#{p}" for p in sorted(partners)) - file_str = ", ".join(sorted(files)[:2]) + if o["pr_a"] == num: partners.add(o["pr_b"]); files.add(o["file"]) + elif o["pr_b"] == num: partners.add(o["pr_a"]); files.add(o["file"]) r["overlap_status"] = "FAIL" - r["overlap_detail"] = f"Line overlap with {partner_str} on {file_str}" - if not r["notes"]: - r["notes"] = f"Merge order matters: overlaps with {partner_str}" - elif num in warn_prs: - r["overlap_status"] = "warn" - r["overlap_detail"] = "Shares files but no line overlap" - elif num in pr_file_hunks: + r["overlap_detail"] = f"Line overlap with {', '.join(f'#{p}' for p in sorted(partners))} on {', '.join(sorted(files)[:2])}" + elif num in pr_hunks: r["overlap_status"] = "pass" - r["overlap_detail"] = "\u2014" - # Recompute fail_count now that overlap_status is set for r in results: - r["fail_count"] = sum( - 1 - for s in [r["ci_status"], r["conflict_status"], r["review_status"], - r["stale_status"], r["overlap_status"]] - if s == "FAIL" - ) - - # Flag PRs to recommend closing + r["fail_count"] = sum(1 for s in [r["ci_status"], r["conflict_status"], r["review_status"], r["stale_status"], r["overlap_status"]] if s == "FAIL") + for r in results: reasons = [] days = r["days_since_update"] - if r["isDraft"] and days is not None and days > 21 and r["conflict_status"] == "FAIL": + if r["isDraft"] and days and days > 21 and r["conflict_status"] == "FAIL": reasons.append(f"Draft with conflicts, inactive {days}d") - if r["superseded_by"]: - reasons.append(f"Superseded by #{r['superseded_by']}") - if days is not None and days > 60: + if days and days > 60: reasons.append(f"Inactive for {days} days") - if days is not None and days > 30 and r["fail_count"] >= 2: + if days and days > 30 and r["fail_count"] >= 2: reasons.append(f"Stale ({days}d) with {r['fail_count']} blockers") if reasons: r["recommend_close"] = True r["recommend_close_reason"] = "; ".join(reasons) - # Rank PRs: type priority, then blocker count, then priority labels, then size - results.sort( - key=lambda r: ( - 1 if r["isDraft"] else 0, - TYPE_PRIORITY.get(r["pr_type"], 99), - r["fail_count"], - 0 if r["has_priority"] else 1, - r["size_score"], - ) - ) + results.sort(key=lambda r: (1 if r["isDraft"] else 0, TYPE_PRIORITY.get(r["pr_type"], 99), r["fail_count"], 0 if r["has_priority"] else 1, r["size_score"])) for i, r in enumerate(results): r["rank"] = i + 1 - # Compute review order for clean PRs - review_order = compute_review_order(results, overlaps, pr_file_hunks) + review_order = [r["number"] for r in results if not r["isDraft"] and r["fail_count"] == 0 and r["conflict_status"] == "pass"] + needs_review = [r["number"] for r in results if r["review_status"] == "needs_review"] + + for r in results: + p = os.path.join(output_dir, str(r["number"]), "analysis.json") + if os.path.isdir(os.path.join(output_dir, str(r["number"]))): + with open(p, "w") as f: + json.dump(r, f, indent=2, ensure_ascii=False) - # Stats non_draft = [r for r in results if not r["isDraft"]] stats = { - "total": len(results), - "drafts": len(results) - len(non_draft), + "total": len(results), "drafts": len(results) - len(non_draft), "clean": sum(1 for r in non_draft if r["fail_count"] == 0), "one_blocker": sum(1 for r in non_draft if r["fail_count"] == 1), "needs_work": sum(1 for r in non_draft if r["fail_count"] >= 2), "recommend_close": sum(1 for r in results if r["recommend_close"]), - "fork_prs": sum(1 for r in results if r["is_fork"]), + "fork_prs": sum(1 for r in results if r["isFork"]), "by_type": {}, } - - # Type breakdown for r in results: - t = r["pr_type"] - stats["by_type"][t] = stats["by_type"].get(t, 0) + 1 + stats["by_type"][r["pr_type"]] = stats["by_type"].get(r["pr_type"], 0) + 1 - # Collect PRs needing sub-agent review - needs_review_nums = [r["number"] for r in results if r["review_status"] == "needs_review"] - - # Write per-PR analysis files - analysis_dir = os.path.join(output_dir, "analysis") - os.makedirs(analysis_dir, exist_ok=True) - - for r in results: - pr_path = os.path.join(analysis_dir, f"{r['number']}.json") - with open(pr_path, "w") as f: - json.dump(r, f, indent=2, ensure_ascii=False) - - # Write per-PR summary markdown (compact, agent-friendly) - summaries_dir = os.path.join(output_dir, "summaries") - os.makedirs(summaries_dir, exist_ok=True) - - for r in results: - num = r["number"] - lines = [ - f"# PR #{num}: {r['title']}", - f"", - f"- **Author:** {r['author']}", - f"- **Type:** {r['pr_type']}", - f"- **Size:** {r['size']}", - f"- **Updated:** {r['updatedAt']}", - f"- **Branch:** {r['branch']}", - f"- **Draft:** {'yes' if r['isDraft'] else 'no'}", - f"- **Fork:** {'yes (' + r['fork_owner'] + ')' if r['is_fork'] else 'no'}", - f"", - f"## Blocker Summary ({r['fail_count']} blockers)", - f"", - f"| Check | Status | Detail |", - f"|-------|--------|--------|", - f"| CI | {r['ci_status']} | {r['ci_detail']} |", - f"| Conflicts | {r['conflict_status']} | {r['conflict_detail']} |", - f"| Reviews | {r['review_status']} | {r['review_detail']} |", - f"| Jira | {r['jira_status']} | {r['jira_detail']} |", - f"| Staleness | {r['stale_status']} | {r['stale_detail']} |", - f"| Overlap | {r['overlap_status']} | {r['overlap_detail']} |", - ] - - if r["recommend_close"]: - lines.append(f"") - lines.append(f"**Recommend closing:** {r['recommend_close_reason']}") - - if r["notes"]: - lines.append(f"") - lines.append(f"**Notes:** {r['notes']}") - - # Add comment count summary - raw = pr_data_cache.get(num, {}) - if raw: - pr_comments_list = raw.get("pr", {}).get("comments", []) - reviews_list = raw.get("reviews", []) - review_comments_list = raw.get("review_comments", []) - lines.append(f"") - lines.append( - f"**Comments:** {len(pr_comments_list)} PR comments, " - f"{len(reviews_list)} reviews, " - f"{len(review_comments_list)} inline comments" - ) - - summary_path = os.path.join(summaries_dir, f"{num}.md") - with open(summary_path, "w") as f: - f.write("\n".join(lines) + "\n") - - # Write unified comment stream per PR - reviews_dir = os.path.join(output_dir, "reviews") - - for num in needs_review_nums: - pr_reviews_dir = os.path.join(reviews_dir, str(num)) - os.makedirs(pr_reviews_dir, exist_ok=True) - - raw = pr_data_cache.get(num, {}) - if not raw: - continue - - all_comments = extract_unified_comments(raw) - pr = raw.get("pr", {}) - - # Write meta file - meta = { - "number": num, - "title": pr.get("title", ""), - "author": (pr.get("author") or {}).get("login", ""), - "total_comments": len(all_comments), - } - with open(os.path.join(pr_reviews_dir, "meta.json"), "w") as f: - json.dump(meta, f, indent=2, ensure_ascii=False) - - # Write each comment as a numbered file, chronological order - for i, comment in enumerate(all_comments, 1): - comment_path = os.path.join(pr_reviews_dir, f"{i:02d}.json") - with open(comment_path, "w") as f: - json.dump(comment, f, indent=2, ensure_ascii=False) - - # Write compact summary - pr_index = [] - for r in results: - pr_index.append( - { - "number": r["number"], - "rank": r["rank"], - "title": r["title"], - "author": r["author"], - "isDraft": r["isDraft"], - "pr_type": r["pr_type"], - "fail_count": r["fail_count"], - "review_status": r["review_status"], - "recommend_close": r["recommend_close"], - "is_fork": r["is_fork"], - } - ) - - summary = { + queue = { "generated_at": now.strftime("%Y-%m-%dT%H:%M:%S UTC"), - "stats": stats, - "review_order": review_order, - "needs_review": needs_review_nums, - "pr_index": pr_index, - "overlaps": overlaps, - "shared_no_overlap": shared_no_overlap, + "stats": stats, "review_order": review_order, "needs_review": needs_review, + "prs": [{"number": r["number"], "rank": r["rank"], "title": r["title"], "author": r["author"], + "pr_type": r["pr_type"], "fail_count": r["fail_count"], "isDraft": r["isDraft"], + "isFork": r["isFork"], "review_status": r["review_status"], "recommend_close": r["recommend_close"]} + for r in results], } + with open(os.path.join(output_dir, "queue.json"), "w") as f: + json.dump(queue, f, indent=2, ensure_ascii=False) - summary_path = os.path.join(output_dir, "analysis.json") - with open(summary_path, "w") as f: - json.dump(summary, f, indent=2, ensure_ascii=False) - - print("Analysis complete:") - print(f" Summary: {summary_path}") - print(f" Per-PR: {analysis_dir}/{{number}}.json") - print(f" Reviews: {reviews_dir}/{{number}}/meta.json + 01.json, 02.json, ...") - print(f" Total: {stats['total']} PRs ({stats['drafts']} drafts)") - print( - f" Clean: {stats['clean']} | One blocker: {stats['one_blocker']} | Needs work: {stats['needs_work']}" - ) - print(f" Recommend closing: {stats['recommend_close']}") - print(f" Type breakdown: {stats['by_type']}") - print( - f" Needs sub-agent review: {len(needs_review_nums)} PRs \u2014 {needs_review_nums}" - ) - print( - f" Overlaps: {len(overlaps)} line-level, {len(shared_no_overlap)} shared-file-only" - ) + print(f"Analysis complete: {stats['total']} PRs") + print(f" Clean: {stats['clean']} | One blocker: {stats['one_blocker']} | Needs work: {stats['needs_work']}") + print(f" Types: {stats['by_type']}") + print(f" Needs review: {len(needs_review)} PRs") if review_order: - arrow = " \u2192 " - print( - f" Review order: {arrow.join(f'#{n}' for n in review_order[:10])}" - ) + print(f" Review order: {' -> '.join(f'#{n}' for n in review_order[:10])}") if __name__ == "__main__": diff --git a/internal-workflows/pr-overview/scripts/fetch-prs.sh b/internal-workflows/pr-overview/scripts/fetch-prs.sh index ae0e6753..780f31b2 100755 --- a/internal-workflows/pr-overview/scripts/fetch-prs.sh +++ b/internal-workflows/pr-overview/scripts/fetch-prs.sh @@ -1,199 +1,105 @@ #!/usr/bin/env bash # -# fetch-prs.sh — Fetch all open PR data from a GitHub repo into structured JSON files. +# fetch-prs.sh — Fetch all open PR data and structure it. # # Usage: # ./scripts/fetch-prs.sh --repo owner/repo [--output-dir artifacts/pr-review] # -# Requirements: -# - gh CLI installed and authenticated -# - jq installed -# -# Progress goes to stderr. Final summary goes to stdout. -# set -euo pipefail -# ── Defaults ────────────────────────────────────────────────────────────────── REPO="" OUTPUT_DIR="artifacts/pr-review" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +STRUCTURE_SCRIPT="${SCRIPT_DIR}/structure-pr-data.py" -# ── Parse args ──────────────────────────────────────────────────────────────── while [[ $# -gt 0 ]]; do case "$1" in - --repo) - REPO="$2" - shift 2 - ;; - --output-dir) - OUTPUT_DIR="$2" - shift 2 - ;; - -h|--help) - echo "Usage: $0 --repo owner/repo [--output-dir artifacts/pr-review]" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - exit 1 - ;; + --repo) REPO="$2"; shift 2 ;; + --output-dir) OUTPUT_DIR="$2"; shift 2 ;; + -h|--help) echo "Usage: $0 --repo owner/repo [--output-dir artifacts/pr-review]"; exit 0 ;; + *) echo "Unknown argument: $1" >&2; exit 1 ;; esac done -if [[ -z "$REPO" ]]; then - echo "Error: --repo is required (e.g., --repo ambient-code/platform)" >&2 - exit 1 -fi - -# ── Preflight checks ───────────────────────────────────────────────────────── -if ! command -v gh &>/dev/null; then - echo "Error: gh CLI is not installed. Install it from https://cli.github.com/" >&2 - exit 1 -fi +[[ -z "$REPO" ]] && { echo "Error: --repo required" >&2; exit 1; } -if ! gh auth status &>/dev/null; then - echo "Error: gh CLI is not authenticated. Run 'gh auth login' first." >&2 - exit 1 -fi +for cmd in gh jq python3; do + command -v "$cmd" &>/dev/null || { echo "Error: ${cmd} not installed" >&2; exit 1; } +done +gh auth status &>/dev/null || { echo "Error: gh not authenticated" >&2; exit 1; } -if ! command -v jq &>/dev/null; then - echo "Error: jq is not installed." >&2 +if [[ ! -f "$STRUCTURE_SCRIPT" ]]; then + echo "Error: structure-pr-data.py not found at ${STRUCTURE_SCRIPT}" >&2 exit 1 fi OWNER="${REPO%%/*}" REPO_NAME="${REPO##*/}" - -# ── Setup output dirs ──────────────────────────────────────────────────────── -mkdir -p "${OUTPUT_DIR}/prs" TMPDIR=$(mktemp -d) trap 'rm -rf "$TMPDIR"' EXIT echo "Fetching open PRs for ${REPO}..." >&2 -# ── Phase 1: Fetch PR index ────────────────────────────────────────────────── INDEX_FIELDS="number,title,author,createdAt,updatedAt,labels,isDraft,baseRefName,headRefName,url,state,additions,deletions,changedFiles,mergeable,body,isCrossRepository,headRepositoryOwner" -gh pr list \ - --repo "$REPO" \ - --state open \ - --limit 200 \ - --json "$INDEX_FIELDS" \ +mkdir -p "${OUTPUT_DIR}" +gh pr list --repo "$REPO" --state open --limit 200 --json "$INDEX_FIELDS" \ | jq '.' > "${OUTPUT_DIR}/index.json" PR_COUNT=$(jq 'length' "${OUTPUT_DIR}/index.json") echo "Found ${PR_COUNT} open PRs." >&2 -if [[ "$PR_COUNT" -eq 0 ]]; then - echo "No open PRs found." - exit 0 -fi +[[ "$PR_COUNT" -eq 0 ]] && { echo "No open PRs found."; exit 0; } -# ── Phase 2: Fetch per-PR detail ───────────────────────────────────────────── -# Note: reviewRequests is excluded — it requires read:org scope which runners -# typically lack. +DETAIL_FIELDS="number,title,author,createdAt,updatedAt,labels,isDraft,baseRefName,headRefName,headRefOid,url,state,additions,deletions,changedFiles,mergeable,body,reviewDecision,statusCheckRollup,comments,assignees,milestone,files,isCrossRepository,headRepositoryOwner" PR_NUMBERS=$(jq -r '.[].number' "${OUTPUT_DIR}/index.json") -DETAIL_FIELDS="number,title,author,createdAt,updatedAt,labels,isDraft,baseRefName,headRefName,url,state,additions,deletions,changedFiles,mergeable,body,reviewDecision,statusCheckRollup,comments,assignees,milestone,files,isCrossRepository,headRepositoryOwner" FETCHED=0 for PR_NUM in $PR_NUMBERS; do FETCHED=$((FETCHED + 1)) - echo -ne " Fetching PR details... ${FETCHED}/${PR_COUNT}\r" >&2 + echo -ne " Fetching PR #${PR_NUM}... (${FETCHED}/${PR_COUNT})\r" >&2 - gh pr view "$PR_NUM" \ - --repo "$REPO" \ - --json "$DETAIL_FIELDS" \ - 2>/dev/null > "${TMPDIR}/pr.json" || echo '{}' > "${TMPDIR}/pr.json" + PR_TMP="${TMPDIR}/${PR_NUM}" + mkdir -p "$PR_TMP" + + gh pr view "$PR_NUM" --repo "$REPO" --json "$DETAIL_FIELDS" \ + 2>/dev/null > "${PR_TMP}/pr.json" || echo '{}' > "${PR_TMP}/pr.json" gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/reviews" \ - --paginate 2>/dev/null > "${TMPDIR}/reviews.json" || echo '[]' > "${TMPDIR}/reviews.json" + --paginate 2>/dev/null > "${PR_TMP}/reviews.json" || echo '[]' > "${PR_TMP}/reviews.json" gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/comments" \ - --paginate 2>/dev/null > "${TMPDIR}/review_comments.json" || echo '[]' > "${TMPDIR}/review_comments.json" - - HEAD_SHA=$(jq -r '.statusCheckRollup // [] | if length > 0 then .[0].commit.oid // empty else empty end' "${TMPDIR}/pr.json" 2>/dev/null || true) + --paginate 2>/dev/null > "${PR_TMP}/review_comments.json" || echo '[]' > "${PR_TMP}/review_comments.json" - echo '[]' > "${TMPDIR}/check_runs.json" + HEAD_SHA=$(jq -r '.headRefOid // empty' "${PR_TMP}/pr.json" 2>/dev/null || true) + echo '[]' > "${PR_TMP}/check_runs.json" if [[ -n "$HEAD_SHA" ]]; then gh api "repos/${OWNER}/${REPO_NAME}/commits/${HEAD_SHA}/check-runs" \ --paginate 2>/dev/null \ - | jq '.check_runs // []' > "${TMPDIR}/check_runs.json" 2>/dev/null || echo '[]' > "${TMPDIR}/check_runs.json" + | jq '.check_runs // []' > "${PR_TMP}/check_runs.json" 2>/dev/null || echo '[]' > "${PR_TMP}/check_runs.json" fi - jq -n \ - --slurpfile pr "${TMPDIR}/pr.json" \ - --slurpfile reviews "${TMPDIR}/reviews.json" \ - --slurpfile review_comments "${TMPDIR}/review_comments.json" \ - --slurpfile check_runs "${TMPDIR}/check_runs.json" \ - '{ - pr: $pr[0], - reviews: $reviews[0], - review_comments: $review_comments[0], - check_runs: $check_runs[0], - diff_files: [] - }' > "${OUTPUT_DIR}/prs/${PR_NUM}.json" - - sleep 0.3 -done -echo "" >&2 - -# ── Phase 3: Fetch diff hunks for mergeable PRs ───────────────────────────── -MERGEABLE_PRS=$(jq -r '.[] | select(.mergeable == "MERGEABLE" and .isDraft == false) | .number' "${OUTPUT_DIR}/index.json") -MERGEABLE_COUNT=$(echo "$MERGEABLE_PRS" | grep -c '[0-9]' || true) - -if [[ "$MERGEABLE_COUNT" -gt 0 ]]; then - DIFF_FETCHED=0 - echo "Fetching diff hunks for ${MERGEABLE_COUNT} mergeable PRs..." >&2 - - for PR_NUM in $MERGEABLE_PRS; do - DIFF_FETCHED=$((DIFF_FETCHED + 1)) - echo -ne " Fetching diffs... ${DIFF_FETCHED}/${MERGEABLE_COUNT}\r" >&2 - + echo '[]' > "${PR_TMP}/diff_files.json" + MERGEABLE=$(jq -r '.mergeable // "UNKNOWN"' "${PR_TMP}/pr.json" 2>/dev/null || echo "UNKNOWN") + IS_DRAFT=$(jq -r '.isDraft // false' "${PR_TMP}/pr.json" 2>/dev/null || echo "false") + if [[ "$MERGEABLE" == "MERGEABLE" && "$IS_DRAFT" != "true" ]]; then gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/files" \ --paginate 2>/dev/null \ - | jq '[.[] | { - filename: .filename, - status: .status, - additions: .additions, - deletions: .deletions, - patch: .patch - }]' > "${TMPDIR}/diff_files.json" 2>/dev/null || echo '[]' > "${TMPDIR}/diff_files.json" - - jq --slurpfile diff_files "${TMPDIR}/diff_files.json" '.diff_files = $diff_files[0]' \ - "${OUTPUT_DIR}/prs/${PR_NUM}.json" > "${OUTPUT_DIR}/prs/${PR_NUM}.json.tmp" \ - && mv "${OUTPUT_DIR}/prs/${PR_NUM}.json.tmp" "${OUTPUT_DIR}/prs/${PR_NUM}.json" - - sleep 0.3 - done - echo "" >&2 -fi + | jq '[.[] | {filename, status, additions, deletions, patch}]' \ + > "${PR_TMP}/diff_files.json" 2>/dev/null || echo '[]' > "${PR_TMP}/diff_files.json" + fi -# ── Phase 4: Sanitize Unicode ──────────────────────────────────────────────── -SANITIZED=0 -if command -v python3 &>/dev/null; then - SANITIZED=$(python3 -c " -import os, sys -output_dir = sys.argv[1] -count = 0 -for root, _, files in os.walk(output_dir): - for fname in files: - if not fname.endswith('.json'): - continue - fpath = os.path.join(root, fname) - with open(fpath, 'r', errors='surrogateescape') as f: - raw = f.read() - clean = raw.encode('utf-8', errors='replace').decode('utf-8') - if clean != raw: - with open(fpath, 'w') as f: - f.write(clean) - count += 1 -print(count) -" "${OUTPUT_DIR}") -fi + python3 "$STRUCTURE_SCRIPT" \ + --pr-json "${PR_TMP}/pr.json" \ + --reviews-json "${PR_TMP}/reviews.json" \ + --review-comments-json "${PR_TMP}/review_comments.json" \ + --check-runs-json "${PR_TMP}/check_runs.json" \ + --diff-json "${PR_TMP}/diff_files.json" \ + --output-dir "${OUTPUT_DIR}/${PR_NUM}" 2>/dev/null -# ── Final summary (stdout — this is what the agent sees) ───────────────────── -echo "Fetch complete: ${PR_COUNT} PRs from ${REPO}" -echo " PR details: ${PR_COUNT} fetched" -echo " Diff hunks: ${MERGEABLE_COUNT} mergeable PRs" -echo " Unicode sanitized: ${SANITIZED} files" -echo " Output: ${OUTPUT_DIR}/" + sleep 0.3 +done + +echo "" >&2 +echo "Fetch complete: ${PR_COUNT} PRs -> ${OUTPUT_DIR}/" >&2 diff --git a/internal-workflows/pr-overview/scripts/structure-pr-data.py b/internal-workflows/pr-overview/scripts/structure-pr-data.py new file mode 100755 index 00000000..90443387 --- /dev/null +++ b/internal-workflows/pr-overview/scripts/structure-pr-data.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +""" +Structure raw PR API data into a clean directory layout. + +Takes raw JSON files from GitHub API and produces: + {output-dir}/summary.json + {output-dir}/comments/overview.json + 01.json, 02.json, ... + {output-dir}/ci/overview.json + {output-dir}/diff.json + {output-dir}/reviews/overview.json + +Usage: + python3 structure-pr-data.py \ + --pr-json raw/pr.json \ + --reviews-json raw/reviews.json \ + --review-comments-json raw/review_comments.json \ + --check-runs-json raw/check_runs.json \ + --diff-json raw/diff_files.json \ + --output-dir artifacts/123 +""" + +import argparse +import json +import os +import sys + + +def build_comments(pr_comments, reviews, review_comments): + """Merge all comment sources chronologically, filter empty bodies.""" + all_comments = [] + + for c in pr_comments: + all_comments.append({ + "source": "pr_comment", + "id": c.get("id", ""), + "author": c.get("author", {}).get("login", ""), + "timestamp": c.get("createdAt", ""), + "body": c.get("body", ""), + }) + + for r in reviews: + body = r.get("body", "") + if not body or not body.strip(): + continue + all_comments.append({ + "source": "review", + "id": r.get("id", ""), + "author": r.get("user", {}).get("login", ""), + "state": r.get("state", ""), + "timestamp": r.get("submitted_at", ""), + "body": body, + }) + + for rc in review_comments: + body = rc.get("body", "") + if not body or not body.strip(): + continue + all_comments.append({ + "source": "inline_comment", + "id": rc.get("id", ""), + "author": rc.get("user", {}).get("login", ""), + "path": rc.get("path", ""), + "line": rc.get("line"), + "timestamp": rc.get("created_at", ""), + "body": body, + }) + + all_comments.sort(key=lambda c: c.get("timestamp", "")) + return all_comments + + +def build_ci(check_runs): + """Categorize check runs into passing/failing/pending.""" + passing, failing, pending = [], [], [] + for cr in check_runs: + name = cr.get("name", "unknown") + status = cr.get("status", "") + conclusion = cr.get("conclusion", "") + if status != "completed": + pending.append({"name": name, "status": status}) + elif conclusion in ("failure", "timed_out", "cancelled", "action_required"): + failing.append({ + "name": name, + "conclusion": conclusion, + "run_id": cr.get("id", ""), + "html_url": cr.get("html_url", ""), + }) + else: + passing.append(name) + return passing, failing, pending + + +def build_reviews(reviews, review_decision): + """Extract review state per user.""" + user_states = {} + for r in reviews: + login = r.get("user", {}).get("login", "") + state = r.get("state", "") + if login: + user_states[login] = state + + approvals = [{"user": u, "state": s} for u, s in user_states.items() if s == "APPROVED"] + changes_requested = [{"user": u, "state": s} for u, s in user_states.items() if s == "CHANGES_REQUESTED"] + + return { + "decision": review_decision, + "approvals": approvals, + "changes_requested": changes_requested, + "total_reviews": len(reviews), + } + + +def main(): + parser = argparse.ArgumentParser(description="Structure raw PR data") + parser.add_argument("--pr-json", required=True) + parser.add_argument("--reviews-json", required=True) + parser.add_argument("--review-comments-json", required=True) + parser.add_argument("--check-runs-json", required=True) + parser.add_argument("--diff-json", required=True) + parser.add_argument("--output-dir", required=True) + args = parser.parse_args() + + out = args.output_dir + os.makedirs(f"{out}/comments", exist_ok=True) + os.makedirs(f"{out}/ci", exist_ok=True) + os.makedirs(f"{out}/reviews", exist_ok=True) + + with open(args.pr_json) as f: + pr = json.load(f) + with open(args.reviews_json) as f: + reviews = json.load(f) + with open(args.review_comments_json) as f: + review_comments = json.load(f) + with open(args.check_runs_json) as f: + check_runs = json.load(f) + with open(args.diff_json) as f: + diff_files = json.load(f) + + # -- Comments -- + all_comments = build_comments(pr.get("comments", []), reviews, review_comments) + inline_threads = [c for c in all_comments if c["source"] == "inline_comment"] + has_agent_prompts = any("Prompt for AI Agents" in c.get("body", "") for c in all_comments) + + comments_overview = { + "total": len(all_comments), + "by_source": { + "review": sum(1 for c in all_comments if c["source"] == "review"), + "inline_comment": len(inline_threads), + "pr_comment": sum(1 for c in all_comments if c["source"] == "pr_comment"), + }, + "has_agent_prompts": has_agent_prompts, + "latest_activity": all_comments[-1]["timestamp"] if all_comments else "", + "authors": sorted(set(c["author"] for c in all_comments if c["author"])), + } + with open(f"{out}/comments/overview.json", "w") as f: + json.dump(comments_overview, f, indent=2, ensure_ascii=False) + for i, c in enumerate(all_comments, 1): + with open(f"{out}/comments/{i:02d}.json", "w") as f: + json.dump(c, f, indent=2, ensure_ascii=False) + + # -- CI -- + passing, failing, pending = build_ci(check_runs) + ci_overview = {"total": len(check_runs), "passing": passing, "failing": failing, "pending": pending} + with open(f"{out}/ci/overview.json", "w") as f: + json.dump(ci_overview, f, indent=2, ensure_ascii=False) + + ci_status = "pass" + if failing: + ci_status = "failing" + elif pending: + ci_status = "pending" + + # -- Diff -- + diff_data = { + "total_files": len(diff_files), + "additions": sum(df.get("additions", 0) for df in diff_files), + "deletions": sum(df.get("deletions", 0) for df in diff_files), + "files": diff_files, + } + with open(f"{out}/diff.json", "w") as f: + json.dump(diff_data, f, indent=2, ensure_ascii=False) + + # -- Reviews -- + reviews_overview = build_reviews(reviews, pr.get("reviewDecision", "")) + with open(f"{out}/reviews/overview.json", "w") as f: + json.dump(reviews_overview, f, indent=2, ensure_ascii=False) + + # -- Summary (written last, includes rollups) -- + author = (pr.get("author") or {}).get("login", "unknown") + summary = { + "number": pr.get("number"), + "title": pr.get("title", ""), + "author": author, + "url": pr.get("url", ""), + "branch": pr.get("headRefName", ""), + "base": pr.get("baseRefName", "main"), + "isDraft": pr.get("isDraft", False), + "isFork": pr.get("isCrossRepository", False), + "forkOwner": (pr.get("headRepositoryOwner") or {}).get("login", ""), + "mergeable": pr.get("mergeable", "UNKNOWN"), + "headSha": pr.get("headRefOid", ""), + "createdAt": pr.get("createdAt", ""), + "updatedAt": pr.get("updatedAt", ""), + "labels": [lb.get("name", "") for lb in (pr.get("labels") or [])], + "size": { + "files": pr.get("changedFiles", 0) or 0, + "additions": pr.get("additions", 0) or 0, + "deletions": pr.get("deletions", 0) or 0, + }, + "body": pr.get("body", ""), + "comments": { + "total": comments_overview["total"], + "inline_threads": len(inline_threads), + "has_agent_prompts": has_agent_prompts, + }, + "ci": { + "status": ci_status, + "failing": [f["name"] for f in failing], + "passing_count": len(passing), + "pending_count": len(pending), + }, + "reviews": { + "decision": reviews_overview["decision"], + "approvals": len(reviews_overview["approvals"]), + "changes_requested_by": [cr["user"] for cr in reviews_overview["changes_requested"]], + }, + } + with open(f"{out}/summary.json", "w") as f: + json.dump(summary, f, indent=2, ensure_ascii=False) + + print(f"Structured PR #{summary['number']} -> {out}/", file=sys.stderr) + print(f" Comments: {comments_overview['total']} ({len(inline_threads)} inline)", file=sys.stderr) + print(f" CI: {len(passing)} pass, {len(failing)} fail, {len(pending)} pending", file=sys.stderr) + print(f" Diff: {diff_data['total_files']} files (+{diff_data['additions']}/-{diff_data['deletions']})", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/internal-workflows/pr-overview/scripts/test-merge-order.sh b/internal-workflows/pr-overview/scripts/test-merge-order.sh deleted file mode 100755 index 4b76696e..00000000 --- a/internal-workflows/pr-overview/scripts/test-merge-order.sh +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env bash -# -# test-merge-order.sh — Test merge order by locally merging clean PRs in sequence. -# -# Creates a temporary local branch, merges each PR in the given order, -# and stops on the first conflict. Reports which PRs merged cleanly -# and which conflicted. NEVER pushes to any remote. -# -# Usage: -# ./scripts/test-merge-order.sh --repo owner/repo --repo-dir /path/to/clone --prs "616 715 685 ..." -# -# Output: JSON results to stdout -# -# Requirements: -# - gh CLI installed and authenticated -# - git installed -# - The repo must be cloned at --repo-dir -# - -set -euo pipefail - -REPO="" -REPO_DIR="" -PR_LIST="" -BRANCH_NAME="tmp/merge-queue-test" - -while [[ $# -gt 0 ]]; do - case "$1" in - --repo) - REPO="$2" - shift 2 - ;; - --repo-dir) - REPO_DIR="$2" - shift 2 - ;; - --prs) - PR_LIST="$2" - shift 2 - ;; - -h|--help) - echo "Usage: $0 --repo owner/repo --repo-dir /path/to/clone --prs '616 715 685 ...'" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - exit 1 - ;; - esac -done - -if [[ -z "$REPO" || -z "$REPO_DIR" || -z "$PR_LIST" ]]; then - echo "Error: --repo, --repo-dir, and --prs are all required" >&2 - exit 1 -fi - -cd "$REPO_DIR" - -OWNER="${REPO%%/*}" -REPO_NAME="${REPO##*/}" - -# ── Safety: ensure we never push ───────────────────────────────────────────── -# Override push URL to a non-existent path so even accidental pushes fail -ORIGINAL_PUSH_URL=$(git remote get-url --push origin 2>/dev/null || true) -git remote set-url --push origin /dev/null/no-push-allowed - -cleanup() { - # Restore push URL and clean up branch - git merge --abort 2>/dev/null || true - git checkout main 2>/dev/null || git checkout - 2>/dev/null || true - git branch -D "$BRANCH_NAME" 2>/dev/null || true - if [[ -n "$ORIGINAL_PUSH_URL" ]]; then - git remote set-url --push origin "$ORIGINAL_PUSH_URL" 2>/dev/null || true - fi -} -trap cleanup EXIT - -# ── Stash any local changes ────────────────────────────────────────────────── -STASHED=false -if ! git diff --quiet 2>/dev/null || ! git diff --cached --quiet 2>/dev/null; then - git stash push -m "test-merge-order: stashing before merge test" -q - STASHED=true -fi - -# ── Fetch all PR refs ──────────────────────────────────────────────────────── -# This fetches every PR head ref in one call, handling forks automatically. -echo "Fetching all PR refs..." >&2 -git fetch origin '+refs/pull/*/head:refs/remotes/origin/pr/*' --quiet 2>/dev/null || true - -# ── Create tmp branch from main ────────────────────────────────────────────── -git checkout main --quiet 2>/dev/null -git checkout -b "$BRANCH_NAME" --quiet 2>/dev/null - -echo "Starting merge test on branch $BRANCH_NAME..." >&2 - -# ── Merge each PR in order ─────────────────────────────────────────────────── -RESULTS="[" -MERGED_COUNT=0 -FIRST=true - -for PR_NUM in $PR_LIST; do - PR_REF="origin/pr/${PR_NUM}" - - # Check if the ref exists - if ! git rev-parse --verify "$PR_REF" &>/dev/null; then - echo " PR #${PR_NUM}: ref not found, skipping" >&2 - if [[ "$FIRST" == "true" ]]; then FIRST=false; else RESULTS+=","; fi - RESULTS+="{\"number\":${PR_NUM},\"result\":\"skipped\",\"detail\":\"PR ref not found\"}" - continue - fi - - # Attempt the merge - echo " Merging PR #${PR_NUM}..." >&2 - if git merge --no-edit --no-ff "$PR_REF" -m "test-merge: PR #${PR_NUM}" &>/dev/null; then - echo " PR #${PR_NUM}: merged" >&2 - if [[ "$FIRST" == "true" ]]; then FIRST=false; else RESULTS+=","; fi - RESULTS+="{\"number\":${PR_NUM},\"result\":\"merged\"}" - MERGED_COUNT=$((MERGED_COUNT + 1)) - else - # Conflict — find which files - CONFLICT_FILES=$(git diff --name-only --diff-filter=U 2>/dev/null | head -5 | tr '\n' ', ' | sed 's/,$//') - echo " PR #${PR_NUM}: CONFLICT on ${CONFLICT_FILES}" >&2 - git merge --abort 2>/dev/null || true - - if [[ "$FIRST" == "true" ]]; then FIRST=false; else RESULTS+=","; fi - RESULTS+="{\"number\":${PR_NUM},\"result\":\"conflict\",\"files\":\"${CONFLICT_FILES}\"}" - - # Mark remaining PRs as not attempted - REMAINING=false - for REMAINING_PR in $PR_LIST; do - if [[ "$REMAINING" == "true" ]]; then - RESULTS+=",{\"number\":${REMAINING_PR},\"result\":\"not_attempted\",\"detail\":\"Stopped after conflict on #${PR_NUM}\"}" - fi - if [[ "$REMAINING_PR" == "$PR_NUM" ]]; then - REMAINING=true - fi - done - - break - fi -done - -RESULTS+="]" - -echo "" >&2 -echo "Merge test complete: ${MERGED_COUNT} merged cleanly" >&2 - -# ── Output JSON ────────────────────────────────────────────────────────────── -echo "$RESULTS" - -# ── Restore stash ──────────────────────────────────────────────────────────── -# (cleanup trap handles branch deletion and push URL restore) -if [[ "$STASHED" == "true" ]]; then - git checkout main --quiet 2>/dev/null - git stash pop --quiet 2>/dev/null || true -fi