mirror of
https://github.com/mhattingpete/personal-ai-os.git
synced 2026-11-18 18:04:27 +00:00
Add GitHub PR review automation with Claude Code integration
- Add GitHubPRTrigger and GitHubPRCondition models for PR review triggers - Add GitHubReviewAction model for launching Claude Code with review context - Create pai_mcp/github.py MCP server with 5 tools (list_my_prs, list_prs_with_reviews, get_pr_reviews, get_pr_diff, format_review_for_claude) - Add GitHubPRWatcher to poll for new PR reviews on authored PRs - Implement _execute_github_review in executor to prepare Claude Code context - Add 'pai watch github' CLI command - Update db.py to support multiple watcher types - Add GitHub action mappings to MCP routing - Add 48 new tests covering all GitHub functionality
This commit is contained in:
@@ -0,0 +1,346 @@
|
||||
"""GitHub MCP server for PAI.
|
||||
|
||||
Provides tools to interact with GitHub PRs and reviews using the gh CLI.
|
||||
Run with: uv run pai-github-mcp
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP("PAI GitHub", json_response=True)
|
||||
|
||||
|
||||
async def _run_gh(*args: str) -> dict | list | None:
|
||||
"""Run gh CLI command and parse JSON output."""
|
||||
cmd = ["gh", *args]
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
stdout, stderr = await proc.communicate()
|
||||
|
||||
if proc.returncode != 0:
|
||||
error_msg = stderr.decode().strip() if stderr else "Unknown error"
|
||||
return {"error": error_msg, "returncode": proc.returncode}
|
||||
|
||||
if not stdout:
|
||||
return None
|
||||
|
||||
return json.loads(stdout.decode())
|
||||
except json.JSONDecodeError:
|
||||
# Return raw output if not JSON
|
||||
return {"raw": stdout.decode().strip()}
|
||||
except FileNotFoundError:
|
||||
return {"error": "gh CLI not found. Install from https://cli.github.com"}
|
||||
|
||||
|
||||
def _get_current_user() -> str | None:
|
||||
"""Get the authenticated GitHub username synchronously."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["gh", "api", "user", "--jq", ".login"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
return result.stdout.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def list_my_prs(state: str = "open") -> dict:
|
||||
"""List PRs authored by the authenticated user.
|
||||
|
||||
Args:
|
||||
state: PR state filter - "open", "closed", "merged", or "all"
|
||||
|
||||
Returns:
|
||||
Dict with list of PRs
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return {"error": "Not authenticated with gh CLI"}
|
||||
|
||||
result = await _run_gh(
|
||||
"pr", "list",
|
||||
"--author", user,
|
||||
"--state", state,
|
||||
"--json", "number,title,url,state,headRepository,createdAt,updatedAt,reviewDecision,reviews",
|
||||
"--limit", "50",
|
||||
)
|
||||
|
||||
if isinstance(result, dict) and "error" in result:
|
||||
return result
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
"state": state,
|
||||
"prs": result or [],
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def list_prs_with_reviews(since_hours: int = 24) -> dict:
|
||||
"""List PRs authored by me that have received reviews recently.
|
||||
|
||||
Args:
|
||||
since_hours: Look for reviews in the last N hours
|
||||
|
||||
Returns:
|
||||
Dict with PRs that have new reviews
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return {"error": "Not authenticated with gh CLI"}
|
||||
|
||||
# Get all open PRs by the user
|
||||
prs_result = await _run_gh(
|
||||
"pr", "list",
|
||||
"--author", user,
|
||||
"--state", "open",
|
||||
"--json", "number,title,url,headRepository,reviews,headRefName",
|
||||
"--limit", "50",
|
||||
)
|
||||
|
||||
if isinstance(prs_result, dict) and "error" in prs_result:
|
||||
return prs_result
|
||||
|
||||
prs_with_reviews = []
|
||||
for pr in prs_result or []:
|
||||
reviews = pr.get("reviews", [])
|
||||
if reviews:
|
||||
prs_with_reviews.append({
|
||||
"number": pr["number"],
|
||||
"title": pr["title"],
|
||||
"url": pr["url"],
|
||||
"repo": pr["headRepository"]["nameWithOwner"],
|
||||
"branch": pr["headRefName"],
|
||||
"review_count": len(reviews),
|
||||
"latest_review": reviews[-1] if reviews else None,
|
||||
})
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
"prs_with_reviews": prs_with_reviews,
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def get_pr_reviews(repo: str, pr_number: int) -> dict:
|
||||
"""Get all reviews and comments for a PR.
|
||||
|
||||
Args:
|
||||
repo: Repository in owner/repo format
|
||||
pr_number: Pull request number
|
||||
|
||||
Returns:
|
||||
Dict with reviews, comments, and review threads
|
||||
"""
|
||||
# Get PR details
|
||||
pr_result = await _run_gh(
|
||||
"pr", "view", str(pr_number),
|
||||
"--repo", repo,
|
||||
"--json", "number,title,body,author,state,additions,deletions,changedFiles,files,headRefName,baseRefName",
|
||||
)
|
||||
|
||||
if isinstance(pr_result, dict) and "error" in pr_result:
|
||||
return pr_result
|
||||
|
||||
# Get reviews
|
||||
reviews_result = await _run_gh(
|
||||
"api", f"repos/{repo}/pulls/{pr_number}/reviews",
|
||||
)
|
||||
|
||||
# Get review comments (inline comments)
|
||||
comments_result = await _run_gh(
|
||||
"api", f"repos/{repo}/pulls/{pr_number}/comments",
|
||||
)
|
||||
|
||||
reviews = []
|
||||
if isinstance(reviews_result, list):
|
||||
for review in reviews_result:
|
||||
reviews.append({
|
||||
"id": review.get("id"),
|
||||
"author": review.get("user", {}).get("login"),
|
||||
"state": review.get("state"), # APPROVED, CHANGES_REQUESTED, COMMENTED
|
||||
"body": review.get("body"),
|
||||
"submitted_at": review.get("submitted_at"),
|
||||
})
|
||||
|
||||
comments = []
|
||||
if isinstance(comments_result, list):
|
||||
for comment in comments_result:
|
||||
comments.append({
|
||||
"id": comment.get("id"),
|
||||
"author": comment.get("user", {}).get("login"),
|
||||
"path": comment.get("path"),
|
||||
"line": comment.get("line") or comment.get("original_line"),
|
||||
"body": comment.get("body"),
|
||||
"created_at": comment.get("created_at"),
|
||||
"diff_hunk": comment.get("diff_hunk"),
|
||||
"in_reply_to_id": comment.get("in_reply_to_id"),
|
||||
})
|
||||
|
||||
return {
|
||||
"repo": repo,
|
||||
"pr": pr_result,
|
||||
"reviews": reviews,
|
||||
"comments": comments,
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def get_pr_diff(repo: str, pr_number: int) -> dict:
|
||||
"""Get the diff for a PR.
|
||||
|
||||
Args:
|
||||
repo: Repository in owner/repo format
|
||||
pr_number: Pull request number
|
||||
|
||||
Returns:
|
||||
Dict with diff content and changed files
|
||||
"""
|
||||
# Get diff
|
||||
diff_result = await _run_gh(
|
||||
"pr", "diff", str(pr_number),
|
||||
"--repo", repo,
|
||||
)
|
||||
|
||||
# Get file list
|
||||
files_result = await _run_gh(
|
||||
"pr", "view", str(pr_number),
|
||||
"--repo", repo,
|
||||
"--json", "files",
|
||||
)
|
||||
|
||||
diff_text = ""
|
||||
if isinstance(diff_result, dict):
|
||||
if "raw" in diff_result:
|
||||
diff_text = diff_result["raw"]
|
||||
elif "error" in diff_result:
|
||||
return diff_result
|
||||
|
||||
files = []
|
||||
if isinstance(files_result, dict) and "files" in files_result:
|
||||
files = files_result["files"]
|
||||
|
||||
return {
|
||||
"repo": repo,
|
||||
"pr_number": pr_number,
|
||||
"diff": diff_text,
|
||||
"files": files,
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def format_review_for_claude(repo: str, pr_number: int) -> dict:
|
||||
"""Format PR review data as a prompt for Claude Code.
|
||||
|
||||
Args:
|
||||
repo: Repository in owner/repo format
|
||||
pr_number: Pull request number
|
||||
|
||||
Returns:
|
||||
Dict with formatted prompt and metadata
|
||||
"""
|
||||
# Fetch all PR data
|
||||
reviews_data = await get_pr_reviews(repo, pr_number)
|
||||
if "error" in reviews_data:
|
||||
return reviews_data
|
||||
|
||||
diff_data = await get_pr_diff(repo, pr_number)
|
||||
|
||||
pr = reviews_data.get("pr", {})
|
||||
reviews = reviews_data.get("reviews", [])
|
||||
comments = reviews_data.get("comments", [])
|
||||
|
||||
# Build the prompt
|
||||
prompt_parts = [
|
||||
f"# PR Review Implementation Task",
|
||||
f"",
|
||||
f"## Pull Request: {pr.get('title', 'Unknown')} (#{pr_number})",
|
||||
f"**Repository:** {repo}",
|
||||
f"**Branch:** {pr.get('headRefName', 'unknown')} -> {pr.get('baseRefName', 'main')}",
|
||||
f"**Changes:** +{pr.get('additions', 0)} -{pr.get('deletions', 0)} in {pr.get('changedFiles', 0)} files",
|
||||
f"",
|
||||
]
|
||||
|
||||
# Add reviews
|
||||
if reviews:
|
||||
prompt_parts.append("## Reviews")
|
||||
for review in reviews:
|
||||
state_emoji = {
|
||||
"APPROVED": "approved",
|
||||
"CHANGES_REQUESTED": "changes requested",
|
||||
"COMMENTED": "commented",
|
||||
}.get(review.get("state", ""), review.get("state", ""))
|
||||
prompt_parts.append(f"")
|
||||
prompt_parts.append(f"### @{review.get('author', 'unknown')} ({state_emoji})")
|
||||
if review.get("body"):
|
||||
prompt_parts.append(f"{review['body']}")
|
||||
|
||||
# Add inline comments grouped by file
|
||||
if comments:
|
||||
prompt_parts.append("")
|
||||
prompt_parts.append("## Inline Comments")
|
||||
|
||||
# Group by file
|
||||
comments_by_file: dict[str, list] = {}
|
||||
for comment in comments:
|
||||
path = comment.get("path", "unknown")
|
||||
if path not in comments_by_file:
|
||||
comments_by_file[path] = []
|
||||
comments_by_file[path].append(comment)
|
||||
|
||||
for path, file_comments in comments_by_file.items():
|
||||
prompt_parts.append(f"")
|
||||
prompt_parts.append(f"### {path}")
|
||||
for comment in file_comments:
|
||||
line = comment.get("line", "?")
|
||||
author = comment.get("author", "unknown")
|
||||
body = comment.get("body", "")
|
||||
prompt_parts.append(f"")
|
||||
prompt_parts.append(f"**Line {line}** (@{author}):")
|
||||
prompt_parts.append(f"{body}")
|
||||
|
||||
# Add instructions
|
||||
prompt_parts.extend([
|
||||
"",
|
||||
"## Your Task",
|
||||
"",
|
||||
"1. Read and understand each review comment above",
|
||||
"2. Implement the requested changes",
|
||||
"3. Commit your changes with a descriptive message",
|
||||
"4. Push to update the PR",
|
||||
"",
|
||||
"Focus on addressing each comment. If a suggestion is unclear or you disagree, explain why.",
|
||||
])
|
||||
|
||||
prompt = "\n".join(prompt_parts)
|
||||
|
||||
return {
|
||||
"repo": repo,
|
||||
"pr_number": pr_number,
|
||||
"branch": pr.get("headRefName"),
|
||||
"prompt": prompt,
|
||||
"review_count": len(reviews),
|
||||
"comment_count": len(comments),
|
||||
"files_changed": [f.get("path") for f in pr.get("files", [])],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
"""Run the GitHub MCP server."""
|
||||
mcp.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -27,6 +27,7 @@ dev = [
|
||||
[project.scripts]
|
||||
pai = "pai.cli:app"
|
||||
pai-gmail-mcp = "pai_mcp.gmail:main"
|
||||
pai-github-mcp = "pai_mcp.github:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
+68
-4
@@ -501,6 +501,9 @@ async def list_automations(
|
||||
@app.command("watch")
|
||||
@async_command
|
||||
async def watch_cmd(
|
||||
source: Annotated[
|
||||
str, typer.Argument(help="What to watch: 'email' or 'github'")
|
||||
] = "email",
|
||||
interval: Annotated[
|
||||
int, typer.Option("--interval", "-i", help="Seconds between polls")
|
||||
] = 60,
|
||||
@@ -510,14 +513,20 @@ async def watch_cmd(
|
||||
):
|
||||
"""Watch for trigger events and run automations.
|
||||
|
||||
Polls Gmail for new emails matching active automation triggers.
|
||||
Polls email or GitHub for events matching active automation triggers.
|
||||
Press Ctrl+C to stop.
|
||||
|
||||
Example:
|
||||
pai watch # Poll every 60 seconds
|
||||
pai watch --interval 30 # Poll every 30 seconds
|
||||
pai watch --once # Check once and exit
|
||||
pai watch # Watch emails (default)
|
||||
pai watch email # Watch emails explicitly
|
||||
pai watch github # Watch GitHub PR reviews
|
||||
pai watch github -i 120 # GitHub with 2min interval
|
||||
pai watch --once # Check once and exit
|
||||
"""
|
||||
if source == "github":
|
||||
await _watch_github(interval, once)
|
||||
return
|
||||
|
||||
from pai.watcher import EmailWatcher
|
||||
|
||||
console.print(Panel.fit(
|
||||
@@ -571,6 +580,61 @@ async def watch_cmd(
|
||||
console.print("[green]Watcher stopped.[/green]")
|
||||
|
||||
|
||||
async def _watch_github(interval: int, once: bool) -> None:
|
||||
"""Watch for GitHub PR reviews."""
|
||||
from pai.watcher import GitHubPRWatcher
|
||||
|
||||
# Default to 2 minutes for GitHub to avoid rate limits
|
||||
if interval == 60:
|
||||
interval = 120
|
||||
|
||||
console.print(Panel.fit(
|
||||
f"[bold]GitHub PR Review Watcher[/bold]\n\n"
|
||||
f"Polling interval: {interval}s\n"
|
||||
f"Mode: {'single check' if once else 'continuous'}\n\n"
|
||||
f"[dim]Watching for PR reviews on your pull requests.[/dim]",
|
||||
title="PAI GitHub Watcher",
|
||||
))
|
||||
|
||||
# Check for active automations
|
||||
db = get_db()
|
||||
await db.initialize()
|
||||
automations = await db.list_automations(status=AutomationStatus.ACTIVE)
|
||||
await db.close()
|
||||
|
||||
github_automations = [
|
||||
a for a in automations
|
||||
if (isinstance(a.trigger, dict) and a.trigger.get("type") == "github_pr")
|
||||
or (hasattr(a.trigger, "type") and a.trigger.type == "github_pr")
|
||||
]
|
||||
|
||||
if not github_automations:
|
||||
console.print("\n[yellow]Warning:[/yellow] No active automations with github_pr triggers.")
|
||||
console.print("[dim]Use 'pai intent \"when someone reviews my PR...\" --plan --save'[/dim]")
|
||||
if not once:
|
||||
console.print("[dim]Watcher will start anyway and check periodically...[/dim]\n")
|
||||
else:
|
||||
console.print(f"\n[green]Found {len(github_automations)} active GitHub automation(s)[/green]")
|
||||
for auto in github_automations:
|
||||
console.print(f" - [cyan]{auto.name}[/cyan]")
|
||||
console.print()
|
||||
|
||||
watcher = GitHubPRWatcher()
|
||||
|
||||
if once:
|
||||
console.print("[dim]Running single check...[/dim]\n")
|
||||
await watcher.start(interval=interval, max_iterations=1)
|
||||
console.print("\n[green]Check complete.[/green]")
|
||||
else:
|
||||
console.print(f"[dim]Starting watcher (Ctrl+C to stop)...[/dim]\n")
|
||||
try:
|
||||
await watcher.start(interval=interval)
|
||||
except KeyboardInterrupt:
|
||||
console.print("\n[yellow]Stopping watcher...[/yellow]")
|
||||
watcher.stop()
|
||||
console.print("[green]Watcher stopped.[/green]")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Query subgroup (emails, entities)
|
||||
# =============================================================================
|
||||
|
||||
+20
-7
@@ -523,11 +523,16 @@ class Database:
|
||||
# Watcher State
|
||||
# =========================================================================
|
||||
|
||||
async def get_watcher_state(self) -> dict[str, Any] | None:
|
||||
"""Get the watcher state."""
|
||||
async def get_watcher_state(self, watcher_type: str = "email") -> dict[str, Any] | None:
|
||||
"""Get the watcher state for a specific watcher type.
|
||||
|
||||
Args:
|
||||
watcher_type: Type of watcher ("email", "github", etc.)
|
||||
"""
|
||||
key = f"{watcher_type}_watcher"
|
||||
async with self.connection() as conn:
|
||||
cursor = await conn.execute(
|
||||
"SELECT value_json FROM watcher_state WHERE key = 'email_watcher'"
|
||||
"SELECT value_json FROM watcher_state WHERE key = ?", (key,)
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if not row:
|
||||
@@ -538,15 +543,23 @@ class Database:
|
||||
data["last_check"] = datetime.fromisoformat(data["last_check"])
|
||||
return data
|
||||
|
||||
async def save_watcher_state(self, state: dict[str, Any]) -> None:
|
||||
"""Save the watcher state."""
|
||||
async def save_watcher_state(
|
||||
self, state: dict[str, Any], watcher_type: str = "email"
|
||||
) -> None:
|
||||
"""Save the watcher state for a specific watcher type.
|
||||
|
||||
Args:
|
||||
state: State data to save.
|
||||
watcher_type: Type of watcher ("email", "github", etc.)
|
||||
"""
|
||||
key = f"{watcher_type}_watcher"
|
||||
async with self.connection() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO watcher_state (key, value_json, updated_at)
|
||||
VALUES ('email_watcher', ?, ?)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(json.dumps(state), datetime.now().isoformat()),
|
||||
(key, json.dumps(state), datetime.now().isoformat()),
|
||||
)
|
||||
await conn.commit()
|
||||
|
||||
|
||||
@@ -125,6 +125,10 @@ class MCPActionExecutor:
|
||||
classify_action = EmailClassifyAction.model_validate(action_data)
|
||||
return await self._execute_classify(classify_action, variables, dry_run)
|
||||
|
||||
# Route github.implement_review to specialized handler
|
||||
if action_type == "github.implement_review":
|
||||
return await self._execute_github_review(action_data, variables, dry_run)
|
||||
|
||||
# Get MCP mapping
|
||||
mcp_mapping = get_mcp_tool_for_action(action_type)
|
||||
if not mcp_mapping:
|
||||
@@ -369,6 +373,144 @@ class MCPActionExecutor:
|
||||
duration_ms=int((time.time() - start_time) * 1000),
|
||||
)
|
||||
|
||||
async def _execute_github_review(
|
||||
self,
|
||||
action_data: dict[str, Any],
|
||||
variables: dict[str, Any],
|
||||
dry_run: bool = False,
|
||||
) -> ActionResult:
|
||||
"""Execute GitHub review implementation action.
|
||||
|
||||
This action prepares context for Claude Code to implement PR review feedback.
|
||||
It uses the bash automation feature (when available) to launch Claude Code
|
||||
with the formatted prompt.
|
||||
|
||||
Until bash automation is implemented, this:
|
||||
1. Fetches PR review context via MCP
|
||||
2. Writes prompt to a file
|
||||
3. Returns instructions for the user to run Claude Code manually
|
||||
|
||||
Once bash automation is available, it will:
|
||||
1. Fetch PR review context via MCP
|
||||
2. Execute a bash script that launches Claude Code with the prompt
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
start_time = time.time()
|
||||
action_id = f"github_review_{uuid4().hex[:8]}"
|
||||
|
||||
# Get repo and PR number from action or trigger data
|
||||
repo = action_data.get("repo")
|
||||
pr_number = action_data.get("pr_number")
|
||||
|
||||
if not repo:
|
||||
repo = self._get_nested_value(variables, "trigger.repo")
|
||||
if not pr_number:
|
||||
pr_number = self._get_nested_value(variables, "trigger.pr_number")
|
||||
|
||||
if not repo or not pr_number:
|
||||
return ActionResult(
|
||||
action_id=action_id,
|
||||
status="failed",
|
||||
error="Missing repo or pr_number - provide in action or trigger data",
|
||||
duration_ms=int((time.time() - start_time) * 1000),
|
||||
)
|
||||
|
||||
# Get formatted prompt from trigger data (already set by watcher)
|
||||
prompt = self._get_nested_value(variables, "trigger.prompt")
|
||||
branch = self._get_nested_value(variables, "trigger.branch")
|
||||
|
||||
# If no prompt in trigger, fetch it via MCP
|
||||
if not prompt:
|
||||
format_result = await self._manager.call_tool(
|
||||
"github", "format_review_for_claude",
|
||||
{"repo": repo, "pr_number": pr_number},
|
||||
)
|
||||
if format_result.success and format_result.structured:
|
||||
prompt = format_result.structured.get("prompt", "")
|
||||
branch = format_result.structured.get("branch", "")
|
||||
|
||||
if not prompt:
|
||||
return ActionResult(
|
||||
action_id=action_id,
|
||||
status="failed",
|
||||
error="Failed to get PR review context",
|
||||
duration_ms=int((time.time() - start_time) * 1000),
|
||||
)
|
||||
|
||||
# Add any custom instructions
|
||||
additional = action_data.get("additional_instructions")
|
||||
if additional:
|
||||
prompt += f"\n\n## Additional Instructions\n{additional}"
|
||||
|
||||
# Write prompt to a task file
|
||||
config_dir = Path.home() / ".config" / "pai" / "pr-tasks"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
task_file = config_dir / f"{repo.replace('/', '_')}_{pr_number}.md"
|
||||
|
||||
if dry_run:
|
||||
return ActionResult(
|
||||
action_id=action_id,
|
||||
status="success",
|
||||
output={
|
||||
"dry_run": True,
|
||||
"repo": repo,
|
||||
"pr_number": pr_number,
|
||||
"branch": branch,
|
||||
"would_write_to": str(task_file),
|
||||
"prompt_preview": prompt[:500] + "..." if len(prompt) > 500 else prompt,
|
||||
},
|
||||
duration_ms=int((time.time() - start_time) * 1000),
|
||||
)
|
||||
|
||||
# Write the task file
|
||||
task_file.write_text(prompt)
|
||||
|
||||
# Try to find the local repo path
|
||||
local_repo = action_data.get("local_repo_path")
|
||||
if not local_repo:
|
||||
# Try common locations
|
||||
repo_name = repo.split("/")[-1]
|
||||
search_paths = [
|
||||
Path.home() / "Documents" / "Repos" / repo_name,
|
||||
Path.home() / "repos" / repo_name,
|
||||
Path.home() / "code" / repo_name,
|
||||
Path.home() / repo_name,
|
||||
Path.cwd() / repo_name,
|
||||
]
|
||||
for p in search_paths:
|
||||
if p.exists() and (p / ".git").exists():
|
||||
local_repo = str(p)
|
||||
break
|
||||
|
||||
# Build the Claude Code command
|
||||
# TODO: Once bash automation is implemented, this will use BashAction
|
||||
# to run a sandboxed script that:
|
||||
# 1. cd to local_repo
|
||||
# 2. git checkout branch
|
||||
# 3. claude --print "$(cat task_file)"
|
||||
claude_cmd = f"cd {local_repo} && git checkout {branch} && claude --print \"$(cat {task_file})\""
|
||||
|
||||
return ActionResult(
|
||||
action_id=action_id,
|
||||
status="success",
|
||||
output={
|
||||
"repo": repo,
|
||||
"pr_number": pr_number,
|
||||
"branch": branch,
|
||||
"task_file": str(task_file),
|
||||
"local_repo": local_repo,
|
||||
"claude_command": claude_cmd,
|
||||
"message": (
|
||||
f"PR review context saved to {task_file}.\n"
|
||||
f"To implement the changes, run:\n\n"
|
||||
f" {claude_cmd}\n\n"
|
||||
"Or manually: cd to repo, checkout branch, then run claude with the task file."
|
||||
),
|
||||
},
|
||||
duration_ms=int((time.time() - start_time) * 1000),
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Execution Engine
|
||||
|
||||
@@ -289,6 +289,12 @@ ACTION_TO_MCP_TOOL: dict[str, tuple[str, str]] = {
|
||||
"outlook.mark_read": ("outlook", "mark_email_read"),
|
||||
"outlook.list_events": ("outlook", "list_calendar_events"),
|
||||
"outlook.get_event": ("outlook", "get_calendar_event_details"),
|
||||
# GitHub actions -> github MCP server
|
||||
"github.list_prs": ("github", "list_my_prs"),
|
||||
"github.get_reviews": ("github", "get_pr_reviews"),
|
||||
"github.get_diff": ("github", "get_pr_diff"),
|
||||
"github.format_review": ("github", "format_review_for_claude"),
|
||||
"github.implement_review": ("github", "format_review_for_claude"), # Gets context for bash
|
||||
}
|
||||
|
||||
|
||||
|
||||
+66
-2
@@ -190,7 +190,36 @@ class ManualTrigger(BaseModel):
|
||||
type: Literal["manual"] = "manual"
|
||||
|
||||
|
||||
Trigger = EmailTrigger | ScheduleTrigger | WebhookTrigger | FileChangeTrigger | ManualTrigger
|
||||
class GitHubPRCondition(BaseModel):
|
||||
"""Condition for GitHub PR review trigger."""
|
||||
|
||||
field: Literal["repo", "author", "reviewer", "state", "title"]
|
||||
operator: Literal["equals", "contains", "matches"]
|
||||
value: str
|
||||
|
||||
|
||||
class GitHubPRTrigger(BaseModel):
|
||||
"""Trigger on GitHub PR review.
|
||||
|
||||
Watches for new reviews on PRs authored by the user.
|
||||
"""
|
||||
|
||||
type: Literal["github_pr"] = "github_pr"
|
||||
account: str # GitHub username
|
||||
conditions: list[GitHubPRCondition] = Field(default_factory=list)
|
||||
review_states: list[Literal["approved", "changes_requested", "commented"]] = Field(
|
||||
default_factory=lambda: ["approved", "changes_requested", "commented"]
|
||||
)
|
||||
|
||||
|
||||
Trigger = (
|
||||
EmailTrigger
|
||||
| ScheduleTrigger
|
||||
| WebhookTrigger
|
||||
| FileChangeTrigger
|
||||
| ManualTrigger
|
||||
| GitHubPRTrigger
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -277,7 +306,42 @@ class EmailClassifyAction(BaseModel):
|
||||
prompt: str | None = None # Optional custom classification prompt
|
||||
|
||||
|
||||
Action = FileAction | SpreadsheetAction | EmailAction | ExtractAction | EmailClassifyAction
|
||||
class GitHubReviewAction(BaseModel):
|
||||
"""Launch Claude Code to implement PR review feedback.
|
||||
|
||||
Formats the PR review context and opens a new terminal with Claude Code
|
||||
pre-loaded with a prompt to implement the reviewer's suggestions.
|
||||
|
||||
This action integrates with the bash automation feature (once implemented)
|
||||
to run a script that:
|
||||
1. Navigates to the repo directory
|
||||
2. Checks out the PR branch
|
||||
3. Launches Claude Code with the formatted prompt
|
||||
|
||||
Until bash automation is ready, this action writes the prompt to a file
|
||||
and notifies the user to run Claude Code manually.
|
||||
"""
|
||||
|
||||
type: Literal["github.implement_review"] = "github.implement_review"
|
||||
# PR context (resolved from trigger)
|
||||
repo: str | None = None # owner/repo format, e.g. "owner/repo"
|
||||
pr_number: int | None = None
|
||||
# Local repo path (will search common locations if not set)
|
||||
local_repo_path: str | None = None
|
||||
# Custom instructions to include in Claude Code prompt
|
||||
additional_instructions: str | None = None
|
||||
# Bash script ID (for bash automation integration)
|
||||
script_id: str | None = None
|
||||
|
||||
|
||||
Action = (
|
||||
FileAction
|
||||
| SpreadsheetAction
|
||||
| EmailAction
|
||||
| ExtractAction
|
||||
| EmailClassifyAction
|
||||
| GitHubReviewAction
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
|
||||
@@ -18,6 +18,8 @@ from pai.models import (
|
||||
AutomationStatus,
|
||||
EmailCondition,
|
||||
EmailTrigger,
|
||||
GitHubPRCondition,
|
||||
GitHubPRTrigger,
|
||||
TriggerEvent,
|
||||
)
|
||||
|
||||
@@ -541,3 +543,318 @@ async def watch_emails(interval: int = 60) -> None:
|
||||
except KeyboardInterrupt:
|
||||
print("\n[watcher] Stopping...")
|
||||
watcher.stop()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GitHub PR Watcher
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class GitHubPRWatcher:
|
||||
"""Watches for new PR reviews and triggers automations.
|
||||
|
||||
Polls GitHub via MCP for PRs authored by the user that have new reviews.
|
||||
|
||||
Usage:
|
||||
watcher = GitHubPRWatcher()
|
||||
await watcher.start(interval=120) # Poll every 2 minutes
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._mcp_manager = get_mcp_manager()
|
||||
self._engine = ExecutionEngine()
|
||||
self._running = False
|
||||
self._last_check: datetime | None = None
|
||||
self._processed_review_ids: set[str] = set()
|
||||
|
||||
async def start(
|
||||
self,
|
||||
interval: int = 120,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
"""Start watching for new PR reviews.
|
||||
|
||||
Args:
|
||||
interval: Seconds between polls.
|
||||
max_iterations: Stop after N iterations (None = run forever).
|
||||
"""
|
||||
self._running = True
|
||||
await self._load_state()
|
||||
|
||||
iteration = 0
|
||||
while self._running:
|
||||
if max_iterations and iteration >= max_iterations:
|
||||
break
|
||||
|
||||
try:
|
||||
await self._poll()
|
||||
except Exception as e:
|
||||
print(f"[github-watcher] Error during poll: {e}")
|
||||
|
||||
iteration += 1
|
||||
if self._running and (not max_iterations or iteration < max_iterations):
|
||||
await asyncio.sleep(interval)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the watcher."""
|
||||
self._running = False
|
||||
|
||||
async def _poll(self) -> None:
|
||||
"""Poll for new PR reviews and check against triggers."""
|
||||
db = get_db()
|
||||
await db.initialize()
|
||||
|
||||
try:
|
||||
# Get active automations with GitHub PR triggers
|
||||
automations = await db.list_automations(status=AutomationStatus.ACTIVE)
|
||||
github_automations = [
|
||||
a for a in automations
|
||||
if self._is_github_pr_trigger(a)
|
||||
]
|
||||
|
||||
if not github_automations:
|
||||
return
|
||||
|
||||
# Get PRs with reviews via MCP
|
||||
prs_with_reviews = await self._fetch_prs_with_reviews()
|
||||
|
||||
for pr_data in prs_with_reviews:
|
||||
# Check each review on this PR
|
||||
reviews = pr_data.get("reviews", [])
|
||||
for review in reviews:
|
||||
review_id = f"{pr_data['repo']}#{pr_data['number']}:{review.get('id', '')}"
|
||||
|
||||
# Skip if already processed
|
||||
if review_id in self._processed_review_ids:
|
||||
continue
|
||||
|
||||
# Check against each automation
|
||||
for automation in github_automations:
|
||||
trigger = self._get_github_pr_trigger(automation)
|
||||
if trigger and self._matches_pr_review(pr_data, review, trigger):
|
||||
await self._execute_automation(automation, pr_data, review)
|
||||
|
||||
self._processed_review_ids.add(review_id)
|
||||
|
||||
# Update state
|
||||
self._last_check = datetime.now()
|
||||
await self._save_state()
|
||||
|
||||
# Keep processed IDs bounded
|
||||
if len(self._processed_review_ids) > 1000:
|
||||
ids_list = list(self._processed_review_ids)
|
||||
self._processed_review_ids = set(ids_list[-500:])
|
||||
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
async def _fetch_prs_with_reviews(self) -> list[dict]:
|
||||
"""Fetch PRs authored by user that have reviews."""
|
||||
result = await self._mcp_manager.call_tool(
|
||||
"github",
|
||||
"list_prs_with_reviews",
|
||||
{"since_hours": 24},
|
||||
)
|
||||
|
||||
if not result.success:
|
||||
print(f"[github-watcher] Failed to fetch PRs: {result.error}")
|
||||
return []
|
||||
|
||||
prs = []
|
||||
if result.structured and isinstance(result.structured, dict):
|
||||
prs_data = result.structured.get("prs_with_reviews", [])
|
||||
# Fetch detailed reviews for each PR
|
||||
for pr in prs_data:
|
||||
detailed = await self._fetch_pr_reviews(pr["repo"], pr["number"])
|
||||
if detailed:
|
||||
prs.append(detailed)
|
||||
return prs
|
||||
|
||||
async def _fetch_pr_reviews(self, repo: str, pr_number: int) -> dict | None:
|
||||
"""Fetch detailed review data for a PR."""
|
||||
result = await self._mcp_manager.call_tool(
|
||||
"github",
|
||||
"get_pr_reviews",
|
||||
{"repo": repo, "pr_number": pr_number},
|
||||
)
|
||||
|
||||
if not result.success:
|
||||
return None
|
||||
|
||||
if result.structured and isinstance(result.structured, dict):
|
||||
return result.structured
|
||||
return None
|
||||
|
||||
def _is_github_pr_trigger(self, automation: Automation) -> bool:
|
||||
"""Check if automation has a GitHub PR trigger."""
|
||||
trigger = automation.trigger
|
||||
if isinstance(trigger, GitHubPRTrigger):
|
||||
return True
|
||||
if isinstance(trigger, dict):
|
||||
return trigger.get("type") == "github_pr"
|
||||
return False
|
||||
|
||||
def _get_github_pr_trigger(self, automation: Automation) -> GitHubPRTrigger | None:
|
||||
"""Get the GitHub PR trigger from an automation."""
|
||||
trigger = automation.trigger
|
||||
if isinstance(trigger, GitHubPRTrigger):
|
||||
return trigger
|
||||
if isinstance(trigger, dict) and trigger.get("type") == "github_pr":
|
||||
conditions = []
|
||||
for cond in trigger.get("conditions", []):
|
||||
conditions.append(GitHubPRCondition(
|
||||
field=cond.get("field", "repo"),
|
||||
operator=cond.get("operator", "contains"),
|
||||
value=cond.get("value", ""),
|
||||
))
|
||||
return GitHubPRTrigger(
|
||||
account=trigger.get("account", ""),
|
||||
conditions=conditions,
|
||||
review_states=trigger.get("review_states", ["approved", "changes_requested", "commented"]),
|
||||
)
|
||||
return None
|
||||
|
||||
def _matches_pr_review(
|
||||
self, pr_data: dict, review: dict, trigger: GitHubPRTrigger
|
||||
) -> bool:
|
||||
"""Check if a PR review matches the trigger conditions."""
|
||||
# Check review state
|
||||
review_state = review.get("state", "").lower()
|
||||
if review_state not in [s.lower() for s in trigger.review_states]:
|
||||
return False
|
||||
|
||||
# Check conditions
|
||||
for condition in trigger.conditions:
|
||||
if not self._check_pr_condition(pr_data, review, condition):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _check_pr_condition(
|
||||
self, pr_data: dict, review: dict, condition: GitHubPRCondition
|
||||
) -> bool:
|
||||
"""Check a single condition against PR/review data."""
|
||||
# Get field value
|
||||
if condition.field == "repo":
|
||||
value = pr_data.get("repo", "")
|
||||
elif condition.field == "author":
|
||||
value = pr_data.get("pr", {}).get("author", {}).get("login", "")
|
||||
elif condition.field == "reviewer":
|
||||
value = review.get("author", "")
|
||||
elif condition.field == "state":
|
||||
value = review.get("state", "")
|
||||
elif condition.field == "title":
|
||||
value = pr_data.get("pr", {}).get("title", "")
|
||||
else:
|
||||
return False
|
||||
|
||||
# Apply operator
|
||||
value_lower = value.lower()
|
||||
pattern_lower = condition.value.lower()
|
||||
|
||||
if condition.operator == "equals":
|
||||
return value_lower == pattern_lower
|
||||
elif condition.operator == "contains":
|
||||
return pattern_lower in value_lower
|
||||
elif condition.operator == "matches":
|
||||
try:
|
||||
return bool(re.search(condition.value, value, re.IGNORECASE))
|
||||
except re.error:
|
||||
return False
|
||||
return False
|
||||
|
||||
async def _execute_automation(
|
||||
self, automation: Automation, pr_data: dict, review: dict
|
||||
) -> None:
|
||||
"""Execute an automation triggered by a PR review."""
|
||||
pr = pr_data.get("pr", {})
|
||||
repo = pr_data.get("repo", "")
|
||||
pr_number = pr.get("number", 0)
|
||||
|
||||
print(f"[github-watcher] Triggering '{automation.name}' for PR #{pr_number} review by @{review.get('author')}")
|
||||
|
||||
# Format the review for Claude Code
|
||||
formatted = await self._format_for_claude(repo, pr_number)
|
||||
|
||||
# Build trigger event
|
||||
trigger_event = TriggerEvent(
|
||||
type="github_pr",
|
||||
data={
|
||||
"repo": repo,
|
||||
"pr_number": pr_number,
|
||||
"branch": pr.get("headRefName", ""),
|
||||
"title": pr.get("title", ""),
|
||||
"review": {
|
||||
"author": review.get("author"),
|
||||
"state": review.get("state"),
|
||||
"body": review.get("body"),
|
||||
},
|
||||
"reviews": pr_data.get("reviews", []),
|
||||
"comments": pr_data.get("comments", []),
|
||||
"prompt": formatted.get("prompt", ""),
|
||||
"files_changed": formatted.get("files_changed", []),
|
||||
},
|
||||
)
|
||||
|
||||
# Execute the automation
|
||||
execution = await self._engine.run(automation, trigger_event, dry_run=False)
|
||||
|
||||
if execution.status.value == "success":
|
||||
print(f"[github-watcher] Automation '{automation.name}' completed")
|
||||
else:
|
||||
print(f"[github-watcher] Automation '{automation.name}' failed: {execution.error}")
|
||||
|
||||
async def _format_for_claude(self, repo: str, pr_number: int) -> dict:
|
||||
"""Get formatted PR data for Claude Code."""
|
||||
result = await self._mcp_manager.call_tool(
|
||||
"github",
|
||||
"format_review_for_claude",
|
||||
{"repo": repo, "pr_number": pr_number},
|
||||
)
|
||||
|
||||
if result.success and result.structured:
|
||||
return result.structured
|
||||
return {"prompt": "", "files_changed": []}
|
||||
|
||||
async def _load_state(self) -> None:
|
||||
"""Load watcher state from database."""
|
||||
db = get_db()
|
||||
await db.initialize()
|
||||
|
||||
try:
|
||||
state = await db.get_watcher_state("github")
|
||||
if state:
|
||||
self._last_check = state.get("last_check")
|
||||
self._processed_review_ids = set(state.get("processed_review_ids", []))
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
async def _save_state(self) -> None:
|
||||
"""Save watcher state to database."""
|
||||
db = get_db()
|
||||
await db.initialize()
|
||||
|
||||
try:
|
||||
await db.save_watcher_state({
|
||||
"last_check": self._last_check.isoformat() if self._last_check else None,
|
||||
"processed_review_ids": list(self._processed_review_ids)[-500:],
|
||||
}, "github")
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
|
||||
async def watch_github_prs(interval: int = 120) -> None:
|
||||
"""Start watching for GitHub PR reviews that trigger automations.
|
||||
|
||||
Args:
|
||||
interval: Seconds between polls (default 2 minutes).
|
||||
"""
|
||||
watcher = GitHubPRWatcher()
|
||||
print(f"[github-watcher] Starting PR review watcher (polling every {interval}s)")
|
||||
print("[github-watcher] Press Ctrl+C to stop")
|
||||
|
||||
try:
|
||||
await watcher.start(interval=interval)
|
||||
except KeyboardInterrupt:
|
||||
print("\n[github-watcher] Stopping...")
|
||||
watcher.stop()
|
||||
|
||||
@@ -16,6 +16,8 @@ from pai.models import (
|
||||
EmailTrigger,
|
||||
EmailCondition,
|
||||
ExecutionStatus,
|
||||
GitHubPRTrigger,
|
||||
GitHubReviewAction,
|
||||
ManualTrigger,
|
||||
TriggerEvent,
|
||||
)
|
||||
@@ -350,3 +352,190 @@ class TestActionResult:
|
||||
duration_ms=150,
|
||||
)
|
||||
assert result.duration_ms == 150
|
||||
|
||||
|
||||
class TestGitHubReviewExecution:
|
||||
"""Tests for GitHub review implementation action."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_mcp_manager(self):
|
||||
"""Create a mock MCP manager with github configured."""
|
||||
manager = MagicMock()
|
||||
manager.get_server_config.return_value = {"command": "uv", "args": ["run", "pai-github-mcp"]}
|
||||
return manager
|
||||
|
||||
@pytest.fixture
|
||||
def executor(self, mock_mcp_manager):
|
||||
"""Create an executor instance with mocked MCP manager."""
|
||||
with patch("pai.executor.get_mcp_manager", return_value=mock_mcp_manager):
|
||||
return MCPActionExecutor()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dry_run_github_review_action(self, executor):
|
||||
"""Test dry run of github.implement_review action."""
|
||||
action_data = {
|
||||
"type": "github.implement_review",
|
||||
"repo": "owner/test-repo",
|
||||
"pr_number": 123,
|
||||
}
|
||||
|
||||
variables = {
|
||||
"trigger": {
|
||||
"repo": "owner/test-repo",
|
||||
"pr_number": 123,
|
||||
"branch": "feature-branch",
|
||||
"prompt": "# Review\n\nPlease fix the bug.",
|
||||
}
|
||||
}
|
||||
|
||||
result = await executor._execute_github_review(action_data, variables, dry_run=True)
|
||||
|
||||
assert result.status == "success"
|
||||
assert result.output["dry_run"] is True
|
||||
assert result.output["repo"] == "owner/test-repo"
|
||||
assert result.output["pr_number"] == 123
|
||||
assert result.output["branch"] == "feature-branch"
|
||||
assert "would_write_to" in result.output
|
||||
assert "owner_test-repo_123.md" in result.output["would_write_to"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_github_review_uses_trigger_data(self, executor):
|
||||
"""Test that action uses trigger data when not specified."""
|
||||
action_data = {
|
||||
"type": "github.implement_review",
|
||||
# repo and pr_number not specified - should come from trigger
|
||||
}
|
||||
|
||||
variables = {
|
||||
"trigger": {
|
||||
"repo": "from/trigger",
|
||||
"pr_number": 456,
|
||||
"branch": "pr-branch",
|
||||
"prompt": "# Fix this\n\nDetails here.",
|
||||
}
|
||||
}
|
||||
|
||||
result = await executor._execute_github_review(action_data, variables, dry_run=True)
|
||||
|
||||
assert result.status == "success"
|
||||
assert result.output["repo"] == "from/trigger"
|
||||
assert result.output["pr_number"] == 456
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_github_review_fails_without_repo(self, executor):
|
||||
"""Test that action fails when repo is missing."""
|
||||
action_data = {
|
||||
"type": "github.implement_review",
|
||||
}
|
||||
|
||||
variables = {} # No trigger data
|
||||
|
||||
result = await executor._execute_github_review(action_data, variables, dry_run=True)
|
||||
|
||||
assert result.status == "failed"
|
||||
assert "Missing repo or pr_number" in result.error
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_github_review_includes_additional_instructions(self, executor):
|
||||
"""Test that additional instructions are included in output."""
|
||||
action_data = {
|
||||
"type": "github.implement_review",
|
||||
"repo": "owner/repo",
|
||||
"pr_number": 1,
|
||||
"additional_instructions": "Run tests before committing",
|
||||
}
|
||||
|
||||
variables = {
|
||||
"trigger": {
|
||||
"prompt": "# Review\n\nFix the issue.",
|
||||
"branch": "main",
|
||||
}
|
||||
}
|
||||
|
||||
result = await executor._execute_github_review(action_data, variables, dry_run=True)
|
||||
|
||||
assert result.status == "success"
|
||||
# Additional instructions should be in the prompt preview
|
||||
assert "Run tests before committing" in result.output["prompt_preview"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_github_review_action_routing(self, executor):
|
||||
"""Test that github.implement_review routes to specialized handler."""
|
||||
action = {
|
||||
"type": "github.implement_review",
|
||||
"repo": "test/repo",
|
||||
"pr_number": 99,
|
||||
}
|
||||
|
||||
variables = {
|
||||
"trigger": {
|
||||
"prompt": "Test prompt",
|
||||
"branch": "test-branch",
|
||||
}
|
||||
}
|
||||
|
||||
# Execute through the main execute method
|
||||
result = await executor.execute(action, variables, dry_run=True)
|
||||
|
||||
# Should have been handled by _execute_github_review
|
||||
assert result.status == "success"
|
||||
assert result.output["repo"] == "test/repo"
|
||||
assert result.output["pr_number"] == 99
|
||||
|
||||
|
||||
class TestGitHubAutomationExecution:
|
||||
"""Tests for full automation execution with GitHub triggers."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_mcp_manager(self):
|
||||
"""Create a mock MCP manager with github configured."""
|
||||
manager = MagicMock()
|
||||
manager.get_server_config.return_value = {"command": "uv", "args": ["run", "pai-github-mcp"]}
|
||||
return manager
|
||||
|
||||
@pytest.fixture
|
||||
def engine(self, mock_mcp_manager):
|
||||
"""Create an engine instance with mocked MCP manager."""
|
||||
with patch("pai.executor.get_mcp_manager", return_value=mock_mcp_manager):
|
||||
return ExecutionEngine()
|
||||
|
||||
@pytest.fixture
|
||||
def github_automation(self):
|
||||
"""Create a sample automation with GitHub trigger."""
|
||||
return Automation(
|
||||
id="test_github_001",
|
||||
name="Implement Reviews",
|
||||
description="Implement PR review feedback",
|
||||
status=AutomationStatus.ACTIVE,
|
||||
trigger=GitHubPRTrigger(account="testuser"),
|
||||
actions=[
|
||||
GitHubReviewAction(
|
||||
additional_instructions="Focus on the main issues",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execution_with_github_trigger(self, engine, github_automation):
|
||||
"""Test execution with GitHub trigger event data."""
|
||||
trigger_event = TriggerEvent(
|
||||
type="github_pr",
|
||||
data={
|
||||
"repo": "testuser/my-project",
|
||||
"pr_number": 42,
|
||||
"branch": "feature-xyz",
|
||||
"prompt": "# Review Feedback\n\nPlease address the comments.",
|
||||
"review": {
|
||||
"author": "reviewer",
|
||||
"state": "changes_requested",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
execution = await engine.run(github_automation, trigger_event, dry_run=True)
|
||||
|
||||
assert execution.status == ExecutionStatus.SUCCESS
|
||||
assert len(execution.action_results) == 1
|
||||
assert execution.action_results[0].output["dry_run"] is True
|
||||
assert execution.action_results[0].output["repo"] == "testuser/my-project"
|
||||
assert execution.action_results[0].output["pr_number"] == 42
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Tests for the GitHub MCP server."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from pai_mcp.github import (
|
||||
_run_gh,
|
||||
_get_current_user,
|
||||
list_my_prs,
|
||||
list_prs_with_reviews,
|
||||
get_pr_reviews,
|
||||
get_pr_diff,
|
||||
format_review_for_claude,
|
||||
)
|
||||
|
||||
|
||||
class TestGhCLIWrapper:
|
||||
"""Tests for gh CLI wrapper functions."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_gh_success(self):
|
||||
"""Test successful gh command execution."""
|
||||
with patch("asyncio.create_subprocess_exec") as mock_exec:
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.returncode = 0
|
||||
mock_proc.communicate.return_value = (
|
||||
b'[{"number": 1, "title": "Test PR"}]',
|
||||
b"",
|
||||
)
|
||||
mock_exec.return_value = mock_proc
|
||||
|
||||
result = await _run_gh("pr", "list", "--json", "number,title")
|
||||
|
||||
assert result == [{"number": 1, "title": "Test PR"}]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_gh_error(self):
|
||||
"""Test gh command error handling."""
|
||||
with patch("asyncio.create_subprocess_exec") as mock_exec:
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.returncode = 1
|
||||
mock_proc.communicate.return_value = (b"", b"Error: not authenticated")
|
||||
mock_exec.return_value = mock_proc
|
||||
|
||||
result = await _run_gh("pr", "list")
|
||||
|
||||
assert "error" in result
|
||||
assert "not authenticated" in result["error"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_gh_non_json_output(self):
|
||||
"""Test handling of non-JSON output (like diffs)."""
|
||||
with patch("asyncio.create_subprocess_exec") as mock_exec:
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.returncode = 0
|
||||
mock_proc.communicate.return_value = (b"diff --git a/file.py b/file.py", b"")
|
||||
mock_exec.return_value = mock_proc
|
||||
|
||||
result = await _run_gh("pr", "diff", "1")
|
||||
|
||||
assert "raw" in result
|
||||
assert "diff --git" in result["raw"]
|
||||
|
||||
def test_get_current_user_success(self):
|
||||
"""Test getting current authenticated user."""
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout="testuser\n")
|
||||
|
||||
result = _get_current_user()
|
||||
|
||||
assert result == "testuser"
|
||||
|
||||
def test_get_current_user_not_authenticated(self):
|
||||
"""Test handling when not authenticated."""
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=1, stdout="")
|
||||
|
||||
result = _get_current_user()
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestListMyPRs:
|
||||
"""Tests for list_my_prs tool."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_my_prs_success(self):
|
||||
"""Test listing PRs authored by user."""
|
||||
with patch("pai_mcp.github._get_current_user", return_value="testuser"), \
|
||||
patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
mock_gh.return_value = [
|
||||
{"number": 1, "title": "Fix bug", "url": "https://github.com/org/repo/pull/1"},
|
||||
{"number": 2, "title": "Add feature", "url": "https://github.com/org/repo/pull/2"},
|
||||
]
|
||||
|
||||
result = await list_my_prs("open")
|
||||
|
||||
assert result["user"] == "testuser"
|
||||
assert result["state"] == "open"
|
||||
assert len(result["prs"]) == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_my_prs_not_authenticated(self):
|
||||
"""Test error when not authenticated."""
|
||||
with patch("pai_mcp.github._get_current_user", return_value=None):
|
||||
result = await list_my_prs()
|
||||
|
||||
assert "error" in result
|
||||
assert "Not authenticated" in result["error"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_my_prs_empty(self):
|
||||
"""Test when user has no PRs."""
|
||||
with patch("pai_mcp.github._get_current_user", return_value="testuser"), \
|
||||
patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
mock_gh.return_value = []
|
||||
|
||||
result = await list_my_prs()
|
||||
|
||||
assert result["prs"] == []
|
||||
|
||||
|
||||
class TestListPRsWithReviews:
|
||||
"""Tests for list_prs_with_reviews tool."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_prs_with_reviews(self):
|
||||
"""Test listing PRs that have reviews."""
|
||||
with patch("pai_mcp.github._get_current_user", return_value="testuser"), \
|
||||
patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
mock_gh.return_value = [
|
||||
{
|
||||
"number": 1,
|
||||
"title": "PR with review",
|
||||
"url": "https://github.com/org/repo/pull/1",
|
||||
"headRepository": {"nameWithOwner": "org/repo"},
|
||||
"headRefName": "feature-branch",
|
||||
"reviews": [{"state": "CHANGES_REQUESTED"}],
|
||||
},
|
||||
]
|
||||
|
||||
result = await list_prs_with_reviews(24)
|
||||
|
||||
assert result["user"] == "testuser"
|
||||
assert len(result["prs_with_reviews"]) == 1
|
||||
assert result["prs_with_reviews"][0]["repo"] == "org/repo"
|
||||
assert result["prs_with_reviews"][0]["review_count"] == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_prs_with_reviews_filters_no_reviews(self):
|
||||
"""Test that PRs without reviews are filtered out."""
|
||||
with patch("pai_mcp.github._get_current_user", return_value="testuser"), \
|
||||
patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
mock_gh.return_value = [
|
||||
{
|
||||
"number": 1,
|
||||
"title": "PR without review",
|
||||
"url": "https://github.com/org/repo/pull/1",
|
||||
"headRepository": {"nameWithOwner": "org/repo"},
|
||||
"headRefName": "branch",
|
||||
"reviews": [], # No reviews
|
||||
},
|
||||
]
|
||||
|
||||
result = await list_prs_with_reviews()
|
||||
|
||||
assert result["prs_with_reviews"] == []
|
||||
|
||||
|
||||
class TestGetPRReviews:
|
||||
"""Tests for get_pr_reviews tool."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_pr_reviews_success(self):
|
||||
"""Test getting reviews for a PR."""
|
||||
with patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
# First call: PR details
|
||||
# Second call: reviews
|
||||
# Third call: comments
|
||||
mock_gh.side_effect = [
|
||||
{"number": 1, "title": "Test PR", "author": {"login": "testuser"}},
|
||||
[{"id": 123, "user": {"login": "reviewer"}, "state": "CHANGES_REQUESTED", "body": "Fix this"}],
|
||||
[{"id": 456, "user": {"login": "reviewer"}, "path": "file.py", "line": 10, "body": "Typo here"}],
|
||||
]
|
||||
|
||||
result = await get_pr_reviews("org/repo", 1)
|
||||
|
||||
assert result["repo"] == "org/repo"
|
||||
assert result["pr"]["title"] == "Test PR"
|
||||
assert len(result["reviews"]) == 1
|
||||
assert result["reviews"][0]["state"] == "CHANGES_REQUESTED"
|
||||
assert len(result["comments"]) == 1
|
||||
assert result["comments"][0]["path"] == "file.py"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_pr_reviews_pr_not_found(self):
|
||||
"""Test error when PR not found."""
|
||||
with patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
mock_gh.return_value = {"error": "Could not resolve PR", "returncode": 1}
|
||||
|
||||
result = await get_pr_reviews("org/repo", 999)
|
||||
|
||||
assert "error" in result
|
||||
|
||||
|
||||
class TestGetPRDiff:
|
||||
"""Tests for get_pr_diff tool."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_pr_diff_success(self):
|
||||
"""Test getting diff for a PR."""
|
||||
with patch("pai_mcp.github._run_gh", new_callable=AsyncMock) as mock_gh:
|
||||
mock_gh.side_effect = [
|
||||
{"raw": "diff --git a/file.py b/file.py\n+new line"},
|
||||
{"files": [{"path": "file.py", "additions": 1, "deletions": 0}]},
|
||||
]
|
||||
|
||||
result = await get_pr_diff("org/repo", 1)
|
||||
|
||||
assert result["repo"] == "org/repo"
|
||||
assert result["pr_number"] == 1
|
||||
assert "diff --git" in result["diff"]
|
||||
assert len(result["files"]) == 1
|
||||
|
||||
|
||||
class TestFormatReviewForClaude:
|
||||
"""Tests for format_review_for_claude tool."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_format_review_for_claude(self):
|
||||
"""Test formatting PR review for Claude Code."""
|
||||
with patch("pai_mcp.github.get_pr_reviews", new_callable=AsyncMock) as mock_reviews, \
|
||||
patch("pai_mcp.github.get_pr_diff", new_callable=AsyncMock) as mock_diff:
|
||||
mock_reviews.return_value = {
|
||||
"repo": "org/repo",
|
||||
"pr": {
|
||||
"number": 1,
|
||||
"title": "Fix authentication",
|
||||
"headRefName": "fix-auth",
|
||||
"baseRefName": "main",
|
||||
"additions": 50,
|
||||
"deletions": 10,
|
||||
"changedFiles": 3,
|
||||
"files": [{"path": "auth.py"}],
|
||||
},
|
||||
"reviews": [
|
||||
{"author": "reviewer", "state": "CHANGES_REQUESTED", "body": "Please add tests"},
|
||||
],
|
||||
"comments": [
|
||||
{"author": "reviewer", "path": "auth.py", "line": 42, "body": "This could be simplified"},
|
||||
],
|
||||
}
|
||||
mock_diff.return_value = {"diff": "...", "files": []}
|
||||
|
||||
result = await format_review_for_claude("org/repo", 1)
|
||||
|
||||
assert result["repo"] == "org/repo"
|
||||
assert result["pr_number"] == 1
|
||||
assert result["branch"] == "fix-auth"
|
||||
assert "prompt" in result
|
||||
assert "Fix authentication" in result["prompt"]
|
||||
assert "@reviewer" in result["prompt"]
|
||||
assert "Please add tests" in result["prompt"]
|
||||
assert "auth.py" in result["prompt"]
|
||||
assert "Line 42" in result["prompt"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_format_review_handles_error(self):
|
||||
"""Test error handling when fetching review fails."""
|
||||
with patch("pai_mcp.github.get_pr_reviews", new_callable=AsyncMock) as mock_reviews:
|
||||
mock_reviews.return_value = {"error": "PR not found"}
|
||||
|
||||
result = await format_review_for_claude("org/repo", 999)
|
||||
|
||||
assert "error" in result
|
||||
@@ -8,6 +8,9 @@ from pai.models import (
|
||||
Entity,
|
||||
EntityType,
|
||||
FileAction,
|
||||
GitHubPRCondition,
|
||||
GitHubPRTrigger,
|
||||
GitHubReviewAction,
|
||||
IntentGraph,
|
||||
)
|
||||
|
||||
@@ -70,3 +73,90 @@ def test_intent_graph():
|
||||
)
|
||||
assert intent.type == "automation"
|
||||
assert intent.confidence == 0.85
|
||||
|
||||
|
||||
def test_github_pr_trigger():
|
||||
"""Test GitHubPRTrigger model."""
|
||||
trigger = GitHubPRTrigger(
|
||||
account="testuser",
|
||||
conditions=[
|
||||
GitHubPRCondition(
|
||||
field="repo",
|
||||
operator="contains",
|
||||
value="my-project",
|
||||
)
|
||||
],
|
||||
review_states=["changes_requested", "commented"],
|
||||
)
|
||||
assert trigger.type == "github_pr"
|
||||
assert len(trigger.conditions) == 1
|
||||
assert trigger.conditions[0].field == "repo"
|
||||
assert "changes_requested" in trigger.review_states
|
||||
|
||||
|
||||
def test_github_pr_trigger_defaults():
|
||||
"""Test GitHubPRTrigger default values."""
|
||||
trigger = GitHubPRTrigger(account="testuser")
|
||||
assert trigger.type == "github_pr"
|
||||
assert trigger.conditions == []
|
||||
assert "approved" in trigger.review_states
|
||||
assert "changes_requested" in trigger.review_states
|
||||
assert "commented" in trigger.review_states
|
||||
|
||||
|
||||
def test_github_pr_condition():
|
||||
"""Test GitHubPRCondition model."""
|
||||
condition = GitHubPRCondition(
|
||||
field="reviewer",
|
||||
operator="equals",
|
||||
value="senior-dev",
|
||||
)
|
||||
assert condition.field == "reviewer"
|
||||
assert condition.operator == "equals"
|
||||
assert condition.value == "senior-dev"
|
||||
|
||||
|
||||
def test_github_review_action():
|
||||
"""Test GitHubReviewAction model."""
|
||||
action = GitHubReviewAction(
|
||||
repo="owner/repo",
|
||||
pr_number=42,
|
||||
local_repo_path="/home/user/projects/repo",
|
||||
additional_instructions="Focus on security fixes",
|
||||
)
|
||||
assert action.type == "github.implement_review"
|
||||
assert action.repo == "owner/repo"
|
||||
assert action.pr_number == 42
|
||||
assert action.additional_instructions == "Focus on security fixes"
|
||||
|
||||
|
||||
def test_github_review_action_defaults():
|
||||
"""Test GitHubReviewAction default values."""
|
||||
action = GitHubReviewAction()
|
||||
assert action.type == "github.implement_review"
|
||||
assert action.repo is None
|
||||
assert action.pr_number is None
|
||||
assert action.script_id is None
|
||||
|
||||
|
||||
def test_automation_with_github_trigger():
|
||||
"""Test Automation with GitHubPRTrigger."""
|
||||
auto = Automation(
|
||||
id="auto_gh_001",
|
||||
name="Implement PR Reviews",
|
||||
description="Automatically implement PR review feedback",
|
||||
trigger=GitHubPRTrigger(
|
||||
account="myuser",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="my-project"),
|
||||
],
|
||||
),
|
||||
actions=[
|
||||
GitHubReviewAction(
|
||||
additional_instructions="Run tests after changes",
|
||||
)
|
||||
],
|
||||
)
|
||||
assert auto.trigger.type == "github_pr"
|
||||
assert len(auto.actions) == 1
|
||||
assert auto.actions[0].type == "github.implement_review"
|
||||
|
||||
+412
-1
@@ -12,8 +12,11 @@ from pai.models import (
|
||||
EmailAction,
|
||||
EmailCondition,
|
||||
EmailTrigger,
|
||||
GitHubPRCondition,
|
||||
GitHubPRTrigger,
|
||||
GitHubReviewAction,
|
||||
)
|
||||
from pai.watcher import EmailWatcher, TriggerMatcher
|
||||
from pai.watcher import EmailWatcher, GitHubPRWatcher, TriggerMatcher
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -471,3 +474,411 @@ class TestWatcherIntegration:
|
||||
|
||||
# But email should still be marked as processed
|
||||
assert watcher_email.id in watcher._processed_ids
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GitHub PR Watcher Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_github_automation():
|
||||
"""Create a sample automation with GitHub PR trigger."""
|
||||
return Automation(
|
||||
id="auto_gh_123",
|
||||
name="Implement PR Reviews",
|
||||
description="Implement PR review feedback with Claude Code",
|
||||
status=AutomationStatus.ACTIVE,
|
||||
trigger=GitHubPRTrigger(
|
||||
account="testuser",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="my-project"),
|
||||
],
|
||||
review_states=["changes_requested", "commented"],
|
||||
),
|
||||
actions=[
|
||||
GitHubReviewAction(
|
||||
additional_instructions="Run tests after changes",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_pr_data():
|
||||
"""Create sample PR data as returned by MCP.
|
||||
|
||||
Note: The watcher expects 'number' and 'repo' at the top level,
|
||||
with 'pr' containing detailed PR info from get_pr_reviews.
|
||||
"""
|
||||
return {
|
||||
"repo": "testuser/my-project",
|
||||
"number": 42, # PR number at top level for review ID tracking
|
||||
"pr": {
|
||||
"number": 42,
|
||||
"title": "Add new feature",
|
||||
"author": {"login": "testuser"},
|
||||
"headRefName": "feature-branch",
|
||||
"baseRefName": "main",
|
||||
"additions": 100,
|
||||
"deletions": 20,
|
||||
"changedFiles": 5,
|
||||
},
|
||||
"reviews": [
|
||||
{
|
||||
"id": 12345,
|
||||
"author": "reviewer1",
|
||||
"state": "CHANGES_REQUESTED",
|
||||
"body": "Please fix the typo on line 42",
|
||||
}
|
||||
],
|
||||
"comments": [
|
||||
{
|
||||
"id": 67890,
|
||||
"author": "reviewer1",
|
||||
"path": "src/main.py",
|
||||
"line": 42,
|
||||
"body": "Typo here: 'teh' should be 'the'",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class TestGitHubPRWatcher:
|
||||
"""Tests for GitHubPRWatcher."""
|
||||
|
||||
def test_is_github_pr_trigger_with_trigger_object(self, sample_github_automation):
|
||||
"""Test _is_github_pr_trigger with GitHubPRTrigger object."""
|
||||
watcher = GitHubPRWatcher()
|
||||
assert watcher._is_github_pr_trigger(sample_github_automation) is True
|
||||
|
||||
def test_is_github_pr_trigger_with_dict_trigger(self):
|
||||
"""Test _is_github_pr_trigger with dict trigger."""
|
||||
watcher = GitHubPRWatcher()
|
||||
automation = Automation(
|
||||
id="auto_1",
|
||||
name="Test",
|
||||
trigger={"type": "github_pr", "account": "test", "conditions": []},
|
||||
actions=[],
|
||||
)
|
||||
assert watcher._is_github_pr_trigger(automation) is True
|
||||
|
||||
def test_is_github_pr_trigger_with_non_github_trigger(self):
|
||||
"""Test _is_github_pr_trigger with non-GitHub trigger."""
|
||||
watcher = GitHubPRWatcher()
|
||||
automation = Automation(
|
||||
id="auto_1",
|
||||
name="Test",
|
||||
trigger={"type": "email", "account": "test@example.com", "conditions": []},
|
||||
actions=[],
|
||||
)
|
||||
assert watcher._is_github_pr_trigger(automation) is False
|
||||
|
||||
def test_get_github_pr_trigger_from_object(self, sample_github_automation):
|
||||
"""Test _get_github_pr_trigger with GitHubPRTrigger object."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = watcher._get_github_pr_trigger(sample_github_automation)
|
||||
|
||||
assert trigger is not None
|
||||
assert isinstance(trigger, GitHubPRTrigger)
|
||||
assert len(trigger.conditions) == 1
|
||||
assert trigger.conditions[0].value == "my-project"
|
||||
assert "changes_requested" in trigger.review_states
|
||||
|
||||
def test_get_github_pr_trigger_from_dict(self):
|
||||
"""Test _get_github_pr_trigger with dict trigger."""
|
||||
watcher = GitHubPRWatcher()
|
||||
automation = Automation(
|
||||
id="auto_1",
|
||||
name="Test",
|
||||
trigger={
|
||||
"type": "github_pr",
|
||||
"account": "testuser",
|
||||
"conditions": [
|
||||
{"field": "repo", "operator": "contains", "value": "project"}
|
||||
],
|
||||
"review_states": ["approved"],
|
||||
},
|
||||
actions=[],
|
||||
)
|
||||
|
||||
trigger = watcher._get_github_pr_trigger(automation)
|
||||
|
||||
assert trigger is not None
|
||||
assert isinstance(trigger, GitHubPRTrigger)
|
||||
assert trigger.account == "testuser"
|
||||
assert len(trigger.conditions) == 1
|
||||
assert trigger.conditions[0].field == "repo"
|
||||
assert trigger.review_states == ["approved"]
|
||||
|
||||
def test_get_github_pr_trigger_returns_none_for_non_github(self):
|
||||
"""Test _get_github_pr_trigger returns None for non-GitHub triggers."""
|
||||
watcher = GitHubPRWatcher()
|
||||
automation = Automation(
|
||||
id="auto_1",
|
||||
name="Test",
|
||||
trigger={"type": "email", "account": "test@example.com"},
|
||||
actions=[],
|
||||
)
|
||||
|
||||
assert watcher._get_github_pr_trigger(automation) is None
|
||||
|
||||
|
||||
class TestGitHubPRTriggerMatching:
|
||||
"""Tests for GitHub PR trigger matching."""
|
||||
|
||||
def test_matches_pr_review_changes_requested(self, sample_github_automation, sample_pr_data):
|
||||
"""Test matching a PR with changes_requested review."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = watcher._get_github_pr_trigger(sample_github_automation)
|
||||
review = sample_pr_data["reviews"][0]
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is True
|
||||
|
||||
def test_matches_pr_review_wrong_state(self, sample_github_automation, sample_pr_data):
|
||||
"""Test that review with wrong state doesn't match."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = watcher._get_github_pr_trigger(sample_github_automation)
|
||||
review = {"state": "APPROVED", "author": "reviewer1"}
|
||||
|
||||
# Trigger only accepts changes_requested and commented, not approved
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is False
|
||||
|
||||
def test_matches_pr_review_repo_condition(self, sample_pr_data):
|
||||
"""Test matching repo condition."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="my-project"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is True
|
||||
|
||||
def test_does_not_match_wrong_repo(self, sample_pr_data):
|
||||
"""Test that wrong repo doesn't match."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="other-project"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is False
|
||||
|
||||
def test_matches_reviewer_condition(self, sample_pr_data):
|
||||
"""Test matching reviewer condition."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="reviewer", operator="equals", value="reviewer1"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is True
|
||||
|
||||
def test_matches_multiple_conditions(self, sample_pr_data):
|
||||
"""Test that all conditions must match."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="my-project"),
|
||||
GitHubPRCondition(field="reviewer", operator="equals", value="reviewer1"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is True
|
||||
|
||||
def test_fails_when_one_condition_doesnt_match(self, sample_pr_data):
|
||||
"""Test that if one condition fails, the whole match fails."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="my-project"),
|
||||
GitHubPRCondition(field="reviewer", operator="equals", value="other-reviewer"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is False
|
||||
|
||||
def test_matches_empty_conditions(self, sample_pr_data):
|
||||
"""Test that empty conditions matches all PRs (with correct state)."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "anyone"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is True
|
||||
|
||||
def test_matches_regex_pattern(self, sample_pr_data):
|
||||
"""Test matching with regex pattern."""
|
||||
watcher = GitHubPRWatcher()
|
||||
trigger = GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="matches", value=r"testuser/.*-project"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
)
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._matches_pr_review(sample_pr_data, review, trigger) is True
|
||||
|
||||
def test_check_pr_condition_title(self, sample_pr_data):
|
||||
"""Test checking title condition."""
|
||||
watcher = GitHubPRWatcher()
|
||||
condition = GitHubPRCondition(field="title", operator="contains", value="new feature")
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
assert watcher._check_pr_condition(sample_pr_data, review, condition) is True
|
||||
|
||||
def test_check_pr_condition_missing_author_in_pr(self, sample_pr_data):
|
||||
"""Test condition check when author is missing from PR data."""
|
||||
watcher = GitHubPRWatcher()
|
||||
condition = GitHubPRCondition(field="author", operator="contains", value="someone")
|
||||
review = {"state": "CHANGES_REQUESTED", "author": "reviewer1"}
|
||||
|
||||
# PR data without author info should still work (checks pr.author.login)
|
||||
pr_without_author = {**sample_pr_data, "pr": {"number": 42, "title": "Test"}}
|
||||
# With missing nested data, should return False (not crash)
|
||||
assert watcher._check_pr_condition(pr_without_author, review, condition) is False
|
||||
|
||||
|
||||
class TestGitHubWatcherIntegration:
|
||||
"""Integration tests for GitHubPRWatcher with mocked dependencies."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_automation_creates_trigger_event(
|
||||
self, sample_github_automation, sample_pr_data
|
||||
):
|
||||
"""Test that _execute_automation creates proper TriggerEvent."""
|
||||
watcher = GitHubPRWatcher()
|
||||
review = sample_pr_data["reviews"][0]
|
||||
|
||||
# Mock the execution engine and format_for_claude
|
||||
with patch.object(watcher._engine, "run", new_callable=AsyncMock) as mock_run, \
|
||||
patch.object(watcher, "_format_for_claude", new_callable=AsyncMock) as mock_format:
|
||||
mock_run.return_value = MagicMock(status=MagicMock(value="success"), error=None)
|
||||
mock_format.return_value = {"prompt": "Test prompt", "files_changed": ["file.py"]}
|
||||
|
||||
await watcher._execute_automation(sample_github_automation, sample_pr_data, review)
|
||||
|
||||
# Verify run was called
|
||||
mock_run.assert_called_once()
|
||||
|
||||
# Check the trigger event
|
||||
call_args = mock_run.call_args
|
||||
trigger_event = call_args[0][1]
|
||||
|
||||
assert trigger_event.type == "github_pr"
|
||||
assert trigger_event.data["repo"] == "testuser/my-project"
|
||||
assert trigger_event.data["pr_number"] == 42
|
||||
assert trigger_event.data["review"]["author"] == "reviewer1"
|
||||
assert trigger_event.data["review"]["state"] == "CHANGES_REQUESTED"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_processes_matching_reviews(self, sample_github_automation, sample_pr_data):
|
||||
"""Test that _poll processes reviews that match triggers."""
|
||||
watcher = GitHubPRWatcher()
|
||||
watcher._processed_review_ids = set()
|
||||
|
||||
mock_db = AsyncMock()
|
||||
mock_db.list_automations.return_value = [sample_github_automation]
|
||||
|
||||
with patch("pai.watcher.get_db", return_value=mock_db), \
|
||||
patch.object(watcher, "_fetch_prs_with_reviews", new_callable=AsyncMock) as mock_fetch, \
|
||||
patch.object(watcher, "_execute_automation", new_callable=AsyncMock) as mock_execute, \
|
||||
patch.object(watcher, "_save_state", new_callable=AsyncMock):
|
||||
|
||||
mock_fetch.return_value = [sample_pr_data]
|
||||
|
||||
await watcher._poll()
|
||||
|
||||
# Verify automation was executed
|
||||
mock_execute.assert_called_once()
|
||||
|
||||
# Verify review was marked as processed
|
||||
review_id = f"{sample_pr_data['repo']}#{sample_pr_data['pr']['number']}:12345"
|
||||
assert review_id in watcher._processed_review_ids
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_skips_already_processed_reviews(
|
||||
self, sample_github_automation, sample_pr_data
|
||||
):
|
||||
"""Test that _poll skips already processed reviews."""
|
||||
watcher = GitHubPRWatcher()
|
||||
review_id = f"{sample_pr_data['repo']}#{sample_pr_data['pr']['number']}:12345"
|
||||
watcher._processed_review_ids = {review_id}
|
||||
|
||||
mock_db = AsyncMock()
|
||||
mock_db.list_automations.return_value = [sample_github_automation]
|
||||
|
||||
with patch("pai.watcher.get_db", return_value=mock_db), \
|
||||
patch.object(watcher, "_fetch_prs_with_reviews", new_callable=AsyncMock) as mock_fetch, \
|
||||
patch.object(watcher, "_execute_automation", new_callable=AsyncMock) as mock_execute, \
|
||||
patch.object(watcher, "_save_state", new_callable=AsyncMock):
|
||||
|
||||
mock_fetch.return_value = [sample_pr_data]
|
||||
|
||||
await watcher._poll()
|
||||
|
||||
# Verify automation was NOT executed
|
||||
mock_execute.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_skips_non_matching_reviews(self, sample_pr_data):
|
||||
"""Test that _poll skips reviews that don't match trigger conditions."""
|
||||
watcher = GitHubPRWatcher()
|
||||
watcher._processed_review_ids = set()
|
||||
|
||||
# Automation that expects a different repo
|
||||
automation = Automation(
|
||||
id="auto_1",
|
||||
name="Test",
|
||||
status=AutomationStatus.ACTIVE,
|
||||
trigger=GitHubPRTrigger(
|
||||
account="test",
|
||||
conditions=[
|
||||
GitHubPRCondition(field="repo", operator="contains", value="other-project"),
|
||||
],
|
||||
review_states=["changes_requested"],
|
||||
),
|
||||
actions=[],
|
||||
)
|
||||
|
||||
mock_db = AsyncMock()
|
||||
mock_db.list_automations.return_value = [automation]
|
||||
|
||||
with patch("pai.watcher.get_db", return_value=mock_db), \
|
||||
patch.object(watcher, "_fetch_prs_with_reviews", new_callable=AsyncMock) as mock_fetch, \
|
||||
patch.object(watcher, "_execute_automation", new_callable=AsyncMock) as mock_execute, \
|
||||
patch.object(watcher, "_save_state", new_callable=AsyncMock):
|
||||
|
||||
mock_fetch.return_value = [sample_pr_data]
|
||||
|
||||
await watcher._poll()
|
||||
|
||||
# Verify automation was NOT executed (repo doesn't match)
|
||||
mock_execute.assert_not_called()
|
||||
|
||||
# But review should still be marked as processed
|
||||
review_id = f"{sample_pr_data['repo']}#{sample_pr_data['pr']['number']}:12345"
|
||||
assert review_id in watcher._processed_review_ids
|
||||
|
||||
Reference in New Issue
Block a user