From cf1cd1fa95decf306595022f27a84b978ea724fd Mon Sep 17 00:00:00 2001 From: Gage Krumbach Date: Tue, 10 Mar 2026 13:04:01 -0500 Subject: [PATCH 1/2] feat: transform PR overview into review queue, add PR fixer workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review Queue (internal-workflows/pr-overview): - Reframe from "merge meeting" to prioritized review queue - Add PR type classification (bug-fix, feature, refactor, chore, docs) via unified TYPE_SIGNALS data structure - Sub-agents now read ALL comments as a unified chronological stream instead of parsing bot vs human separately - Ranking prioritizes by type (bugs first), then blockers, then size - Remove merge order testing (test-merge-order.sh) — not needed for review - Milestone renamed to "Review Queue" (backward compat with "Merge Queue") - Blocker comments use marker - Fix: UNKNOWN mergeability returns warn instead of FAIL - Fix: filter empty-body reviews from comment stream - Fix: eliminate double-read of PR JSON via pr_data_cache - Fix: TOCTOU — use try/except instead of os.path.exists PR Fixer (internal-workflows/pr-fixer): - New workflow to fix individual PRs - fetch-pr.sh: parallel API calls, unified comment stream via merge-comments.py - Agent rebases, evaluates reviewer comments (fix valid, respond to invalid), runs lints/tests, pushes with --force-with-lease - Fix report posted as PR comment ( marker) Co-Authored-By: Claude Opus 4.6 (1M context) --- .../pr-fixer/.ambient/ambient.json | 7 + internal-workflows/pr-fixer/CLAUDE.md | 254 ++++++++++++ internal-workflows/pr-fixer/README.md | 59 +++ .../pr-fixer/scripts/fetch-pr.sh | 136 ++++++ .../pr-fixer/scripts/merge-comments.py | 92 +++++ .../pr-overview/.ambient/ambient.json | 15 +- .../pr-overview/.ambient/rubric.md | 62 +-- internal-workflows/pr-overview/CLAUDE.md | 386 ++++++------------ internal-workflows/pr-overview/README.md | 85 ++-- .../pr-overview/scripts/analyze-prs.py | 371 +++++++++++------ .../pr-overview/templates/review-queue.md | 73 ++++ 11 files changed, 1073 insertions(+), 467 deletions(-) create mode 100644 internal-workflows/pr-fixer/.ambient/ambient.json create mode 100644 internal-workflows/pr-fixer/CLAUDE.md create mode 100644 internal-workflows/pr-fixer/README.md create mode 100755 internal-workflows/pr-fixer/scripts/fetch-pr.sh create mode 100755 internal-workflows/pr-fixer/scripts/merge-comments.py create mode 100644 internal-workflows/pr-overview/templates/review-queue.md diff --git a/internal-workflows/pr-fixer/.ambient/ambient.json b/internal-workflows/pr-fixer/.ambient/ambient.json new file mode 100644 index 00000000..b1d1a320 --- /dev/null +++ b/internal-workflows/pr-fixer/.ambient/ambient.json @@ -0,0 +1,7 @@ +{ + "name": "PR Fixer", + "description": "Fix a single PR: rebase to resolve conflicts, address reviewer feedback, run lints and tests, and push clean commits", + "systemPrompt": "You are a PR fixer agent. Follow the instructions in CLAUDE.md to fix a single pull request: fetch its data, rebase to resolve conflicts, evaluate and address reviewer comments, run lints and tests, and push the fixes. You operate on one PR at a time.", + "startupPrompt": "You are the PR Fixer agent. Follow the instructions in CLAUDE.md. Ask for the repo and PR number if not provided, then start the fix process.", + "results": {} +} diff --git a/internal-workflows/pr-fixer/CLAUDE.md b/internal-workflows/pr-fixer/CLAUDE.md new file mode 100644 index 00000000..f8831d22 --- /dev/null +++ b/internal-workflows/pr-fixer/CLAUDE.md @@ -0,0 +1,254 @@ +# PR Fixer — Agent Instructions + +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. + +## Prerequisites + +You need: + +- **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: + +```bash +./scripts/fetch-pr.sh --repo --pr --output-dir artifacts/pr-fixer/ +``` + +This produces: + +- `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 reviews, inline comments, and discussion merged together) +- `artifacts/pr-fixer/{number}/diff.json` — diff files with patches +- `artifacts/pr-fixer/{number}/ci.json` — check run results + +### Phase 2: Assess PR State + +Read the fetched data to build a picture of what needs fixing. Check: + +1. **Merge conflicts** — is `mergeable` set to `CONFLICTING`? If so, rebase is needed first. +2. **CI status** — are any checks failing? Note which ones. +3. **Review comments** — read `comments.json` to understand the full conversation. + +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 `comments.json` — this is a chronological stream of all comments on the PR. Each comment 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" +} +``` + +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 + +### Phase 5: Fix Valid Issues + +For each valid issue identified in Phase 4: + +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 + +**Commit style:** +- One commit per logical fix (don't squash everything into one commit) +- Message format: `fix: address review feedback — ` +- If fixing a specific reviewer's comment, mention it: `fix: handle nil error case (per @reviewer)` + +### 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: + +```bash +gh api "repos/{owner}/{repo}/pulls/{number}/comments/{comment_id}/replies" \ + -f body="[Your response]" +``` + +### Phase 7: Run Lints and Tests + +After all code changes, verify everything is clean: + +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. **Commit lint/test fixes** — `fix: resolve lint issues` or `fix: update tests for rebase changes` + +### Phase 8: Push + +Once all fixes are committed and lints/tests pass: + +```bash +git push --force-with-lease origin HEAD +``` + +Use `--force-with-lease` (not `--force`) to avoid overwriting changes someone else may have pushed. + +**Important:** Ask the user for confirmation before pushing. Show them: +- The list of commits being pushed +- A summary of changes made +- Any concerns about the fixes + +### Phase 9: Post Fix Report as PR Comment + +Post a summary comment on the PR so the author and reviewers can see what was done. Use the `` marker for identification. + +First, find and delete any existing fix report comment: + +```bash +OLD_COMMENT_ID=$(gh api "repos/{owner}/{repo}/issues/{number}/comments" \ + --jq '.[] | select(.body | contains("")) | .id') + +if [ -n "$OLD_COMMENT_ID" ]; then + gh api -X DELETE "repos/{owner}/{repo}/issues/comments/${OLD_COMMENT_ID}" +fi +``` + +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] + +#### Commits Pushed +- `abc1234` fix: resolve merge conflicts with main +- `def5678` fix: handle nil error case (per @reviewer) +- `ghi9012` fix: resolve lint issues + + +``` + +## Important Notes + +- **Never force push without `--force-with-lease`** — it protects against overwriting others' work +- **Always ask before pushing** — show the user what will be pushed +- **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. +- **Be transparent** — if you're unsure about a fix, note it in the report and let the user decide diff --git a/internal-workflows/pr-fixer/README.md b/internal-workflows/pr-fixer/README.md new file mode 100644 index 00000000..c338f840 --- /dev/null +++ b/internal-workflows/pr-fixer/README.md @@ -0,0 +1,59 @@ +# PR Fixer Workflow + +Fixes a single pull request: rebases to resolve conflicts, evaluates and addresses reviewer feedback, runs lints and tests, and pushes clean commits. + +## Prerequisites + +- [GitHub CLI (`gh`)](https://cli.github.com/) installed and authenticated +- `jq` installed +- The target repo cloned locally + +## Quick Start + +```bash +# 1. Fetch all data for the PR +./scripts/fetch-pr.sh --repo owner/repo --pr 123 + +# 2. Run the agent to fix the PR +# (via Ambient Code Platform or Claude Code) +``` + +The agent reads the fetched data, checks out the PR branch, and works through: rebase, reviewer feedback, lints, tests, and push. + +## Directory Structure + +``` +pr-fixer/ +├── .ambient/ +│ └── ambient.json # Workflow config +├── CLAUDE.md # Agent behavioral instructions +├── scripts/ +│ └── fetch-pr.sh # Single-PR data fetcher +├── artifacts/ +│ └── pr-fixer/{number}/ # Fetched data and fix report +└── README.md +``` + +## Fetch Script + +```bash +./scripts/fetch-pr.sh --repo owner/repo --pr 123 [--output-dir artifacts/pr-fixer/123] +``` + +**Output:** + +- `pr.json` — PR metadata (title, body, labels, branch, mergeable status) +- `comments.json` — unified chronological stream of all reviews, inline comments, and discussion +- `diff.json` — changed files with patches +- `ci.json` — check run results + +## Fix Process + +1. **Rebase** — resolve merge conflicts onto the base branch +2. **Review feedback** — read all comments, fix valid issues, respond to invalid concerns +3. **Lint & test** — run the project's lint and test commands +4. **Push** — force-push with lease after user confirmation + +## Relationship to Review Queue + +The Review Queue workflow (`internal-workflows/pr-overview`) identifies which PRs need attention. The PR Fixer can be run on individual PRs flagged by the review queue — especially those with merge conflicts or reviewer feedback that needs addressing. diff --git a/internal-workflows/pr-fixer/scripts/fetch-pr.sh b/internal-workflows/pr-fixer/scripts/fetch-pr.sh new file mode 100755 index 00000000..ff5c46f9 --- /dev/null +++ b/internal-workflows/pr-fixer/scripts/fetch-pr.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# +# fetch-pr.sh — Fetch all data for a single PR into structured JSON files. +# +# 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 +# + +set -euo pipefail + +REPO="" +PR_NUM="" +OUTPUT_DIR="" +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 + ;; + 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 + +for cmd in gh jq python3; do + if ! command -v "$cmd" &>/dev/null; then + echo "Error: ${cmd} is not installed." >&2 + exit 1 + fi +done + +if ! gh auth status &>/dev/null; then + echo "Error: gh CLI is not authenticated." >&2 + exit 1 +fi + +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,url,state,additions,deletions,changedFiles,mergeable,body,reviewDecision,statusCheckRollup,comments,assignees,milestone,files,isCrossRepository,headRepositoryOwner" + +echo " Fetching PR data (parallel)..." >&2 + +gh pr view "$PR_NUM" --repo "$REPO" --json "$DETAIL_FIELDS" \ + 2>/dev/null > "${OUTPUT_DIR}/pr.json" & +PID_PR=$! + +gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/reviews" \ + --paginate 2>/dev/null > "${TMPDIR}/reviews.json" & +PID_REVIEWS=$! + +gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/comments" \ + --paginate 2>/dev/null > "${TMPDIR}/review_comments.json" & +PID_RC=$! + +gh api "repos/${OWNER}/${REPO_NAME}/pulls/${PR_NUM}/files" \ + --paginate 2>/dev/null \ + | jq '[.[] | {filename, status, additions, deletions, patch}]' \ + > "${OUTPUT_DIR}/diff.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 '.statusCheckRollup // [] | if length > 0 then .[0].commit.oid // empty else empty end' "${OUTPUT_DIR}/pr.json" 2>/dev/null || true) + +echo '[]' > "${OUTPUT_DIR}/ci.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" +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" + +# -- 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)" +echo " Diff files: ${DIFF_COUNT}" +echo " CI checks: ${CI_COUNT}" +echo " Output: ${OUTPUT_DIR}/" diff --git a/internal-workflows/pr-fixer/scripts/merge-comments.py b/internal-workflows/pr-fixer/scripts/merge-comments.py new file mode 100755 index 00000000..e4e44908 --- /dev/null +++ b/internal-workflows/pr-fixer/scripts/merge-comments.py @@ -0,0 +1,92 @@ +#!/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) + + print(f"{len(comments)} comments merged into unified stream", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/internal-workflows/pr-overview/.ambient/ambient.json b/internal-workflows/pr-overview/.ambient/ambient.json index e3a48f85..30a3d4f4 100644 --- a/internal-workflows/pr-overview/.ambient/ambient.json +++ b/internal-workflows/pr-overview/.ambient/ambient.json @@ -1,15 +1,14 @@ { - "name": "PR Overview", - "description": "Review open PRs for merge readiness and generate a prioritized merge meeting doc", - "systemPrompt": "You are a PR review agent for merge meetings. Follow the instructions in CLAUDE.md to execute the workflow: fetch PR data, analyze, evaluate reviews, test merge order, manage milestone, write report, and update milestone description. Be thorough but concise — the output should be scannable in a meeting.", - "startupPrompt": "You are the PR Overview agent. Follow the instructions in CLAUDE.md. Start with the 8-step task checklist and complete every step.", + "name": "Review Queue", + "description": "Evaluate open PRs and generate a prioritized review queue — an ordered list of what needs human attention, ranked by type and urgency", + "systemPrompt": "You are a PR review queue agent. Follow the instructions in CLAUDE.md to execute the workflow: fetch PR data, analyze, evaluate each PR via sub-agents, test merge order, manage milestone, write report, and update milestone description. The output is an attention-ordered queue — bug fixes and small PRs first.", + "startupPrompt": "You are the Review Queue agent. Follow the instructions in CLAUDE.md. Start with the 10-step task checklist and complete every step.", "results": { - "Merge Meeting Report": "artifacts/pr-review/merge-meeting-{date}.md", - "Analysis Summary": "artifacts/pr-review/analysis.json", - "Merge Test Results": "artifacts/pr-review/merge-test.json" + "Review Queue Report": "artifacts/pr-review/review-queue-{date}.md", + "Analysis Summary": "artifacts/pr-review/analysis.json" }, "rubric": { - "activationPrompt": "After completing all 8 checklist items and updating the milestone description, evaluate your own execution efficiency using .ambient/rubric.md. Score yourself on 5 criteria (1-5 each) for a total out of 25. Be honest — flag any truncation issues, failed commands, unnecessary tool calls, or workarounds you had to use.", + "activationPrompt": "After completing all checklist items and updating the milestone description, evaluate your own execution efficiency using .ambient/rubric.md. Score yourself on 5 criteria (1-5 each) for a total out of 25. Be honest — flag any truncation issues, failed commands, unnecessary tool calls, or workarounds you had to use.", "schema": { "type": "object", "properties": { diff --git a/internal-workflows/pr-overview/.ambient/rubric.md b/internal-workflows/pr-overview/.ambient/rubric.md index 9e5bd3de..b9cc5764 100644 --- a/internal-workflows/pr-overview/.ambient/rubric.md +++ b/internal-workflows/pr-overview/.ambient/rubric.md @@ -1,6 +1,6 @@ -# PR Review Workflow — Execution Efficiency Rubric +# Review Queue — Execution Efficiency Rubric -This rubric evaluates how efficiently the PR review agent executed the workflow. It is triggered after the merge meeting report is written. The purpose is to identify inefficiencies — wasted tool calls, workarounds, truncation issues, failed commands — so the workflow can be continuously improved. The output is a score out of 25 (aggregate of 5 criteria at 5 points each) and a brief explanation. +This rubric evaluates how efficiently the review queue agent executed the workflow. It is triggered after the report is written and the milestone updated. The purpose is to identify inefficiencies so the workflow can be continuously improved. The output is a score out of 25 (aggregate of 5 criteria at 5 points each) and a brief explanation. --- @@ -24,7 +24,7 @@ Did the agent avoid flooding its context with large data? - **Score 1**: Agent read raw PR files (50KB+) directly into its context. Multiple "output too large" truncation errors. Critical data was lost. - **Score 2**: Agent read analysis.json when it was too large, causing truncation. Had to re-read with offset/limit workarounds. -- **Score 3**: Agent used the split file structure (analysis.json summary + per-PR files) but read more files than necessary — e.g., reading all 49 PR detail files instead of just the ones needed. +- **Score 3**: Agent used the split file structure (analysis.json summary + per-PR files) but read more files than necessary. - **Score 4**: Agent read only the summary and the specific per-PR files needed. Used sub-agents for review evaluation. Minor unnecessary reads. - **Score 5**: Agent read the compact summary once, delegated review evaluation to parallel sub-agents, and only read individual analysis files for report generation. Zero truncation, zero wasted reads. @@ -36,23 +36,22 @@ Did the agent avoid flooding its context with large data? Did the agent complete the workflow in a reasonable number of tool calls? -- **Score 1**: 50+ tool calls. Extensive thrashing — rewriting scripts, debugging edge cases inline, running analysis multiple times. -- **Score 2**: 40-49 tool calls. Significant wasted calls on exploration, debugging, or re-doing completed work. -- **Score 3**: 30-39 tool calls. Some unnecessary investigation but generally on track. Maybe read a few extra files or ran extra verification commands. -- **Score 4**: 20-29 tool calls. Efficient execution with minimal waste. Used parallel sub-agents where appropriate. +- **Score 1**: 50+ tool calls. Extensive thrashing. +- **Score 2**: 40-49 tool calls. Significant wasted calls. +- **Score 3**: 30-39 tool calls. Some unnecessary investigation but generally on track. +- **Score 4**: 20-29 tool calls. Efficient execution with minimal waste. - **Score 5**: Under 20 tool calls. Ran scripts, delegated review to sub-agents, synced milestone, wrote report, updated milestone description — all with no wasted steps. **Benchmark**: The ideal workflow is approximately: 1. Read CLAUDE.md + template (2 calls) 2. Run fetch-prs.sh (1 call) 3. Run analyze-prs.py (1 call) -4. Spawn parallel sub-agents for review evaluation (1-3 calls) -5. Run test-merge-order.sh (1 call) -6. Find/create milestone + sync PRs (2-3 calls) -7. Read analysis summary + needed per-PR files (3-5 calls) -8. Write report (1 call) -9. Update milestone description (1 call) -Total: ~15-20 calls +4. Spawn parallel sub-agents for per-PR evaluation (1-3 calls) +5. Find/create milestone + sync PRs (2-3 calls) +6. Read analysis summary + needed per-PR files (3-5 calls) +7. Write report (1 call) +8. Update milestone description (1 call) +Total: ~13-18 calls --- @@ -60,32 +59,33 @@ Total: ~15-20 calls When something went wrong, did the agent recover gracefully or spiral? -- **Score 1**: A single error caused the agent to abandon the approach entirely and start over with a different strategy (e.g., rewriting the analysis script from scratch). -- **Score 2**: Errors caused multi-step debugging sessions (5+ tool calls to diagnose and fix a single issue). -- **Score 3**: Agent encountered errors and recovered within 2-3 tool calls but wasted time on the wrong diagnosis first. -- **Score 4**: Agent encountered a minor error and recovered in 1 call (e.g., a missing file, retried with correct path). +- **Score 1**: A single error caused the agent to abandon the approach entirely and start over. +- **Score 2**: Errors caused multi-step debugging sessions (5+ tool calls to diagnose and fix). +- **Score 3**: Agent encountered errors and recovered within 2-3 tool calls. +- **Score 4**: Agent encountered a minor error and recovered in 1 call. - **Score 5**: No errors encountered, or the agent's first recovery attempt succeeded immediately. -**Red flags**: Agent writing replacement scripts when the provided one fails. Retrying the same failing command. Long debugging chains where the agent tries multiple hypotheses before finding the issue. +**Red flags**: Agent writing replacement scripts when the provided one fails. Retrying the same failing command. Long debugging chains. --- ## Criterion 5: Completeness (1-5 points) -Did the agent complete ALL 8 checklist items? +Did the agent complete ALL 9 checklist items? -- **Score 1**: Completed 4 or fewer items. Major deliverables missing (no report, no milestone update). +- **Score 1**: Completed 4 or fewer items. Major deliverables missing. - **Score 2**: Completed 5-6 items. Report was written but milestone was not updated, or review evaluation was skipped. -- **Score 3**: Completed 7 items. One step was skipped or done incorrectly (e.g., milestone synced but description not updated). -- **Score 4**: All 8 items completed but with minor issues (e.g., merge test skipped because script wasn't found, report missing one section). -- **Score 5**: All 8 items completed correctly: fetch → analyze → review evaluation → merge test → milestone find/create → milestone sync → write report → update milestone description. +- **Score 3**: Completed 7 items. One or two steps skipped or done incorrectly. +- **Score 4**: All 9 items completed but with minor issues. +- **Score 5**: All 9 items completed correctly: fetch, analyze, sub-agent evaluation, milestone find/create, milestone sync, blocker comments, write report, update milestone, self-evaluate. -**The 8 checklist items**: +**The 9 checklist items**: 1. Run fetch-prs.sh 2. Run analyze-prs.py -3. Evaluate review comments (via sub-agents) -4. Run test-merge-order.sh -5. Find or create Merge Queue milestone -6. Sync PRs to milestone -7. Write the merge meeting report -8. Update milestone description with the report +3. Evaluate PRs via sub-agents +4. Find or create Review Queue milestone +5. Sync PRs to milestone +6. Comment on blocked PRs +7. Write the review queue report +8. Update milestone description +9. Self-evaluate execution diff --git a/internal-workflows/pr-overview/CLAUDE.md b/internal-workflows/pr-overview/CLAUDE.md index 79e5178f..b4255817 100644 --- a/internal-workflows/pr-overview/CLAUDE.md +++ b/internal-workflows/pr-overview/CLAUDE.md @@ -1,23 +1,22 @@ -# PR Review Workflow — Agent Instructions +# Review Queue — Agent Instructions -You are an agent that reviews open pull requests for merge readiness and generates a ranked merge meeting document. +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. ## Task Checklist Create these as your todo items at the start. Mark each one as you complete it — do not stop until all are done. 1. **Run fetch-prs.sh** — collect all PR data into artifacts/pr-review/ -2. **Run analyze-prs.py** — produce analysis.json with blocker statuses and merge order -3. **Evaluate review comments** — spawn parallel sub-agents to read review files for `needs_review` PRs and return verdicts -4. **Run test-merge-order.sh** — locally merge clean PRs in order, record which merged/conflicted -5. **Find or create Merge Queue milestone** — get the milestone number -6. **Sync PRs to milestone** — add clean PRs, remove ones with blockers -7. **Comment on blocked PRs** — post blocker summaries on PRs not in the queue (only if PR was updated since last comment) -8. **Write the merge meeting report** — fill the template with all data including merge test results -9. **Update milestone description** — overwrite with the final report -10. **Self-evaluate execution** — read `.ambient/rubric.md` and score your own efficiency (5 criteria, 25 points total) - -**Do not stop until all 10 items are done.** The self-evaluation is the final step. +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) + +**Do not stop until all 9 items are done.** The self-evaluation is the final step. ## Workflow @@ -55,60 +54,22 @@ Each `prs/{number}.json` file has this top-level structure: "deletions": 18, "changedFiles": 5, "labels": [{ "name": "bug" }], - "milestone": { "title": "Merge Queue" }, + "milestone": { "title": "Review Queue" }, "statusCheckRollup": [...], - "comments": [ - { - "author": { "login": "github-actions" }, - "body": "# Amber Code Review\n### Blocker Issues\n..." - } - ], + "comments": [...], "reviewDecision": "APPROVED", "files": [...] }, - "reviews": [ - { - "user": { "login": "reviewer", "type": "User" }, - "state": "CHANGES_REQUESTED", - "body": "..." - } - ], - "review_comments": [ - { - "user": { "login": "reviewer", "type": "User" }, - "body": "inline comment text..." - } - ], - "check_runs": [ - { - "name": "ci/build", - "conclusion": "success", - "status": "completed" - } - ], - "diff_files": [ - { - "filename": "path/to/file.go", - "status": "modified", - "additions": 10, - "deletions": 3, - "patch": "@@ -1,5 +1,7 @@\n..." - } - ] + "reviews": [...], + "review_comments": [...], + "check_runs": [...], + "diff_files": [...] } ``` -**Critical data path notes:** - -- **PR comments** (including bot reviews like Amber Code Review) are at `pr.comments[]` — NOT at the top-level `reviews` or `review_comments`. -- **Reviews** (approve/request changes) are at the top-level `reviews[]` with `user.login` and `state` fields. The `user.type` field is `"User"` for humans and `"Bot"` for GitHub Apps. -- **Inline review comments** (code-level discussion threads) are at the top-level `review_comments[]` with `user.login`. -- **CI status** is in both `pr.statusCheckRollup[]` and the top-level `check_runs[]`. Use `check_runs` as the primary source — it has the `conclusion` field. -- **Milestone** is at `pr.milestone` — will be `null` or `{ "title": "..." }`. - ### Phase 2: Analyze PRs -Run the analysis script to evaluate every PR against the blocker checklist: +Run the analysis script to evaluate every PR against the blocker checklist and classify by type: ```bash python3 ./scripts/analyze-prs.py --output-dir artifacts/pr-review @@ -116,42 +77,64 @@ python3 ./scripts/analyze-prs.py --output-dir artifacts/pr-review This produces: -- `artifacts/pr-review/analysis.json` — compact summary with stats, merge order, overlap data, and a `pr_index` (one line per PR: number, rank, title, author, fail_count, review_status). Small enough to read in one go. -- `artifacts/pr-review/analysis/{number}.json` — full per-PR analysis (all blocker statuses, details, labels, notes). Read these when you need detail on specific PRs. +- `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/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 -The script prints a `needs_review` list of PR numbers that require your evaluation. The summary file also has a `needs_review` array. +### Phase 3: Per-PR Sub-Agent Evaluation -**Review comments require evaluation.** Use **parallel sub-agents** to evaluate the `needs_review` PRs so the raw comment data doesn't flood your main context and evaluation runs fast. +This is where the real intelligence lives. The analyze script does mechanical checks (CI, conflicts, Jira, staleness). The sub-agents do the nuanced reading — understanding review conversations, judging comment validity, assessing overall PR health. -Split the `needs_review` list into batches of ~10 PRs each and spawn sub-agents **in parallel** (multiple Task calls in a single message). Use this prompt for each batch: +**Spawn one sub-agent per batch of ~10 PRs.** Use this prompt for each batch: -> Evaluate review comments for the PRs listed below. For each PR: -> -> 1. Read `artifacts/pr-review/reviews/{number}/meta.json` to see how many comments there are -> 2. Read the comment files **from highest number to lowest** (newest first): `reviews/{number}/05.json`, `04.json`, etc. -> 3. Each comment file has: `source` (pr_comment / review / inline_comment), `author`, `body`, and optionally `state` or `path` -> 4. Stop reading once you've found the latest bot review (author contains "github-actions" or "[bot]") and have enough context to judge +> Evaluate each PR listed below. For each PR: > -> **Bot review comments (e.g., "Amber Code Review") are real code reviews.** They analyzed the actual diff. Evaluate the latest bot review's findings by severity: +> 1. Read `artifacts/pr-review/analysis/{number}.json` to see the mechanical check results and the PR's `updatedAt` timestamp +> 2. Read `artifacts/pr-review/reviews/{number}/meta.json` to see the comment count +> 3. Read ALL comment files in `reviews/{number}/` in order (01.json, 02.json, ...) — these are the full chronological comment stream including human reviews, bot reviews, inline comments, and discussion. Do not skip any. +> 4. Understand the full conversation arc: who reviewed, what they said, whether issues were addressed, whether reviews are stale (old commits), whether there's unresolved disagreement > -> - **Blocker issues** → always FAIL. These are showstoppers (compile errors, security vulnerabilities, data races, missing auth). -> - **Critical issues** → FAIL, but explain WHY it's blocking in your summary. These are serious (incorrect logic, missing error handling on critical paths, breaking changes). -> - **Major issues** → usually NOT a blocker. Only FAIL if the major issue would cause a real bug or regression in production. Style issues, naming concerns, missing docs, or "nice to have" improvements marked as Major are NOT blockers. -> - **Minor issues** → never a blocker. Pass. +> For each PR, return a verdict with these fields: +> - **number**: PR number +> - **verdict**: `ready` (no blockers, needs human approval), `almost` (1 minor issue), `blocked` (real blockers), `stale` (abandoned/inactive) +> - **review_summary**: 1-2 sentences capturing the review state — who reviewed, what was raised, whether it was addressed. Be specific. +> - **action_needed**: What a human should do next (e.g., "Approve — all feedback addressed", "Author needs to fix CI", "Reviewer @alice has unresolved concern about error handling") +> - **action_owner**: Who needs to act — `@author`, `@reviewer`, `@maintainer`, or a specific username +> - **blockers_from_comments**: List of genuine blockers found in comments (empty list if none). Only real issues — not style nits, not stale bot findings on old commits. > -> For each PR, return: PR number, verdict (FAIL or pass), and a 1-2 sentence explanation of your reasoning. For FAIL, describe the specific issue. For pass, briefly note what was found and why it's not blocking (e.g., "Major: naming suggestion — style only, not blocking"). +> Key judgment calls: +> - A bot review from 3 weeks ago on a different commit is probably stale — note it but don't block on it +> - A human requesting changes, author pushing a fix, but no re-approval = needs reviewer to re-review, not a blocker from comments +> - "nit" comments or style suggestions with CHANGES_REQUESTED state = not a real blocker, note the mismatch +> - Multiple rounds of review with all issues addressed = ready for approval +> - Unresolved substantive disagreement = blocked, explain the disagreement > > PRs to evaluate: {batch list} -Each comment is a small file — no truncation, no size limits. The sub-agent reads newest first and stops early once it has a verdict. +Collect all verdicts from the parallel sub-agents and update each PR's review data before proceeding. -Collect all verdicts from the parallel sub-agents and update each PR's `review_status` and `fail_count` in your working data before proceeding. +**Do not rewrite the analysis script.** If you need to adjust a deterministic check, edit `scripts/analyze-prs.py` directly. -**Do not rewrite the analysis script.** If you need to adjust a deterministic check, edit `scripts/analyze-prs.py` directly. Do **not** write the final report yet — the milestone count is needed first (see Phase 3). +## 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 six categories. Each is either clear or a blocker/warning. +For **every** open PR, evaluate each of these categories. Each is either clear or a blocker/warning. ### 1. CI @@ -169,16 +152,12 @@ For **every** open PR, evaluate each of these six categories. Each is either cle ### 3. Review Comments The script handles two deterministic checks automatically: -- **CHANGES_REQUESTED** without a subsequent APPROVED or DISMISSED → `FAIL` -- **Inline review threads** (from `review_comments[]`) → `FAIL` with count - -For PRs with `review_status: "needs_review"`, sub-agents evaluate the comments (see Phase 2). The key severity rules: +- **CHANGES_REQUESTED** without a subsequent APPROVED or DISMISSED +- **Inline review threads** (from `review_comments[]`) -- **Blocker/Critical** bot review findings → `FAIL` (with reasoning in the report) -- **Major** findings → usually `pass` unless it's a real bug/regression risk. Most Majors are style, naming, or improvement suggestions — not merge blockers. -- **Minor** findings → always `pass` +Everything else — bot reviews, human discussion, comment arcs — is evaluated by the sub-agents who read the full comment stream and make judgment calls. See Phase 3 for the sub-agent prompt. -When marking a PR as FAIL in the report, include a brief explanation of the actual issue so the team can act on it — don't just say "Bot review: FAIL". +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 @@ -192,11 +171,11 @@ When marking a PR as FAIL in the report, include a brief explanation of the actu - 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 clearly so a maintainer knows manual review is required. +- 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). But **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. +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 @@ -204,49 +183,19 @@ Consider recommending closure for PRs that show multiple signs of abandonment: - Superseded by a newer PR from the same author - Very old (60+ days) regardless of other signals -Do not waste report space on these — use the condensed "Recommend Closing" table instead of a full blocker breakdown. +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 merge readiness: - -1. **Blocker count** — PRs with zero blockers first, then one, then two, etc. -2. **Priority labels** — within the same blocker count, PRs with `priority/critical`, `bug`, or `hotfix` labels rank higher. -3. **Size (smaller first)** — PRs with fewer changed files and smaller diffs rank higher, reducing merge risk. -4. **Line-level conflict risk** — use diff hunk data (see below) to determine which mergeable PRs would actually collide. Rank the smaller PR first within a conflict pair. -5. **Dependency chains** — if a PR's branch is based on another PR's branch, the base PR must rank higher. Note these explicitly. -6. **Draft PRs last** — drafts always sort to the bottom regardless of other signals. - -## Diff Hunk Analysis (Merge Order Optimisation) - -For mergeable (non-draft) PRs, the fetch script collects `diff_files` — an array of per-file objects containing the `patch` field with actual diff content. Use this data to detect **line-level overlaps** between mergeable PRs and optimise merge order. - -### How to parse hunks +Produce a single ranked list of all open PRs, ordered by what needs human attention first: -Each `patch` string contains one or more hunk headers in unified diff format: - -``` -@@ -oldStart,oldCount +newStart,newCount @@ optional context -``` - -Extract the `newStart` and `newCount` values (the `+` side) for each hunk. These represent the line ranges the PR modifies in the target file. A hunk touches lines `newStart` through `newStart + newCount - 1`. - -### How to detect overlaps - -For every pair of mergeable PRs (A, B): - -1. Find files that appear in both `diff_files` arrays (match on `filename`). -2. For each shared file, compare hunk ranges. Two hunks overlap if: - - Hunk A: lines `a_start` to `a_start + a_count - 1` - - Hunk B: lines `b_start` to `b_start + b_count - 1` - - Overlap exists when `a_start <= b_start + b_count - 1` AND `b_start <= a_start + a_count - 1` -3. If any hunk pair overlaps, the two PRs have a **line-level conflict risk**. - -### How to use overlap data - -- **No overlapping hunks** between two PRs that touch the same file: they can merge in any order safely. Note this as "same file, no line overlap" — it's good news. -- **Overlapping hunks**: merge the smaller PR first to minimise rebase pain. Flag the overlap in the `{{NOTES}}` field with the specific file and line ranges. -- When multiple mergeable PRs form a chain of overlaps (A overlaps B, B overlaps C), recommend a specific merge sequence and explain why. +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 @@ -260,7 +209,7 @@ Use these in the **Status** column of the per-PR blocker table: ## Output Format -Use the template at `templates/merge-meeting.md`. Populate it from `analysis.json`. +Use the template at `templates/review-queue.md`. Populate it from `analysis.json` and sub-agent verdicts. ### Dates @@ -268,98 +217,55 @@ Use absolute dates in `YYYY-MM-DD` format (e.g., `2026-02-27`). Do not use relat ### At a Glance -A 2-3 sentence summary at the top of the report. Mention how many PRs are ready, call out the top 3-4 smallest ones by number, and flag any notable concerns (e.g., "3 PRs recommended for closure", "6 PRs blocked by merge conflicts"). - -### Clean PRs (condensed table) +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"). -PRs with `fail_count == 0` and `isDraft == false` go in the condensed summary table — one row per PR. List them in the order from the `merge_order` array (smallest and least conflicting first). +### Ready for Review (condensed table) -For fork PRs (`is_fork == true`), add "🍴 Fork — no agent review" to the Notes column so maintainers know manual review is needed. +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 **Merge Test** column shows the result from `test-merge-order.sh`: -- `merged` — PR merged cleanly on top of all previous PRs in the sequence -- `CONFLICT` — merge failed; note the conflicting file(s) -- `not attempted` — skipped because an earlier PR conflicted +For fork PRs (`is_fork == true`), add "Fork — no agent review" to the Notes column. -The **Notes** column: overlap warnings, jira hygiene, or "—". - -After the table, if any PR conflicted, add a **Resolution Strategy** section explaining: -- Which PRs conflicted and on which files -- Who owns the conflicting PR and what they need to do (rebase on top of which PR) -- Which downstream PRs are blocked and will need rebasing once the conflict is resolved +The **Action Needed** column: what a human reviewer should do (from sub-agent verdict). ### PRs With Blockers (full tables) -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 — do **not** give them a full blocker breakdown. +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. ### Fork PRs -Fork PRs are **not** separated into their own section. They appear in the same Clean PRs or PRs With Blockers tables as internal PRs, based on their blocker count — just like any other PR. +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. -To signal that a PR is from a fork, add "🍴 Fork — no agent review" to the **Notes** column. If the `fork_owner` field is available, include it: "🍴 Fork (`fork_owner`) — no agent review". This gives maintainers a clear visual indicator without fragmenting the report. +To signal that a PR is from a fork, add "Fork (`fork_owner`) — no agent review" to the **Notes** column. ### Recommend Closing -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 (relative). Use your judgment to add PRs the script missed. - -### Status indicators - -| Status | Meaning | -|--------|---------| -| `pass` | No issues detected | -| `FAIL` | Blocker — must be resolved before merge | -| `warn` | Hygiene / informational issue — does not block merge | - -## Phase 3: Test Merge Order - -After analysis and review evaluation, test the merge order locally to verify clean PRs actually merge without conflicts: - -```bash -MERGE_ORDER=$(python3 -c "import json; d=json.load(open('artifacts/pr-review/analysis.json')); print(' '.join(str(n) for n in d['merge_order']))") - -./scripts/test-merge-order.sh \ - --repo \ - --repo-dir /workspace/repos/ \ - --prs "$MERGE_ORDER" -``` - -This creates a temporary local branch, fetches all PR refs (including forks via `refs/pull/*/head`), and merges each PR in sequence. It stops on the first conflict and reports results as JSON. - -**The script NEVER pushes to any remote.** The push URL is overridden to `/dev/null` and the tmp branch is deleted on exit. - -Use the results to: -- Mark each clean PR's merge test result in the report table (merged / conflict / not attempted) -- For conflicts: note the conflicting files and which PR pair caused it -- For not-attempted PRs: explain why (blocked by earlier conflict) -- Add a **resolution strategy** after the table explaining what needs to happen to unblock the remaining PRs (who needs to rebase, which file, what the conflict is about) - -If the merge test script is not available or fails, skip this phase and note it in the report. +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. ## Phase 4: Milestone Management -Manage the **"Merge Queue"** milestone. This milestone acts as a living bucket of ready-to-merge PRs — no due date, never closed, updated every run. The milestone description stores the report and per-PR analysis timestamps, which are used as state on subsequent runs. +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. **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 -MILESTONE_NUM=$(gh api "repos/{owner}/{repo}/milestones" --jq '.[] | select(.title=="Merge Queue") | .number') +# 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="Merge Queue" \ + -f title="Review Queue" \ -f state=open \ - -f description="Auto-managed by PR Overview workflow" \ + -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 (this catches merged/closed PRs that the fetch script wouldn't see since it only fetches open PRs): +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" \ @@ -382,23 +288,18 @@ Then sync: 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 merge order +### 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 `merge_order` from the analysis. - -First, get the milestone's node ID and each PR's node ID: +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 merge_order) +# Get PR node IDs (for each PR in review_order) PR_NODE_ID=$(gh api "repos/{owner}/{repo}/pulls/{number}" --jq '.node_id') -``` -Then reorder by calling the mutation for each PR in sequence, setting `prevId` to the previous PR's node ID: - -```bash +# Reorder gh api graphql -f query=' mutation { reprioritizeMilestoneIssue(input: { @@ -412,20 +313,16 @@ gh api graphql -f query=' ' ``` -For the first PR in the order, omit `prevId` (it goes to the top). For each subsequent PR, set `prevId` to the PR that should come before it. - -**Note:** This is an undocumented GitHub GraphQL mutation. If it fails, skip silently — the milestone description still has the merge order in the report. +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/merge-meeting-{YYYY-MM-DD}.md` using the template. +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 -Overwrite the milestone description with the final report, prefixed with a timestamp: - ```bash -REPORT=$(cat artifacts/pr-review/merge-meeting-{date}.md) +REPORT=$(cat artifacts/pr-review/review-queue-{date}.md) TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC') DESCRIPTION="**Last updated:** ${TIMESTAMP} @@ -440,95 +337,50 @@ gh api -X PATCH "repos/{owner}/{repo}/milestones/${MILESTONE_NUM}" \ - 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 of the description. +- Always include the `Last updated` timestamp at the top. -## Phase 5: Comment on Blocked PRs +## 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 Merge Queue. This gives PR authors direct feedback on what's blocking their PR. +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. This is how you find and manage previous comments from this workflow. +**All comments are identified by a hidden HTML marker:** `` at the end of the comment body. ### Noise reduction rules -To avoid spamming PRs with redundant comments: - -1. **Find existing comment:** For each blocked PR, list its comments and look for one containing ``. -2. **Check freshness:** If an existing comment is found, compare the PR's `updatedAt` timestamp with the comment's `created_at` timestamp. - - If the PR was **not updated** since the last comment → **skip** (the existing comment is still current). - - If the PR **was updated** since the last comment → **delete** the old comment, then **post** a new one. +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. -### Finding and deleting old comments - -```bash -# List comments and find the one with our marker -OLD_COMMENT_ID=$(gh api "repos/{owner}/{repo}/issues/{number}/comments" \ - --jq '.[] | select(.body | contains("")) | .id') - -# Delete it if found -if [ -n "$OLD_COMMENT_ID" ]; then - gh api -X DELETE "repos/{owner}/{repo}/issues/comments/${OLD_COMMENT_ID}" -fi -``` - -### Per-PR analysis file structure - -Each `analysis/{number}.json` has blocker statuses as **top-level fields** (not nested under a `blockers` key). The fields you need for the comment: - -| Field | Example | Purpose | -|-------|---------|---------| -| `ci_status` | `"pass"`, `"FAIL"`, `"warn"` | CI check result | -| `ci_detail` | `"Failing: build"` or `"—"` | CI detail text | -| `conflict_status` | `"pass"`, `"FAIL"` | Merge conflict result | -| `conflict_detail` | `"Has merge conflicts"` or `"—"` | Conflict detail text | -| `review_status` | `"pass"`, `"FAIL"`, `"needs_review"` | Review result | -| `review_detail` | `"CHANGES_REQUESTED from @user"` | Review detail text | -| `jira_status` | `"pass"`, `"warn"` | Jira hygiene result | -| `jira_detail` | `"No Jira reference found"` or `"—"` | Jira detail text | -| `stale_status` | `"pass"`, `"FAIL"` | Staleness result | -| `stale_detail` | `"Last updated 2026-01-15 — 47 days ago"` | Staleness detail text | -| `overlap_status` | `"pass"`, `"FAIL"`, `"warn"`, `"—"` | Diff overlap result | -| `overlap_detail` | `"Line overlap with #456 on file.go"` | Overlap detail text | -| `fail_count` | `2` | Total number of FAIL statuses | -| `isDraft` | `false` | Whether PR is a draft | -| `recommend_close` | `false` | Whether PR is flagged for closure | -| `updatedAt` | `"2026-02-20"` | PR last updated date (truncated to date) | - ### Comment format -Post a concise, actionable comment listing the blocker statuses: - ```markdown -### Merge Readiness — Blockers Found +### Review Queue — Blockers Found | Check | Status | Detail | |-------|--------|--------| | CI | FAIL | `build` failed | -| Merge conflicts | pass | — | +| Merge conflicts | pass | --- | | Review comments | FAIL | Changes requested by @reviewer | | Jira hygiene | pass | RHOAIENG-1234 | -| Staleness | pass | — | -| Diff overlap risk | pass | — | - -> This comment is auto-generated by the PR Overview workflow and will be updated when the PR changes. +| Staleness | pass | --- | +| Diff overlap risk | pass | --- | - -``` - -Include all six blocker categories. Use `pass`, `FAIL`, or `warn` in the Status column, reading directly from the `*_status` fields. Use the corresponding `*_detail` field for the Detail column. +**Action needed:** Author needs to fix CI and address review comments. -### Posting the comment +> This comment is auto-generated by the Review Queue workflow and will be updated when the PR changes. -```bash -gh api "repos/{owner}/{repo}/issues/{number}/comments" \ - -f body="${COMMENT_BODY}" + ``` +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, the author hasn't marked them ready. -- **PRs recommended for closing** — don't comment, they'll be flagged in the report instead. +- **Draft PRs** — don't comment on drafts. +- **PRs recommended for closing** — don't comment, they'll be flagged in the report. ## Important Notes diff --git a/internal-workflows/pr-overview/README.md b/internal-workflows/pr-overview/README.md index 00201a1f..b4ea5210 100644 --- a/internal-workflows/pr-overview/README.md +++ b/internal-workflows/pr-overview/README.md @@ -1,6 +1,6 @@ -# PR Review Workflow +# Review Queue Workflow -Automates pre-merge-meeting PR triage for a GitHub repository. Fetches all open PR data, analyzes merge readiness, and generates a structured meeting document. +Evaluates all open PRs in a GitHub repository and generates a prioritized review queue — an ordered list of what needs human attention, ranked by type and urgency. ## Prerequisites @@ -11,70 +11,73 @@ Automates pre-merge-meeting PR triage for a GitHub repository. Fetches all open ```bash # 1. Fetch PR data -./scripts/fetch-prs.sh --repo ambient-code/platform +./scripts/fetch-prs.sh --repo owner/repo -# 2. Run the agent to analyze and generate the report +# 2. Run the agent to analyze and generate the queue # (via Ambient Code Platform or Claude Code) ``` -The agent reads the fetched data, applies merge readiness criteria, and writes a report to `artifacts/pr-review/merge-meeting-{date}.md`. +The agent reads the fetched data, evaluates each PR via sub-agents, and writes a report to `artifacts/pr-review/review-queue-{date}.md`. ## Directory Structure ``` -pr-review/ +pr-overview/ ├── .ambient/ -│ └── ambient.json # Workflow config +│ ├── ambient.json # Workflow config +│ └── rubric.md # Self-evaluation rubric ├── CLAUDE.md # Agent behavioral instructions ├── scripts/ -│ └── fetch-prs.sh # Data fetching script +│ ├── fetch-prs.sh # Data fetching script (all open PRs) +│ ├── analyze-prs.py # Blocker analysis and type classification +│ └── test-merge-order.sh # Local merge dry-run test ├── templates/ -│ └── merge-meeting.md # Output template +│ ├── review-queue.md # Output template +│ └── merge-meeting.md # Legacy template (deprecated) ├── artifacts/ │ └── pr-review/ # Generated reports and raw data └── README.md ``` -## Fetch Script +## How It Works -```bash -./scripts/fetch-prs.sh --repo owner/repo [--output-dir artifacts/pr-review] -``` +1. **Fetch** — `fetch-prs.sh` pulls all open PR data from the GitHub API +2. **Analyze** — `analyze-prs.py` runs mechanical checks (CI, conflicts, Jira, staleness) and classifies PRs by type +3. **Sub-agent evaluation** — each PR's full comment stream is read by a sub-agent that understands review arcs, stale comments, and nuanced feedback +4. **Merge test** — `test-merge-order.sh` does a local dry-run merge of clean PRs in sequence +5. **Report** — generates a prioritized queue and updates the GitHub milestone -**Output:** +## PR Type Classification -- `index.json` — array of all open PR summaries -- `prs/{number}.json` — detailed data per PR (reviews, CI checks, comments, and diff hunks for mergeable PRs) +PRs are classified by type based on labels, branch name, title, and diff shape: -## Merge Readiness Criteria +| Type | Examples | +|------|----------| +| `bug-fix` | `fix/`, `bugfix/` branches, `bug` label, `fix:` title prefix | +| `feature` | `feat/` branches, `enhancement` label, `feat:` title prefix | +| `refactor` | `refactor/` branches, `cleanup` label | +| `chore` | CI/config changes, `chore:` prefix, `deps` label | +| `docs` | Markdown-only changes, `docs/` branches | -A PR is **ready to merge** when: -- CI passes (all checks green or neutral) -- Not a draft -- No merge conflicts -- No unresolved human review comments -- Latest automated review has no genuine critical issues +## Queue Ranking -## Report Format +PRs are ranked by what needs human attention first: -The output is a single ranked list of all open PRs, ordered by merge readiness (fewest blockers first). Each PR entry includes a blocker table covering: +1. Bug fixes before features before refactors +2. Fewer blockers rank higher +3. Smaller PRs rank higher (faster to review) +4. Priority labels (`critical`, `hotfix`) boost rank +5. Draft PRs sort to the bottom -| Blocker Category | What It Checks | -|------------------|----------------| -| CI | All check runs passing | -| Merge conflicts | `mergeable` status is not `CONFLICTING` | -| Human review comments | Unresolved threads from human reviewers | -| Agent review issues | Critical issues from automated code review bots | -| Jira hygiene | Jira ticket reference in body or branch name | -| Staleness | Updated within 30 days, not superseded | -| Diff overlap risk | Line-level hunk overlap with other mergeable PRs | +## Review Readiness Criteria -For mergeable PRs, the fetch script pulls actual diff patches from the GitHub API. The agent parses `@@` hunk headers to detect line-range overlaps between PR pairs, enabling smarter merge ordering (merge the smaller PR first when two overlap on the same lines). - -A summary at the bottom tallies PRs by readiness bucket (clean, one blocker away, needs work, recommend closing). +A PR is **ready for review** when: +- CI passes (all checks green or neutral) +- Not a draft +- No merge conflicts +- No unresolved substantive review feedback +- Not stale (updated within 30 days) -## Customization +## Related Workflows -- Edit `templates/merge-meeting.md` to change the report format -- Edit `CLAUDE.md` to adjust readiness criteria or ordering logic -- The Jira pattern defaults to `RHOAIENG-\d+` but also catches any `[A-Z]{2,}-\d+` pattern +- **PR Fixer** (`internal-workflows/pr-fixer`) — fixes individual PRs flagged by the review queue (rebase, address feedback, run tests) diff --git a/internal-workflows/pr-overview/scripts/analyze-prs.py b/internal-workflows/pr-overview/scripts/analyze-prs.py index 5f6a28f9..4dad3d05 100755 --- a/internal-workflows/pr-overview/scripts/analyze-prs.py +++ b/internal-workflows/pr-overview/scripts/analyze-prs.py @@ -18,9 +18,46 @@ from datetime import datetime, timedelta, timezone -# ── Jira exclusions ────────────────────────────────────────────────────────── +# -- 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"}, + "branches": ("fix/", "bugfix/", "hotfix/", "bug/"), + "titles": ("fix:", "fix(", "bugfix:", "hotfix:"), + }, + "feature": { + "labels": {"feature", "enhancement"}, + "branches": ("feat/", "feature/"), + "titles": ("feat:", "feat(", "feature:", "add:"), + }, + "refactor": { + "labels": {"refactor", "cleanup", "tech-debt"}, + "branches": ("refactor/", "cleanup/", "tech-debt/"), + "titles": ("refactor:", "refactor(", "cleanup:"), + }, + "docs": { + "labels": {"docs", "documentation"}, + "branches": ("docs/", "doc/"), + "titles": ("docs:", "doc:"), + }, + "chore": { + "labels": {"chore", "ci", "dependencies", "deps"}, + "branches": ("chore/", "ci/", "deps/", "dependabot/", "renovate/"), + "titles": ("chore:", "chore(", "ci:", "ci(", "build:", "build("), + }, +} + +TYPE_PRIORITY = { + "bug-fix": 0, + "feature": 1, + "unknown": 2, + "refactor": 3, + "chore": 4, + "docs": 5, +} def parse_date(s): @@ -32,8 +69,53 @@ def parse_date(s): return None +# -- PR type classification -- -# ── Blocker checks ─────────────────────────────────────────────────────────── + +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() + + for pr_type, signals in TYPE_SIGNALS.items(): + if label_names & signals["labels"]: + return pr_type + + for pr_type, signals in TYPE_SIGNALS.items(): + if any(branch_lower.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"]): + 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" + + return "unknown" + + +# -- Blocker checks -- def check_ci(check_runs, status_rollup): @@ -54,7 +136,6 @@ def check_ci(check_runs, status_rollup): detail += f" (+{extra} more)" return "FAIL", f"Failing: {detail}" - # Check for in-progress runs (not yet completed) in_progress = [ cr for cr in check_runs @@ -66,7 +147,6 @@ def check_ci(check_runs, status_rollup): return "pass", "\u2014" - # Fallback to statusCheckRollup if status_rollup: failing = [ s @@ -76,7 +156,9 @@ def check_ci(check_runs, status_rollup): or s.get("state", "").upper() in ("FAILURE", "ERROR") ] if failing: - names = [s.get("name", "") or s.get("context", "unknown") for s in failing[:3]] + names = [ + s.get("name", "") or s.get("context", "unknown") for s in failing[:3] + ] extra = len(failing) - 3 detail = ", ".join(names) if extra > 0: @@ -99,24 +181,23 @@ def check_conflicts(mergeable): return "pass", "\u2014" elif mergeable == "CONFLICTING": return "FAIL", "Has merge conflicts" + elif mergeable == "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 agent's job. + """Handle deterministic review checks only. Comment evaluation is the sub-agent's job. Returns (status, detail, has_comments). - - status/detail cover only CHANGES_REQUESTED and inline threads. - - has_comments indicates whether the agent needs to evaluate comments. """ - # If the fetch failed, we can't know if there are comments — flag for review if not fetch_ok: - return "needs_review", "PR data incomplete — fetch may have failed", True + return "needs_review", "PR data incomplete \u2014 fetch may have failed", True issues = [] - # 1. Check for unresolved CHANGES_REQUESTED (handle DISMISSED) + # Check for unresolved CHANGES_REQUESTED user_states = {} for r in reviews: login = r.get("user", {}).get("login", "") @@ -129,9 +210,11 @@ def check_reviews(reviews, review_comments, pr_comments, fetch_ok=True): 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)}") + issues.append( + f"CHANGES_REQUESTED from {', '.join('@' + u for u in unresolved)}" + ) - # 2. Check inline review comments (count threads) + # Check inline review comments if review_comments: paths = set(c.get("path", "") for c in review_comments if c.get("path")) if paths: @@ -139,14 +222,13 @@ def check_reviews(reviews, review_comments, pr_comments, fetch_ok=True): f"{len(review_comments)} inline threads on {', '.join(list(paths)[:2])}" ) - # 3. Check if there are any comments worth reviewing (don't extract them — - # the agent spawns a sub-agent that reads the full raw PR file directly) + # 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 — agent to evaluate", True + return "needs_review", "Has comments \u2014 sub-agent to evaluate", True return "pass", "\u2014", False @@ -162,7 +244,6 @@ def check_jira(title, body, branch): def check_staleness(updated_at_str, now): - """Compute staleness signals for agent judgment. Returns (status, detail, staleness_data).""" if not updated_at_str: return "FAIL", "No updatedAt date found", {"days_old": None} updated = parse_date(updated_at_str) @@ -170,22 +251,22 @@ def check_staleness(updated_at_str, now): 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 ( + "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 ───────────────────────────────────────────────── +# -- Superseded PR detection -- def detect_superseded(results, index_map): - """Detect PRs that may be superseded by newer PRs touching the same files.""" - # Build a map of files touched by each PR (from index data) pr_files = {} for r in results: num = r["number"] idx = index_map.get(num, {}) - # changedFiles count is in the index, but actual file list is in detail - # We'll use branch name similarity and title similarity as signals pr_files[num] = { "branch": r["branch"], "title": r["title"].lower(), @@ -195,7 +276,7 @@ def detect_superseded(results, index_map): "changed_files": idx.get("changedFiles", 0), } - superseded = {} # pr_number -> superseding pr_number + superseded = {} for r in results: num = r["number"] @@ -207,11 +288,9 @@ def detect_superseded(results, index_map): continue other_info = pr_files[other_num] - # Skip if the other PR is older if other_info["created"] <= info["created"]: continue - # Check if branches suggest supersession (e.g., feat/foo-v2 supersedes feat/foo) if ( info["branch"] and other_info["branch"] @@ -221,7 +300,6 @@ def detect_superseded(results, index_map): superseded[num] = other_num break - # Check if titles are very similar (edit distance proxy: one contains the other) if ( len(info["title"]) > 15 and len(other_info["title"]) > 15 @@ -237,11 +315,10 @@ def detect_superseded(results, index_map): return superseded -# ── Diff hunk overlap analysis ─────────────────────────────────────────────── +# -- Diff hunk overlap analysis -- def parse_hunks(patch): - """Parse hunk headers from a unified diff patch string.""" if not patch: return [] hunks = [] @@ -257,7 +334,6 @@ def hunks_overlap(h1, h2): def compute_overlaps(pr_file_hunks): - """Find line-level overlaps between all pairs of mergeable PRs.""" nums = sorted(pr_file_hunks.keys()) overlaps = [] shared_no_overlap = [] @@ -295,11 +371,11 @@ def compute_overlaps(pr_file_hunks): return overlaps, shared_no_overlap -# ── Merge order computation ────────────────────────────────────────────────── +# -- Review order computation -- -def compute_merge_order(results, overlaps, pr_file_hunks): - """Compute a recommended merge sequence for clean, mergeable PRs.""" +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 @@ -309,7 +385,6 @@ def compute_merge_order(results, overlaps, pr_file_hunks): if not clean_mergeable: return [] - # Build overlap graph: edges between PRs that overlap overlap_graph = defaultdict(set) for o in overlaps: if o["pr_a"] in clean_mergeable and o["pr_b"] in clean_mergeable: @@ -320,11 +395,11 @@ def compute_merge_order(results, overlaps, pr_file_hunks): ordered = [] remaining = set(clean_mergeable) - # Greedy: pick PR with fewest overlap partners, priority labels first, smallest size 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"], @@ -336,11 +411,73 @@ def compute_merge_order(results, overlaps, pr_file_hunks): return ordered -# ── Main ───────────────────────────────────────────────────────────────────── +# -- 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 -- def main(): - parser = argparse.ArgumentParser(description="Analyze PRs for merge readiness") + parser = argparse.ArgumentParser(description="Analyze PRs for review readiness") parser.add_argument( "--output-dir", default="artifacts/pr-review", @@ -351,26 +488,26 @@ def main(): output_dir = args.output_dir now = datetime.now(timezone.utc) - # Load index with open(os.path.join(output_dir, "index.json")) as f: index = json.load(f) index_map = {pr["number"]: pr for pr in index} - # Analyze each PR results = [] - pr_file_hunks = {} # for overlap analysis + 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") - # Load detailed data pr_data = {} fetch_ok = False - if os.path.exists(pr_file) and os.path.getsize(pr_file) > 10: + 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", []) @@ -378,7 +515,6 @@ def main(): check_runs = pr_data.get("check_runs", []) diff_files = pr_data.get("diff_files", []) - # Use index as fallback for fields missing in detail 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)) @@ -391,38 +527,50 @@ def main(): 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", "") + 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) + 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) - # Count FAILs (warn doesn't count) fail_count = sum( 1 for s in [ci_status, conflict_status, review_status, stale_status] if s == "FAIL" ) - # Priority labels has_priority = any( - lb in ("priority/critical", "bug", "hotfix", "priority/high") for lb in labels + lb in ("priority/critical", "bug", "hotfix", "priority/high") + for lb in labels ) - # Size score (for ranking) size_score = additions + deletions + changed_files * 10 size_str = f"{changed_files} files (+{additions}/-{deletions})" - # Build file hunks for overlap analysis if not is_draft and mergeable == "MERGEABLE" and diff_files: file_hunks = {} for df in diff_files: @@ -437,13 +585,14 @@ def main(): results.append( { "number": num, - "rank": 0, # set after sorting + "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 "", @@ -527,7 +676,7 @@ def main(): r["overlap_status"] = "pass" r["overlap_detail"] = "\u2014" - # Flag PRs to recommend closing (for agent to review) + # Flag PRs to recommend closing for r in results: reasons = [] days = r["days_since_update"] @@ -543,10 +692,11 @@ def main(): r["recommend_close"] = True r["recommend_close_reason"] = "; ".join(reasons) - # Rank PRs + # 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"], @@ -555,8 +705,8 @@ def main(): for i, r in enumerate(results): r["rank"] = i + 1 - # Compute merge order for clean PRs - merge_order = compute_merge_order(results, overlaps, pr_file_hunks) + # Compute review order for clean PRs + review_order = compute_review_order(results, overlaps, pr_file_hunks) # Stats non_draft = [r for r in results if not r["isDraft"]] @@ -568,13 +718,18 @@ def main(): "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_count": sum(1 for r in results if r["is_fork"]), + "by_type": {}, } - # ── Collect PRs needing agent review ──────────────────────────────────── + # Type breakdown + for r in results: + t = r["pr_type"] + stats["by_type"][t] = stats["by_type"].get(t, 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 ─────────────────────────────────────── + # Write per-PR analysis files analysis_dir = os.path.join(output_dir, "analysis") os.makedirs(analysis_dir, exist_ok=True) @@ -583,55 +738,19 @@ def main(): with open(pr_path, "w") as f: json.dump(r, f, indent=2, ensure_ascii=False) - # ── Write per-comment review files for needs_review PRs ─────────────── - # Raw prs/{number}.json can be 50-80KB (diffs, patches, full body) which - # exceeds the Read tool's output limit. Instead, extract each comment into - # its own small file so the sub-agent can read them one at a time, newest - # first, and stop as soon as it finds the latest bot review. + # 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_path = os.path.join(output_dir, "prs", f"{num}.json") - if not os.path.exists(raw_path): + raw = pr_data_cache.get(num, {}) + if not raw: continue - with open(raw_path) as f: - raw = json.load(f) + all_comments = extract_unified_comments(raw) pr = raw.get("pr", {}) - all_comments = [] - - # PR comments (includes bot reviews) - for c in pr.get("comments", []): - all_comments.append({ - "source": "pr_comment", - "author": c.get("author", {}).get("login", ""), - "body": c.get("body", ""), - }) - - # Formal reviews with body content - for r_item in raw.get("reviews", []): - body = r_item.get("body", "") - if body and body.strip(): - all_comments.append({ - "source": "review", - "author": r_item.get("user", {}).get("login", ""), - "state": r_item.get("state", ""), - "body": body, - }) - - # Inline review comments - for rc in raw.get("review_comments", []): - body = rc.get("body", "") - if body and body.strip(): - all_comments.append({ - "source": "inline_comment", - "author": rc.get("user", {}).get("login", ""), - "path": rc.get("path", ""), - "body": body, - }) # Write meta file meta = { @@ -643,31 +762,34 @@ def main(): 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 (01.json, 02.json, ...) + # 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 (no per-PR details — just the index) ──────── + # 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"], - "fail_count": r["fail_count"], - "review_status": r["review_status"], - "recommend_close": r["recommend_close"], - "is_fork": r["is_fork"], - }) + 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 = { "generated_at": now.strftime("%Y-%m-%dT%H:%M:%S UTC"), "stats": stats, - "merge_order": merge_order, + "review_order": review_order, "needs_review": needs_review_nums, "pr_index": pr_index, "overlaps": overlaps, @@ -678,17 +800,26 @@ def main(): with open(summary_path, "w") as f: json.dump(summary, f, indent=2, ensure_ascii=False) - print(f"Analysis complete:") + 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" Clean: {stats['clean']} | One blocker: {stats['one_blocker']} | Needs work: {stats['needs_work']}" + ) print(f" Recommend closing: {stats['recommend_close']}") - print(f" Needs agent review: {len(needs_review_nums)} PRs — {needs_review_nums}") - print(f" Overlaps: {len(overlaps)} line-level, {len(shared_no_overlap)} shared-file-only") - if merge_order: - print(f" Merge order: {' → '.join(f'#{n}' for n in merge_order[:10])}") + 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" + ) + if review_order: + print( + f" Review order: {' \u2192 '.join(f'#{n}' for n in review_order[:10])}" + ) if __name__ == "__main__": diff --git a/internal-workflows/pr-overview/templates/review-queue.md b/internal-workflows/pr-overview/templates/review-queue.md new file mode 100644 index 00000000..e563c34e --- /dev/null +++ b/internal-workflows/pr-overview/templates/review-queue.md @@ -0,0 +1,73 @@ +# Review Queue — {{REPO}} + +**Date:** {{DATE}} +**Open PRs:** {{TOTAL_PRS}} | **Ready for Review:** {{READY_COUNT}} | **In Review Queue:** {{MILESTONE_COUNT}} + +### At a Glance + +{{AT_A_GLANCE}} + +--- + +## Ready for Review ({{READY_COUNT}}) + +> Ordered by priority: bug fixes first, then features, smallest first within each type. + +| # | PR | Type | Author | Size | Updated | Action Needed | Notes | +|---|---|---|---|---|---|---|---| +{{#each READY_PR_ROWS}} +| {{RANK}} | [#{{NUMBER}}]({{URL}}) — {{TITLE}} | {{TYPE}} | {{AUTHOR}} | {{SIZE}} | {{UPDATED}} | {{ACTION_NEEDED}} | {{NOTES}} | +{{/each}} + +--- + +## PRs With Blockers + +{{#each BLOCKER_PR_ENTRIES}} + +### {{RANK}}. [#{{NUMBER}}]({{URL}}) — {{TITLE}} + +**Author:** {{AUTHOR}} | **Type:** {{TYPE}} | **Size:** {{SIZE}} | **Updated:** {{UPDATED}} | **Branch:** `{{BRANCH}}` + +| Blocker | Status | Detail | +|---------|--------|--------| +| CI | {{CI_STATUS}} | {{CI_DETAIL}} | +| Merge conflicts | {{CONFLICT_STATUS}} | {{CONFLICT_DETAIL}} | +| Review comments | {{REVIEW_STATUS}} | {{REVIEW_DETAIL}} | +| Jira hygiene | {{JIRA_STATUS}} | {{JIRA_DETAIL}} | +| Staleness | {{STALE_STATUS}} | {{STALE_DETAIL}} | +| Diff overlap risk | {{OVERLAP_STATUS}} | {{OVERLAP_DETAIL}} | + +**Action needed:** {{ACTION_NEEDED}} + +{{#if REVIEW_SUMMARY}} +> {{REVIEW_SUMMARY}} +{{/if}} + +--- + +{{/each}} + +{{#if RECOMMEND_CLOSE_ENTRIES}} +## Recommend Closing + +> These PRs appear abandoned, superseded, or too stale to maintain. Close or ping the author. + +| PR | Author | Reason | Last Updated | +|---|---|---|---| +{{#each RECOMMEND_CLOSE_ENTRIES}} +| [#{{NUMBER}}]({{URL}}) — {{TITLE}} | {{AUTHOR}} | {{REASON}} | {{UPDATED}} | +{{/each}} + +--- + +{{/if}} + +## Summary + +- **Ready for review:** {{READY_COUNT}} PRs with zero blockers +- **In Review Queue:** {{MILESTONE_COUNT}} PRs +- **One blocker away:** {{NEAR_COUNT}} PRs +- **Needs work:** {{WORK_COUNT}} PRs +- **Recommend closing:** {{CLOSE_COUNT}} PRs +{{#if FORK_COUNT}}- **Fork PRs:** {{FORK_COUNT}} (marked in tables — no automated agent review, require manual review){{/if}} From 200e55fbc659cd62ad9dad445d5cad9ed680bbf4 Mon Sep 17 00:00:00 2001 From: Gage Krumbach Date: Tue, 10 Mar 2026 13:25:29 -0500 Subject: [PATCH 2/2] fix: address review feedback on workflows PR - Fix ambient.json: remove stale "test merge order" ref, update to 9-step - Fix CLAUDE.md: UNKNOWN mergeability is warn, not blocker (matches script) - Fix analyze-prs.py: check_reviews returns FAIL when fetch_ok=False - Fix analyze-prs.py: recompute fail_count after overlap_status is set - Fix fetch-pr.sh: use headRefOid instead of statusCheckRollup for HEAD SHA - Fix rubric.md: benchmark step order matches actual workflow - Fix markdown: add language specs to fenced code blocks in READMEs Co-Authored-By: Claude Opus 4.6 (1M context) --- internal-workflows/pr-fixer/README.md | 2 +- internal-workflows/pr-fixer/scripts/fetch-pr.sh | 4 ++-- internal-workflows/pr-overview/.ambient/ambient.json | 4 ++-- internal-workflows/pr-overview/.ambient/rubric.md | 11 +++++------ internal-workflows/pr-overview/CLAUDE.md | 3 ++- internal-workflows/pr-overview/README.md | 2 +- internal-workflows/pr-overview/scripts/analyze-prs.py | 11 ++++++++++- 7 files changed, 23 insertions(+), 14 deletions(-) diff --git a/internal-workflows/pr-fixer/README.md b/internal-workflows/pr-fixer/README.md index c338f840..f4488fb8 100644 --- a/internal-workflows/pr-fixer/README.md +++ b/internal-workflows/pr-fixer/README.md @@ -22,7 +22,7 @@ The agent reads the fetched data, checks out the PR branch, and works through: r ## Directory Structure -``` +```text pr-fixer/ ├── .ambient/ │ └── ambient.json # Workflow config diff --git a/internal-workflows/pr-fixer/scripts/fetch-pr.sh b/internal-workflows/pr-fixer/scripts/fetch-pr.sh index ff5c46f9..5d9ebc3b 100755 --- a/internal-workflows/pr-fixer/scripts/fetch-pr.sh +++ b/internal-workflows/pr-fixer/scripts/fetch-pr.sh @@ -74,7 +74,7 @@ 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,url,state,additions,deletions,changedFiles,mergeable,body,reviewDecision,statusCheckRollup,comments,assignees,milestone,files,isCrossRepository,headRepositoryOwner" +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 @@ -104,7 +104,7 @@ 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 '.statusCheckRollup // [] | if length > 0 then .[0].commit.oid // empty else empty end' "${OUTPUT_DIR}/pr.json" 2>/dev/null || true) +HEAD_SHA=$(jq -r '.headRefOid // empty' "${OUTPUT_DIR}/pr.json" 2>/dev/null || true) echo '[]' > "${OUTPUT_DIR}/ci.json" if [[ -n "$HEAD_SHA" ]]; then diff --git a/internal-workflows/pr-overview/.ambient/ambient.json b/internal-workflows/pr-overview/.ambient/ambient.json index 30a3d4f4..c5b2ae17 100644 --- a/internal-workflows/pr-overview/.ambient/ambient.json +++ b/internal-workflows/pr-overview/.ambient/ambient.json @@ -1,8 +1,8 @@ { "name": "Review Queue", "description": "Evaluate open PRs and generate a prioritized review queue — an ordered list of what needs human attention, ranked by type and urgency", - "systemPrompt": "You are a PR review queue agent. Follow the instructions in CLAUDE.md to execute the workflow: fetch PR data, analyze, evaluate each PR via sub-agents, test merge order, manage milestone, write report, and update milestone description. The output is an attention-ordered queue — bug fixes and small PRs first.", - "startupPrompt": "You are the Review Queue agent. Follow the instructions in CLAUDE.md. Start with the 10-step task checklist and complete every step.", + "systemPrompt": "You are a PR review queue agent. Follow the instructions in CLAUDE.md to execute the workflow: fetch PR data, analyze, evaluate each PR via sub-agents, manage milestone, write report, and update milestone description. The output is an attention-ordered queue — bug fixes and small PRs first.", + "startupPrompt": "You are the Review Queue agent. Follow the instructions in CLAUDE.md. Start with the 9-step task checklist and complete every step.", "results": { "Review Queue Report": "artifacts/pr-review/review-queue-{date}.md", "Analysis Summary": "artifacts/pr-review/analysis.json" diff --git a/internal-workflows/pr-overview/.ambient/rubric.md b/internal-workflows/pr-overview/.ambient/rubric.md index b9cc5764..af1f2af9 100644 --- a/internal-workflows/pr-overview/.ambient/rubric.md +++ b/internal-workflows/pr-overview/.ambient/rubric.md @@ -46,12 +46,11 @@ Did the agent complete the workflow in a reasonable number of tool calls? 1. Read CLAUDE.md + template (2 calls) 2. Run fetch-prs.sh (1 call) 3. Run analyze-prs.py (1 call) -4. Spawn parallel sub-agents for per-PR evaluation (1-3 calls) -5. Find/create milestone + sync PRs (2-3 calls) -6. Read analysis summary + needed per-PR files (3-5 calls) -7. Write report (1 call) -8. Update milestone description (1 call) -Total: ~13-18 calls +4. Read analysis summary + spawn parallel sub-agents for per-PR evaluation (2-4 calls) +5. Find/create milestone + sync PRs + comment on blocked (3-5 calls) +6. Write report (1 call) +7. Update milestone description (1 call) +Total: ~11-15 calls --- diff --git a/internal-workflows/pr-overview/CLAUDE.md b/internal-workflows/pr-overview/CLAUDE.md index b4255817..09c245a8 100644 --- a/internal-workflows/pr-overview/CLAUDE.md +++ b/internal-workflows/pr-overview/CLAUDE.md @@ -147,7 +147,8 @@ For **every** open PR, evaluate each of these categories. Each is either clear o - Check the `mergeable` field. - **Clear:** `MERGEABLE`. -- **Blocker:** `CONFLICTING` or `UNKNOWN`. Note which files overlap with other open PRs if detectable. +- **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 diff --git a/internal-workflows/pr-overview/README.md b/internal-workflows/pr-overview/README.md index b4ea5210..01c3448d 100644 --- a/internal-workflows/pr-overview/README.md +++ b/internal-workflows/pr-overview/README.md @@ -21,7 +21,7 @@ The agent reads the fetched data, evaluates each PR via sub-agents, and writes a ## Directory Structure -``` +```text pr-overview/ ├── .ambient/ │ ├── ambient.json # Workflow config diff --git a/internal-workflows/pr-overview/scripts/analyze-prs.py b/internal-workflows/pr-overview/scripts/analyze-prs.py index 4dad3d05..598345fe 100755 --- a/internal-workflows/pr-overview/scripts/analyze-prs.py +++ b/internal-workflows/pr-overview/scripts/analyze-prs.py @@ -193,7 +193,7 @@ def check_reviews(reviews, review_comments, pr_comments, fetch_ok=True): Returns (status, detail, has_comments). """ if not fetch_ok: - return "needs_review", "PR data incomplete \u2014 fetch may have failed", True + return "FAIL", "PR data incomplete \u2014 fetch may have failed", True issues = [] @@ -676,6 +676,15 @@ def main(): 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 for r in results: reasons = []