|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""GitHub PR comment-based review flow for agentic test iteration. |
| 3 | +
|
| 4 | +Posts fix details as PR comments and polls for author replies within a |
| 5 | +timed review window. Designed to work alongside Slack webhook notifications |
| 6 | +(one-way) — GitHub PR comments provide the two-way interaction channel. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + # Post a review comment on a PR |
| 10 | + python3 review-github.py post <pr_number> <message> [--repo owner/repo] |
| 11 | +
|
| 12 | + # Wait for author reply within a review window |
| 13 | + python3 review-github.py wait <pr_number> <since_timestamp> [--timeout 600] [--repo owner/repo] |
| 14 | +
|
| 15 | +Output formats: |
| 16 | + post: COMMENT_ID=<id> COMMENT_TIME=<iso_timestamp> |
| 17 | + wait: REPLY=<text> (author replied) |
| 18 | + NO_REPLY (timeout reached, no author reply) |
| 19 | +
|
| 20 | +Requires: gh CLI authenticated with comment access to the target repo. |
| 21 | +
|
| 22 | +Security: Author filtering is enforced deterministically in code — |
| 23 | +the PR author's login is fetched via API and only comments from that |
| 24 | +user are considered. This is not instruction-based filtering. |
| 25 | +""" |
| 26 | + |
| 27 | +import argparse |
| 28 | +import json |
| 29 | +import subprocess |
| 30 | +import sys |
| 31 | +import time |
| 32 | +from datetime import datetime, timezone |
| 33 | + |
| 34 | + |
| 35 | +DEFAULT_REPO = "openshift/monitoring-plugin" |
| 36 | +MAGIC_PREFIX = "/agent" |
| 37 | + |
| 38 | + |
| 39 | +def gh_api(endpoint, method="GET", body=None, repo=None): |
| 40 | + """Call GitHub API via gh CLI.""" |
| 41 | + cmd = ["gh", "api"] |
| 42 | + if repo: |
| 43 | + endpoint = endpoint.replace("{repo}", repo) |
| 44 | + if method != "GET": |
| 45 | + cmd.extend(["--method", method]) |
| 46 | + if body: |
| 47 | + for key, value in body.items(): |
| 48 | + cmd.extend(["-f", f"{key}={value}"]) |
| 49 | + cmd.append(endpoint) |
| 50 | + |
| 51 | + result = subprocess.run(cmd, capture_output=True, text=True) |
| 52 | + if result.returncode != 0: |
| 53 | + print(f"gh api failed: {result.stderr.strip()}", file=sys.stderr) |
| 54 | + return None |
| 55 | + |
| 56 | + if not result.stdout.strip(): |
| 57 | + return {} |
| 58 | + |
| 59 | + try: |
| 60 | + return json.loads(result.stdout) |
| 61 | + except json.JSONDecodeError: |
| 62 | + print(f"Invalid JSON from gh api: {result.stdout[:200]}", file=sys.stderr) |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | +def get_pr_author(pr, repo): |
| 67 | + """Fetch the PR author's login.""" |
| 68 | + data = gh_api(f"repos/{repo}/pulls/{pr}") |
| 69 | + if data and "user" in data: |
| 70 | + return data["user"]["login"] |
| 71 | + return None |
| 72 | + |
| 73 | + |
| 74 | +def post_comment(pr, message, repo): |
| 75 | + """Post a comment on a PR. Returns (comment_id, created_at).""" |
| 76 | + data = gh_api( |
| 77 | + f"repos/{repo}/issues/{pr}/comments", |
| 78 | + method="POST", |
| 79 | + body={"body": message}, |
| 80 | + ) |
| 81 | + if data and "id" in data: |
| 82 | + comment_id = data["id"] |
| 83 | + created_at = data.get("created_at", "") |
| 84 | + print(f"COMMENT_ID={comment_id}") |
| 85 | + print(f"COMMENT_TIME={created_at}") |
| 86 | + return comment_id, created_at |
| 87 | + |
| 88 | + print("Failed to post comment", file=sys.stderr) |
| 89 | + return None, None |
| 90 | + |
| 91 | + |
| 92 | +def wait_for_author_reply(pr, since_timestamp, repo, timeout=600, poll_interval=30): |
| 93 | + """Poll PR comments for a reply from the PR author. |
| 94 | +
|
| 95 | + Only considers comments that: |
| 96 | + 1. Were posted AFTER since_timestamp (time-scoped) |
| 97 | + 2. Were authored by the PR author (deterministic .user.login check) |
| 98 | + 3. Optionally start with the magic prefix /agent (if present, stripped from reply) |
| 99 | +
|
| 100 | + Args: |
| 101 | + pr: PR number |
| 102 | + since_timestamp: ISO 8601 timestamp — only comments after this are considered |
| 103 | + repo: owner/repo string |
| 104 | + timeout: seconds to wait before giving up |
| 105 | + poll_interval: seconds between polls |
| 106 | +
|
| 107 | + Returns: |
| 108 | + Reply text if found, None otherwise. |
| 109 | + """ |
| 110 | + # Fetch PR author login — deterministic, code-enforced filter |
| 111 | + pr_author = get_pr_author(pr, repo) |
| 112 | + if not pr_author: |
| 113 | + print("Could not determine PR author. Proceeding without review.", file=sys.stderr) |
| 114 | + print("NO_REPLY") |
| 115 | + return None |
| 116 | + |
| 117 | + print(f"Waiting up to {timeout}s for reply from @{pr_author} on PR #{pr}...", flush=True) |
| 118 | + |
| 119 | + deadline = time.time() + timeout |
| 120 | + seen_ids = set() |
| 121 | + |
| 122 | + while time.time() < deadline: |
| 123 | + # Fetch comments created after since_timestamp |
| 124 | + comments = gh_api( |
| 125 | + f"repos/{repo}/issues/{pr}/comments?since={since_timestamp}&per_page=50" |
| 126 | + ) |
| 127 | + |
| 128 | + if comments is None: |
| 129 | + remaining = int(deadline - time.time()) |
| 130 | + if remaining > 0: |
| 131 | + print(f"API error, retrying in {poll_interval}s ({remaining}s remaining)...", |
| 132 | + file=sys.stderr, flush=True) |
| 133 | + time.sleep(min(poll_interval, max(1, remaining))) |
| 134 | + continue |
| 135 | + |
| 136 | + for comment in comments: |
| 137 | + comment_id = comment.get("id") |
| 138 | + if comment_id in seen_ids: |
| 139 | + continue |
| 140 | + seen_ids.add(comment_id) |
| 141 | + |
| 142 | + # Deterministic author filter — code-enforced, not instruction-based |
| 143 | + commenter = comment.get("user", {}).get("login", "") |
| 144 | + if commenter != pr_author: |
| 145 | + continue |
| 146 | + |
| 147 | + body = comment.get("body", "").strip() |
| 148 | + |
| 149 | + # If magic prefix is used, strip it; otherwise accept any author comment |
| 150 | + if body.startswith(MAGIC_PREFIX): |
| 151 | + body = body[len(MAGIC_PREFIX):].strip() |
| 152 | + |
| 153 | + if body: |
| 154 | + print(f"REPLY={body}") |
| 155 | + return body |
| 156 | + |
| 157 | + remaining = int(deadline - time.time()) |
| 158 | + if remaining > 0: |
| 159 | + print( |
| 160 | + f"No reply yet from @{pr_author}, {remaining}s remaining...", |
| 161 | + file=sys.stderr, |
| 162 | + flush=True, |
| 163 | + ) |
| 164 | + time.sleep(min(poll_interval, max(1, remaining))) |
| 165 | + |
| 166 | + print("NO_REPLY") |
| 167 | + return None |
| 168 | + |
| 169 | + |
| 170 | +def format_fix_comment(message): |
| 171 | + """Wrap the agent's message in a standard comment format.""" |
| 172 | + return ( |
| 173 | + "### Agent: Fix Applied\n\n" |
| 174 | + f"{message}\n\n" |
| 175 | + "---\n" |
| 176 | + f"*Reply to this comment (or prefix with `{MAGIC_PREFIX}`) to provide feedback. " |
| 177 | + "The agent will incorporate your input before pushing, or proceed automatically " |
| 178 | + "after the review window expires.*" |
| 179 | + ) |
| 180 | + |
| 181 | + |
| 182 | +def cmd_post(args): |
| 183 | + """Handle the 'post' subcommand.""" |
| 184 | + formatted = format_fix_comment(args.message) |
| 185 | + comment_id, created_at = post_comment(args.pr, formatted, args.repo) |
| 186 | + return 0 if comment_id else 1 |
| 187 | + |
| 188 | + |
| 189 | +def cmd_wait(args): |
| 190 | + """Handle the 'wait' subcommand.""" |
| 191 | + wait_for_author_reply( |
| 192 | + args.pr, args.since, args.repo, timeout=args.timeout |
| 193 | + ) |
| 194 | + return 0 |
| 195 | + |
| 196 | + |
| 197 | +def main(): |
| 198 | + parser = argparse.ArgumentParser( |
| 199 | + description="GitHub PR comment-based review for agentic test iteration" |
| 200 | + ) |
| 201 | + parser.add_argument( |
| 202 | + "--repo", default=DEFAULT_REPO, |
| 203 | + help=f"GitHub repo (default: {DEFAULT_REPO})" |
| 204 | + ) |
| 205 | + subparsers = parser.add_subparsers(dest="command", required=True) |
| 206 | + |
| 207 | + # 'post' subcommand |
| 208 | + post_parser = subparsers.add_parser("post", help="Post a review comment on a PR") |
| 209 | + post_parser.add_argument("pr", help="PR number") |
| 210 | + post_parser.add_argument("message", help="Comment body (markdown supported)") |
| 211 | + |
| 212 | + # 'wait' subcommand |
| 213 | + wait_parser = subparsers.add_parser( |
| 214 | + "wait", help="Wait for author reply on a PR" |
| 215 | + ) |
| 216 | + wait_parser.add_argument("pr", help="PR number") |
| 217 | + wait_parser.add_argument("since", help="ISO 8601 timestamp — only consider comments after this") |
| 218 | + wait_parser.add_argument( |
| 219 | + "--timeout", type=int, default=600, |
| 220 | + help="Seconds to wait for reply (default: 600)" |
| 221 | + ) |
| 222 | + |
| 223 | + args = parser.parse_args() |
| 224 | + |
| 225 | + if args.command == "post": |
| 226 | + return cmd_post(args) |
| 227 | + elif args.command == "wait": |
| 228 | + return cmd_wait(args) |
| 229 | + |
| 230 | + |
| 231 | +if __name__ == "__main__": |
| 232 | + sys.exit(main()) |
0 commit comments