From ac3ac2f53048fcd7a1b020ea95d7efb449cc94b7 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 5 Oct 2026 20:35:47 +0000 Subject: [PATCH] fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails (#806) --- changelog.d/806.md | 5 + ...when-its-timeline-or-reviews-read-fails.md | 38 +++++ src/devops_cli/github/pr_monitor.py | 145 ++++++++++++---- tests/test_github_pr_monitor.py | 158 ++++++++++++++++++ tests/test_pr_cmd.py | 39 +++++ 5 files changed, 349 insertions(+), 36 deletions(-) create mode 100644 changelog.d/806.md create mode 100644 docs/agent/tasks/task-806-pr-monitor-reports-copilot-as-idle-or-completed-when-its-timeline-or-reviews-read-fails.md diff --git a/changelog.d/806.md b/changelog.d/806.md new file mode 100644 index 0000000000..e88ba41372 --- /dev/null +++ b/changelog.d/806.md @@ -0,0 +1,5 @@ +### Fixed +- **PR monitor fail-closed Copilot review state handling**: + - `devops pr monitor` reports Copilot review state as `unread` with `unread_reason` when timeline or review reads fail, rather than reporting `completed` or `idle` (#806). + - Treat `unread` Copilot state as not review-ready and keep polling until settle/timeout, reporting the unread reason upon timeout rather than certifying ready (#806). + - Include unread Copilot review diagnostics in `failure_reasons` and JSON/YAML structured output (#806). diff --git a/docs/agent/tasks/task-806-pr-monitor-reports-copilot-as-idle-or-completed-when-its-timeline-or-reviews-read-fails.md b/docs/agent/tasks/task-806-pr-monitor-reports-copilot-as-idle-or-completed-when-its-timeline-or-reviews-read-fails.md new file mode 100644 index 0000000000..7494d855c8 --- /dev/null +++ b/docs/agent/tasks/task-806-pr-monitor-reports-copilot-as-idle-or-completed-when-its-timeline-or-reviews-read-fails.md @@ -0,0 +1,38 @@ +# Task: PR Monitor Reports Copilot as Idle or Completed When Its Timeline or Reviews Read Fails (#806) + +**Issue**: [#806](https://github.com/dan-petty/devops-cli/issues/806) +**Status**: Done +**Milestone**: v0.2.27 +**Priority**: priority/p1-high +**Scope**: scope/github, type/bug + +## Description + +`devops pr monitor` previously reported that GitHub Copilot was idle or completed review when timeline or review reads failed (due to rate limiting, network blips, or non-zero subprocess exit), potentially certifying a PR ready while Copilot was still reviewing or had requested changes. + +This implementation adds fail-closed Copilot review state handling: +- **`CopilotReviewStatus` Model**: Added `unread` state and `unread_reason: str = ""` field. +- **Timeline & Reviews Read Failure Detection**: + - `_extract_proc_error`: Trimmed stderr (up to 256 chars) or `Exit code {code}` fallback. + - `_query_timeline_copilot_state`: Returns `(working, event, err)`, capturing subprocess failures. + - `_fetch_raw_reviews`: Returns `RawReviewsList` preserving review items and tracking `error` reason upon non-zero exit. + - `_detect_copilot_status`: Detects read failures from timeline or reviews and immediately returns `unread` state with the failure reason, taking precedence over `changes_requested` and `completed`. +- **Readiness & Settle Gating**: + - `PRMonitorStatus.is_review_ready` treats `unread` Copilot state as not ready. + - `_check_pr_ready_step` avoids certifying settled readiness while Copilot is `unread`. + - `_build_monitor_timeout_result` reports `(Copilot review state could not be read: {reason})` upon timeout. + - `_build_failure_reasons` includes `Copilot review state could not be read: {reason}` in failure reasons. + - `devops pr monitor --format json` emits `state: unread` and `unread_reason` in structured payload. + +## Acceptance Criteria + +- [x] Timeline read exits 1 and an earlier Copilot review exists: `_detect_copilot_status` returns `state == "unread"` with non-empty `unread_reason`, and `PRMonitorStatus.is_review_ready` is `False`. +- [x] Reviews read exits 1: `get_pr_monitoring_status` returns `copilot_status.state == "unread"`. +- [x] Timeline read exits 1 and known Copilot review recommends changes: state is `unread`, taking precedence over `changes_requested`. +- [x] A successful read with empty output still reports `idle`, and every existing state is unchanged. +- [x] `monitor_pr` does not certify an approved, green PR ready while Copilot is `unread`, exiting 3 with the unread reason in the timeout message. +- [x] `failure_reasons` names the unread reason. +- [x] `devops pr monitor --format json` output carries `copilot_status.state == "unread"` and `copilot_status.unread_reason`. +- [x] All tests run offline and patch external subprocess calls. +- [x] `changelog.d/806.md` exists and `CHANGELOG.md` and `docs/ROADMAP.md` remain untouched. +- Pending a person: `uv run devops ci` passes on this branch. diff --git a/src/devops_cli/github/pr_monitor.py b/src/devops_cli/github/pr_monitor.py index c53be608c7..a04d6a39e6 100644 --- a/src/devops_cli/github/pr_monitor.py +++ b/src/devops_cli/github/pr_monitor.py @@ -73,7 +73,8 @@ class CopilotReviewStatus(BaseModel): """Status of GitHub Copilot / automated code review session on a pull request.""" is_active: bool = False - state: str = "idle" # idle | working | completed | changes_requested + state: str = "idle" # idle | working | completed | changes_requested | unread + unread_reason: str = "" message: str = "" last_review_at: str = "" active_event: str = "" @@ -131,7 +132,7 @@ def is_review_ready(self) -> bool: approval_ok = (self.review_decision == "APPROVED") if self.require_reviews else True copilot_ok = ( not self.copilot_status.is_active - and self.copilot_status.state != "changes_requested" + and self.copilot_status.state not in {"changes_requested", "unread"} and not self.has_changes_requested ) return threads_ok and approval_ok and copilot_ok @@ -314,7 +315,17 @@ def _extract_latest_copilot_review( return latest_review, has_changes, latest_state, last_time -def _query_timeline_copilot_state(owner: str, repo_name: str, pr_number: int) -> tuple[bool, str]: +def _extract_proc_error(proc: Any) -> str: + """Extract trimmed stderr or exit code from a process result.""" + stderr = str(getattr(proc, "stderr", "") or "").strip() + if stderr: + return stderr[:256] + return f"Exit code {getattr(proc, 'returncode', 1)}" + + +def _query_timeline_copilot_state( + owner: str, repo_name: str, pr_number: int +) -> tuple[bool, str, str]: """Query issue timeline to detect active Copilot review events.""" cmd = [ CONST_GH_CLI, @@ -325,9 +336,50 @@ def _query_timeline_copilot_state(owner: str, repo_name: str, pr_number: int) -> '.[] | select(.event | test("copilot|reviewed")) | {event: .event, created_at: .created_at, submitted_at: .submitted_at, author: (.actor.login // .user.login // "")}', ] proc = run_gh(cmd, check=False, quiet=True) - if proc.returncode == 0 and proc.stdout.strip(): - return _parse_timeline_copilot_state(proc.stdout) - return False, "" + if proc.returncode == 0: + if proc.stdout.strip(): + working, event = _parse_timeline_copilot_state(proc.stdout) + return working, event, "" + return False, "", "" + err = _extract_proc_error(proc) + return False, "", err + + +def _resolve_timeline_query(owner: str, repo_name: str, pr_number: int) -> tuple[bool, str, str]: + """Query timeline events and return working flag, active event, and any error reason.""" + res = _query_timeline_copilot_state(owner, repo_name, pr_number) + if len(res) == 3: + return res + return res[0], res[1], "" + + +def _build_changes_status( + latest_state: str, + last_time: str, + active_event: str, + unresolved_threads: list[ReviewThread] | None, +) -> CopilotReviewStatus: + """Construct CopilotReviewStatus when changes were requested in latest review.""" + if unresolved_threads is not None and not unresolved_threads: + return CopilotReviewStatus( + is_active=False, + state="completed", + message="Copilot review session completed (all recommended changes resolved)", + last_review_at=last_time, + active_event=active_event, + ) + msg = ( + "Copilot requested changes on the pull request" + if latest_state == "CHANGES_REQUESTED" + else "Copilot recommended changes on the pull request" + ) + return CopilotReviewStatus( + is_active=False, + state="changes_requested", + message=msg, + last_review_at=last_time, + active_event=active_event, + ) def _detect_copilot_status( @@ -336,10 +388,24 @@ def _detect_copilot_status( pr_number: int, reviews: list[dict[str, Any]], unresolved_threads: list[ReviewThread] | None = None, + reviews_err: str = "", ) -> CopilotReviewStatus: """Inspect timeline events and review states to detect Copilot review activity.""" latest_review, has_changes, latest_state, last_time = _extract_latest_copilot_review(reviews) - copilot_working, active_event = _query_timeline_copilot_state(owner, repo_name, pr_number) + copilot_working, active_event, timeline_err = _resolve_timeline_query( + owner, repo_name, pr_number + ) + + err = reviews_err or getattr(reviews, "error", "") or timeline_err + if err: + return CopilotReviewStatus( + is_active=False, + state="unread", + unread_reason=err, + message=f"Copilot review state could not be read: {err}", + last_review_at=last_time, + active_event=active_event, + ) if copilot_working: return CopilotReviewStatus( @@ -350,26 +416,7 @@ def _detect_copilot_status( active_event=active_event, ) if has_changes: - if unresolved_threads is not None and not unresolved_threads: - return CopilotReviewStatus( - is_active=False, - state="completed", - message="Copilot review session completed (all recommended changes resolved)", - last_review_at=last_time, - active_event=active_event, - ) - msg = ( - "Copilot requested changes on the pull request" - if latest_state == "CHANGES_REQUESTED" - else "Copilot recommended changes on the pull request" - ) - return CopilotReviewStatus( - is_active=False, - state="changes_requested", - message=msg, - last_review_at=last_time, - active_event=active_event, - ) + return _build_changes_status(latest_state, last_time, active_event, unresolved_threads) if latest_review: return CopilotReviewStatus( is_active=False, @@ -488,12 +535,22 @@ def _fetch_rest_check_runs(owner: str, repo: str, head_sha: str) -> list[PRCheck ) +class RawReviewsList(list[dict[str, Any]]): + """List of review dictionaries carrying optional read error reason.""" + + error: str = "" + + def __init__(self, items: Any = (), error: str = "") -> None: + super().__init__(items) + self.error = error + + def _fetch_pr_details(owner: str, repo_name: str, pr_number: int) -> dict[str, Any]: """Query GitHub REST API for pull request core attributes.""" pr_cmd = [CONST_GH_CLI, "api", f"repos/{owner}/{repo_name}/pulls/{pr_number}"] pr_proc = run_gh(pr_cmd, check=False, quiet=True) if pr_proc.returncode != 0 or not pr_proc.stdout.strip(): - err = pr_proc.stderr.strip()[:256] if pr_proc.stderr else f"Exit code {pr_proc.returncode}" + err = _extract_proc_error(pr_proc) raise GitHubOperationError(f"Failed to query PR #{pr_number}: {err}") try: data = json.loads(pr_proc.stdout) @@ -502,7 +559,7 @@ def _fetch_pr_details(owner: str, repo_name: str, pr_number: int) -> dict[str, A raise GitHubOperationError(f"Failed to parse PR #{pr_number} data: {exc}") from exc -def _fetch_raw_reviews(owner: str, repo_name: str, pr_number: int) -> list[dict[str, Any]]: +def _fetch_raw_reviews(owner: str, repo_name: str, pr_number: int) -> RawReviewsList: """Fetch all review records for a PR.""" from devops_cli.github.client import parse_paginated_json @@ -513,9 +570,11 @@ def _fetch_raw_reviews(owner: str, repo_name: str, pr_number: int) -> list[dict[ f"repos/{owner}/{repo_name}/pulls/{pr_number}/reviews", ] reviews_proc = run_gh(reviews_cmd, check=False, quiet=True) - if reviews_proc.returncode == 0 and reviews_proc.stdout.strip(): - return parse_paginated_json(reviews_proc.stdout) - return [] + if reviews_proc.returncode == 0: + items = parse_paginated_json(reviews_proc.stdout) if reviews_proc.stdout.strip() else [] + return RawReviewsList(items, error="") + err = _extract_proc_error(reviews_proc) + return RawReviewsList([], error=err) def _fetch_unresolved_threads(owner: str, repo_name: str, pr_number: int) -> list[ReviewThread]: @@ -562,7 +621,9 @@ def _build_failure_reasons( reasons.append(f"{len(failing)} CI check(s) failed") if unresolved_threads: reasons.append(f"{len(unresolved_threads)} unresolved review thread(s)") - if copilot_status.state == "changes_requested": + if copilot_status.state == "unread": + reasons.append(f"Copilot review state could not be read: {copilot_status.unread_reason}") + elif copilot_status.state == "changes_requested": reasons.append(f"Copilot review: {copilot_status.message}") elif has_changes_requested: reasons.append("Reviewers requested changes on the pull request") @@ -632,8 +693,14 @@ def get_pr_monitoring_status( checks = _fetch_rest_check_runs(owner, repo_name, head_sha) raw_reviews = _fetch_raw_reviews(owner, repo_name, pr_number) unresolved_threads = _fetch_unresolved_threads(owner, repo_name, pr_number) + reviews_err = getattr(raw_reviews, "error", "") copilot_status = _detect_copilot_status( - owner, repo_name, pr_number, raw_reviews, unresolved_threads=unresolved_threads + owner, + repo_name, + pr_number, + raw_reviews, + unresolved_threads=unresolved_threads, + reviews_err=reviews_err, ) review_decision = _resolve_review_decision(raw_reviews, head_sha=head_sha) @@ -775,7 +842,13 @@ def _build_monitor_timeout_result( ) -> PRMonitorResult: """Build timeout result with pending check and review diagnostics.""" pending_checks = len(latest_status.pending_checks) - copilot_msg = " (Copilot review still active)" if latest_status.copilot_status.is_active else "" + if latest_status.copilot_status.is_active: + copilot_msg = " (Copilot review still active)" + elif latest_status.copilot_status.state == "unread": + reason = latest_status.copilot_status.unread_reason or "unknown" + copilot_msg = f" (Copilot review state could not be read: {reason})" + else: + copilot_msg = "" return PRMonitorResult( success=False, exit_code=3, @@ -798,7 +871,7 @@ def _check_pr_ready_step( checks_completed = latest_status.all_checks_completed and latest_status.all_checks_passed copilot_done = ( not latest_status.copilot_status.is_active - and latest_status.copilot_status.state != "changes_requested" + and latest_status.copilot_status.state not in {"changes_requested", "unread"} ) settled = now >= settle_deadline if checks_completed and copilot_done and (settled or not require_reviews): diff --git a/tests/test_github_pr_monitor.py b/tests/test_github_pr_monitor.py index cf622aac70..940bdbdf89 100644 --- a/tests/test_github_pr_monitor.py +++ b/tests/test_github_pr_monitor.py @@ -275,6 +275,54 @@ def mock_subprocess(cmd: list[str], **kwargs: object) -> MagicMock: assert status.unresolved_threads == [] assert status.is_ready_for_merge is True + def test_get_pr_monitoring_status_unread_when_reviews_read_fails(self) -> None: + pr_rest_data = { + "number": 168, + "title": "fix: metrics delta", + "draft": False, + "head": {"sha": "7316135"}, + "mergeable": True, + "mergeable_state": "clean", + } + check_runs_data = { + "check_runs": [ + { + "name": "Validation", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/runs/1", + "app": {"name": "CI Quality Gate"}, + }, + ] + } + timeline_output = ( + '{"event": "copilot_work_started", "created_at": "2026-09-12T13:52:12Z"}\n' + '{"event": "reviewed", "submitted_at": "2026-09-12T13:59:17Z"}\n' + ) + + def mock_subprocess(cmd: list[str], **kwargs: object) -> MagicMock: + cmd_str = " ".join(cmd) + if "pulls/168/reviews" in cmd_str: + return MagicMock(returncode=1, stdout="", stderr="HTTP 502: Bad Gateway") + if "pulls/168" in cmd_str: + return MagicMock(returncode=0, stdout=json.dumps(pr_rest_data), stderr="") + if "check-runs" in cmd_str: + return MagicMock(returncode=0, stdout=json.dumps(check_runs_data), stderr="") + if "timeline" in cmd_str: + return MagicMock(returncode=0, stdout=timeline_output, stderr="") + return MagicMock(returncode=0, stdout="", stderr="") + + with ( + patch("devops_cli.github.pr_monitor.run_gh", side_effect=mock_subprocess), + patch("devops_cli.github.pr_monitor.list_pr_review_threads", return_value=[]), + ): + status = get_pr_monitoring_status("dan-petty", "devops-cli", 168) + assert ( + status.copilot_status.state, + status.copilot_status.unread_reason, + status.is_review_ready, + ) == ("unread", "HTTP 502: Bad Gateway", False) + class TestMonitorPR: """Test monitor_pr loop and exit code outcomes.""" @@ -391,6 +439,39 @@ def test_monitor_pr_timeout(self) -> None: assert result.exit_code == 3 assert "timed out" in result.message + def test_monitor_pr_does_not_certify_ready_while_copilot_unread(self) -> None: + unread_status = PRMonitorStatus( + number=168, + title="fix: ready checks but copilot unread", + checks=[PRCheckRun(name="Validation", status="COMPLETED", conclusion="SUCCESS")], + copilot_status=CopilotReviewStatus( + is_active=False, + state="unread", + unread_reason="HTTP 403: rate limit", + message="Copilot review state could not be read: HTTP 403: rate limit", + ), + unresolved_threads=[], + review_decision="APPROVED", + mergeable=True, + mergeable_state="clean", + ) + with ( + patch( + "devops_cli.github.pr_monitor.get_pr_monitoring_status", return_value=unread_status + ), + patch("time.sleep", return_value=None), + ): + result = monitor_pr( + "dan-petty", + "devops-cli", + 168, + timeout=1, + interval=1, + settle_timeout=0, + ) + assert (result.success, result.exit_code) == (False, 3) + assert "HTTP 403: rate limit" in result.message + def test_monitor_pr_changes_requested_returns_exit_code_2(self) -> None: cr_status = PRMonitorStatus( number=168, @@ -558,6 +639,59 @@ def test_detect_copilot_status_retains_changes_requested_when_unresolved_threads assert status.is_active is False assert "recommended changes" in status.message + def test_detect_copilot_status_unread_when_timeline_read_fails(self) -> None: + reviews_data = [ + { + "user": {"login": "copilot-pull-request-reviewer[bot]"}, + "state": "COMMENTED", + "body": "### 🟢 No changes recommended\n\nLooks good!", + "submitted_at": "2026-09-12T14:00:00Z", + } + ] + from devops_cli.github.pr_monitor import _detect_copilot_status + + with patch("devops_cli.github.pr_monitor.run_gh") as mock_sub: + mock_sub.return_value = MagicMock( + returncode=1, stdout="", stderr="HTTP 403: rate limit" + ) + status = _detect_copilot_status("dan-petty", "devops-cli", 168, reviews_data) + pr_status = PRMonitorStatus( + number=168, + title="test", + copilot_status=status, + unresolved_threads=[], + review_decision="APPROVED", + ) + assert ( + status.state, + status.unread_reason, + status.is_active, + pr_status.is_review_ready, + ) == ("unread", "HTTP 403: rate limit", False, False) + assert "could not be read: HTTP 403: rate limit" in status.message + + def test_detect_copilot_status_unread_wins_over_changes_requested(self) -> None: + reviews_data = [ + { + "user": {"login": "copilot-pull-request-reviewer[bot]"}, + "state": "COMMENTED", + "body": "### 🟡 Changes recommended\n\nFix this.", + "submitted_at": "2026-09-12T14:00:00Z", + } + ] + from devops_cli.github.pr_monitor import _detect_copilot_status + + with patch("devops_cli.github.pr_monitor.run_gh") as mock_sub: + mock_sub.return_value = MagicMock( + returncode=1, stdout="", stderr="HTTP 500: internal server error" + ) + status = _detect_copilot_status("dan-petty", "devops-cli", 168, reviews_data) + assert ( + status.state, + status.unread_reason, + status.is_active, + ) == ("unread", "HTTP 500: internal server error", False) + def test_monitor_pr_succeeds_when_copilot_changes_resolved(self) -> None: reviews_data = [ { @@ -889,6 +1023,30 @@ def test_build_failure_reasons_includes_review_approval(self) -> None: ) assert any("requires approved review" in r for r in reasons) + def test_build_failure_reasons_includes_copilot_unread(self) -> None: + """Verify _build_failure_reasons records unread reason when Copilot review cannot be read.""" + from devops_cli.github.pr_monitor import _build_failure_reasons + + reasons = _build_failure_reasons( + checks=[], + unresolved_threads=[], + copilot_status=CopilotReviewStatus( + is_active=False, + state="unread", + unread_reason="HTTP 403: rate limit", + message="Copilot review state could not be read: HTTP 403: rate limit", + ), + has_changes_requested=False, + mergeable=True, + mergeable_state="clean", + is_draft=False, + require_reviews=True, + review_decision="APPROVED", + ) + assert any( + "Copilot review state could not be read: HTTP 403: rate limit" in r for r in reasons + ) + def test_parse_timeline_copilot_state_empty_array(self) -> None: """Verify _parse_timeline_copilot_state handles empty JSON array.""" from devops_cli.github.pr_monitor import _parse_timeline_copilot_state diff --git a/tests/test_pr_cmd.py b/tests/test_pr_cmd.py index a8eeb72ffe..32b71c671d 100644 --- a/tests/test_pr_cmd.py +++ b/tests/test_pr_cmd.py @@ -628,6 +628,45 @@ def test_pr_monitor_json_format_is_pure_json(self, runner: CliRunner) -> None: assert parsed["success"] is True assert parsed["exit_code"] == 0 + def test_pr_monitor_json_format_copilot_unread(self, runner: CliRunner) -> None: + from devops_cli.github.pr_monitor import ( + CopilotReviewStatus, + PRCheckRun, + PRMonitorResult, + PRMonitorStatus, + ) + + mock_status = PRMonitorStatus( + number=168, + title="fix: unread", + checks=[PRCheckRun(name="CI", status="COMPLETED", conclusion="SUCCESS")], + copilot_status=CopilotReviewStatus( + is_active=False, + state="unread", + unread_reason="HTTP 403: rate limit", + message="Copilot review state could not be read: HTTP 403: rate limit", + ), + unresolved_threads=[], + ) + mock_result = PRMonitorResult( + success=False, + exit_code=3, + message="PR #168 monitoring timed out after 300s: 0 check(s) pending (Copilot review state could not be read: HTTP 403: rate limit).", + status=mock_status, + ) + with ( + patch("shutil.which", return_value="/usr/bin/gh"), + patch("devops_cli.core.repo.get_repo_origin_name", return_value="owner/repo"), + patch("devops_cli.github.pr_monitor.monitor_pr", return_value=mock_result), + ): + res = runner.invoke(app, ["monitor", "168", "--format", "json"]) + assert res.exit_code == 3 + parsed = json.loads(res.output.strip()) + assert ( + parsed["status"]["copilot_status"]["state"], + parsed["status"]["copilot_status"]["unread_reason"], + ) == ("unread", "HTTP 403: rate limit") + def test_pr_monitor_invalid_bounds_and_format(self, runner: CliRunner) -> None: with ( patch("shutil.which", return_value="/usr/bin/gh"),