From 46ab2fc7747c226b79dcf9f64c35ed2c090974dd Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 13 Nov 2026 08:00:02 +0000 Subject: [PATCH 1/3] fix(review): review a pull request at the merge base of its base branch devops review pr read the files of a pull request from the pulls files endpoint, its diff from the pulls endpoint, and its base text at the merge base of the payload's base.sha. GitHub does not move base.sha when a merge commit moves the merge base, so after a merge of main into a pull request branch the review read the changes of main as changes of the pull request. devops ai analyze pr read the same stale file list. Both commands now read the compare of the tip of the base branch and the head commit, which is the diff that the squash merge applies. The review reads the diff, the base text, the conventions and the base worktree at the merge base of that compare. A compare at the 300-file limit ends the review with a message that names devops review branch, and gives the analysis a warning. GitHubClient.get_compare_files returns the merge base, GitHubClient.get_compare_diff reads the compare diff, and the change deletes get_pull_files and get_merge_base, which have no caller. Refs #5346 --- docs/SELF_IMPROVEMENT.md | 3 +- .../5346-review-pr-merge-base/.openspec.yaml | 2 + .../5346-review-pr-merge-base/design.md | 20 ++ .../5346-review-pr-merge-base/proposal.md | 48 ++++ .../specs/pr-squash-diff/spec.md | 38 +++ .../5346-review-pr-merge-base/tasks.md | 39 +++ .../devops_cli/python_packages.md | 2 +- src/devops_cli/ai/review/runner.py | 73 +++--- src/devops_cli/commands/analyze.py | 23 +- src/devops_cli/commands/review.py | 13 +- src/devops_cli/github/client.py | 69 +++-- src/devops_cli/lang/en/messages.py | 10 + .../ai/client/test_batch_2_review_defects.py | 27 +- tests/ai/review/test_review_path_routing.py | 26 +- tests/ai/review/test_review_runner.py | 24 +- tests/commands/test_analyze.py | 177 +++++++++---- tests/commands/test_review_pr_post.py | 48 +--- tests/commands/test_review_scope.py | 245 +++++++++++++----- .../github/hello_world_pull_request.json | 75 +++--- tests/git/test_ai_task_metadata.py | 11 +- tests/git/test_review_worktree_regression.py | 19 +- tests/github/test_github_client.py | 148 ++++++----- tests/roadmap/test_roadmap_draft_readiness.py | 2 + tests/support/fakes/github.py | 41 ++- 24 files changed, 783 insertions(+), 400 deletions(-) create mode 100644 openspec/changes/5346-review-pr-merge-base/.openspec.yaml create mode 100644 openspec/changes/5346-review-pr-merge-base/design.md create mode 100644 openspec/changes/5346-review-pr-merge-base/proposal.md create mode 100644 openspec/changes/5346-review-pr-merge-base/specs/pr-squash-diff/spec.md create mode 100644 openspec/changes/5346-review-pr-merge-base/tasks.md diff --git a/docs/SELF_IMPROVEMENT.md b/docs/SELF_IMPROVEMENT.md index e7bb99441c..d236afbf00 100644 --- a/docs/SELF_IMPROVEMENT.md +++ b/docs/SELF_IMPROVEMENT.md @@ -742,7 +742,8 @@ project enforces, the inputs the project trusts, or house rules for its document A change is reviewed under the conventions it started from, so it cannot loosen its own review (#946). `devops review branch` reads conventions with git at the merge base of the branch and its base (at `HEAD` for uncommitted changes), not from the working tree, and `devops review pr` reads -them from the pull request's base. A base with no local branch, as in a CI checkout of a feature, +them at the merge base of the pull request's head commit and the tip of its base branch, the base +of the diff that the squash merge applies (#5346). A base with no local branch, as in a CI checkout of a feature, is `origin/`, and the checked-out branch is never its own base: with no base at all the diff fails. The lookup also stops at a defect corpus's root, which its manifest marks, read at the same revision. It reads only regular files: a conventions file that is a link is skipped, on disk and diff --git a/openspec/changes/5346-review-pr-merge-base/.openspec.yaml b/openspec/changes/5346-review-pr-merge-base/.openspec.yaml new file mode 100644 index 0000000000..22ca07d756 --- /dev/null +++ b/openspec/changes/5346-review-pr-merge-base/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-13 diff --git a/openspec/changes/5346-review-pr-merge-base/design.md b/openspec/changes/5346-review-pr-merge-base/design.md new file mode 100644 index 0000000000..035c3a204a --- /dev/null +++ b/openspec/changes/5346-review-pr-merge-base/design.md @@ -0,0 +1,20 @@ +# Design + +## Decisions + +- **Read the file list from the compare of the base branch name and the head commit sha.**: GitHub compares from the merge base of the two, so this is the diff that the squash merge applies. For pull request 2509, `compare/main...344adba9` gave the 11 files of the squash commit. Readiness reads the same compare (#2530), and the head is a commit sha for a fork too. +- **Read the diff from the compare of the merge base and the head commit.**: The merge base comes from the file read, so the diff and the file list come from one commit, also when the base branch moves between the two requests. The compare of a merge base and its descendant is the diff of the two. +- **Read the base text, the conventions and the base worktree at the merge base of the compare.**: The tip of the base branch can be ahead of the merge base, and symbols added on the base since would read as removed. The fetch of `refs/pull//head` brings every ancestor of the head, the merge base too, so the local worktree can be made there. The payload's `base.sha` can be absent from the local repository. +- **Return the merge base from `get_compare_files` and delete `get_merge_base`.**: The review needs the files and the merge base of one compare, and one request gives both. The design of #2530 kept the two reads apart so that a malformed file entry did not break the merge base read of the review. The review now needs the files, so that reason is gone. +- **Give the merge base to the review worktrees through `BaseRevision.revision`.**: The branch review gives its base worktree the same field. `_run_pr_review_workflow` then needs no pull request. +- **End `devops review pr` when the compare lists 300 files.**: The compare diff holds every file, but the head files, the symbol deltas and the filter of deleted files read the file list. A review of a partial list would give wrong deltas with no sign. The message names `devops review branch`, which reads the diff with git and has no such limit. +- **Warn and continue in `devops ai analyze pr` when the compare lists 300 files.**: The analysis gives one record for each file, so a partial list gives fewer records and no wrong record. The warning names the limit. +- **List the files of the comment from the base revision of the review.**: The base revision holds the compare that the review read, so the comment names the same files and needs no second request. +- **Delete `get_pull_files`.**: No code in `src/` calls it after this change. Its tests move to the compare read, which parses the same `PullRequestFile` model. + +## Rejected alternatives + +- **Compare from the payload's `base.sha`.**: For pull request 2509, `compare/0137f231...344adba9` gave merge base 0137f231 and the same 184 files as the pulls files endpoint. +- **Keep the diff of the pulls endpoint and filter it by the compare file list.**: The pulls diff of pull request 2509 held 184 files against 11 in the compare, and a page of a file that both changed would show the changes of `main` too. +- **Read the diff from `compare/...`.**: It is the same diff while the merge base stays, but a push that moves the merge base between the two requests, such as a merge of the head into the base branch, could give a diff from another merge base than the file list. +- **Fall back to the pulls files endpoint when the compare lists 300 files.**: That list keeps the stale base, so the review would read the changes of `main` again. diff --git a/openspec/changes/5346-review-pr-merge-base/proposal.md b/openspec/changes/5346-review-pr-merge-base/proposal.md new file mode 100644 index 0000000000..b794fe8df9 --- /dev/null +++ b/openspec/changes/5346-review-pr-merge-base/proposal.md @@ -0,0 +1,48 @@ +# Proposal: #5346 + +## Why + +The issue #5346 reports that `devops review pr` and `devops ai analyze pr` read a stale change set. The review read the files of a pull request from the pulls files endpoint and its diff from the pulls endpoint, and it read the base text at the merge base of the payload's `base.sha` and the head commit. It also gave `base.sha` to the review worktrees as the base revision. GitHub does not move `base.sha` when a merge commit moves the merge base of a pull request, and the pulls files and diff endpoints keep that stale base too. Thus, after a person merges `main` into a pull request branch, the review reads the changes of `main` as changes of the pull request. `devops ai analyze pr` read the pulls files endpoint and has the same defect. The issue #2530 fixed the same cause in `devops pr check-readiness`. + +## What Changes + +- `devops review pr` reads the files of a pull request from the compare of the tip of its base branch and its head commit (`compare/...`), in the base repository. This is the diff that the squash merge applies. +- The review reads the diff from the compare of that merge base and the head commit (`compare/...`, diff media type), so the files and the diff come from one merge base. +- The review reads the base text of each changed file and the base conventions at that merge base. No request of the review names the payload's `base.sha`. +- The base worktree of the review is at that merge base. The fetch of the pull request head brings the merge base to the local repository. +- A compare at GitHub's limit of 300 files ends `devops review pr` with status 1 and a message that names the limit and `devops review branch`. The compare diff has no such limit, but the review needs every changed file for the head files, the symbol deltas and the filter of deleted files. +- When the diff names no reviewable file, the comment of `devops review pr --post` lists the files of the compare that the review read. The command does not read the file list a second time. +- `devops ai analyze pr` reads the files of a pull request from the compare of the tip of its base branch and its head commit. A compare at the limit gives an analysis of the listed files and a warning that names the limit. +- `GitHubClient.get_compare_files` also returns the merge base of the compare, and the new `GitHubClient.get_compare_diff` reads the diff of two commits. `GitHubClient.get_pull_files` and `GitHubClient.get_merge_base` have no caller after this change, so the change deletes them. +- The change alters the output of two commands, so it carries a spec delta. It fits one pull request. + +## Capabilities + +### New Capabilities + +- `pr-squash-diff`: A PR review reads the diff that the squash merge applies, A PR review refuses a compare at the file limit, The PR analysis reads the files of the compare of its base branch + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/github/client.py`, `src/devops_cli/ai/review/runner.py`, `src/devops_cli/commands/review.py`, `src/devops_cli/commands/analyze.py`, `src/devops_cli/lang/en/messages.py` +- Docs: `docs/SELF_IMPROVEMENT.md`, `src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md` +- Tests: `tests/github/test_github_client.py`, `tests/commands/test_review_scope.py`, `tests/commands/test_review_pr_post.py`, `tests/commands/test_analyze.py`, `tests/ai/review/test_review_runner.py`, `tests/ai/review/test_review_path_routing.py`, `tests/ai/client/test_batch_2_review_defects.py`, `tests/git/test_review_worktree_regression.py`, `tests/git/test_ai_task_metadata.py`, `tests/roadmap/test_roadmap_draft_readiness.py`, `tests/support/fakes/github.py`, `tests/fixtures/github/hello_world_pull_request.json` + +## Feasibility + +- A live probe on 2026-11-13 confirmed the premise. `devops gh api repos/dan-petty/devops-cli/pulls/2509` gave state closed, merged true, `base.sha` 0137f231, `base.ref` main, head 344adba9 and 184 changed files. +- `compare/0137f231...344adba9?per_page=1` gave merge base 0137f231 and 184 files, and `compare/main...344adba9?per_page=1` gave merge base 5c4d24ee and 11 files, the files of the squash commit. +- The diff of the pulls endpoint (`pulls/2509` with `Accept: application/vnd.github.diff`) held 184 `diff --git` headers, and the diff of `compare/main...344adba9` held 11. So the diff that the review read was stale too, not only its file list. +- `compare/v0.100.0...v0.127.0?per_page=1` listed 300 files, the limit, and its diff media type held 3394 `diff --git` headers. So the compare diff has no 300-file limit, and the file list is the read that can be partial. +- `compare/master...ec18ca7b` of octocat/Hello-World pull request 158 gave merge base 7fd1a60b and its 2 files. The change records that answer in `tests/fixtures/github/hello_world_pull_request.json`. +- The source of `origin/main` showed the stale reads: `src/devops_cli/ai/review/runner.py:952` read `get_pr_diff`, line 957 read `get_pull_files`, line 988 read `get_merge_base(base_repo, pull.base.sha, pull.head.sha)`, line 1015 read the conventions at `pull.base.sha`, and line 278 read `get_pull_files` for the comment. `src/devops_cli/commands/review.py:731` gave `pull.base.sha` to the worktrees, and `src/devops_cli/commands/analyze.py:537` read `get_pull_files`. +- `git grep` for `get_pull_files` and `get_merge_base` in `src/` showed no caller other than these reads. + +## Existing Tool Considered + +- The GitHub REST compare endpoint covers the need: it compares from the merge base of the base branch and the head, and it serves the diff in the diff media type. The change uses `GitHubClient.get_compare_files`, which #2530 added for readiness, and adds no second copy of that read. +- The change deletes `GitHubClient.get_pull_files`, `GitHubClient.get_merge_base`, the model `_Comparison`, the test route `route_merge_base`, the `pull` parameter of `_run_pr_review_workflow`, and the second file read of the PR comment. diff --git a/openspec/changes/5346-review-pr-merge-base/specs/pr-squash-diff/spec.md b/openspec/changes/5346-review-pr-merge-base/specs/pr-squash-diff/spec.md new file mode 100644 index 0000000000..15c1a82df1 --- /dev/null +++ b/openspec/changes/5346-review-pr-merge-base/specs/pr-squash-diff/spec.md @@ -0,0 +1,38 @@ +## Purpose + +Which changes of a pull request `devops review pr` and `devops ai analyze pr` read: the files and the diff that the squash merge applies, which is the compare of the tip of the base branch and the head commit, and not the stale base of the pull request payload. + +## ADDED Requirements + +### Requirement: A PR review reads the diff that the squash merge applies +The command `devops review pr` SHALL read the files and the diff of a pull request from the compare of the tip of its base branch and its head commit, and SHALL read the base text and the base conventions at the merge base of that compare. It MUST NOT read the pulls files endpoint or the diff of the pulls endpoint, and MUST NOT read a file at the `base.sha` of the pull request payload. + +#### Scenario: A moved merge base +- **WHEN** a merge of the base branch into the pull request moved its merge base, the payload's `base.sha` and the pulls files and diff endpoints still name the old base, and the compare of the base branch and the head commit names another merge base +- **THEN** the review pages hold only the files of the compare, the base text and the conventions are read at the merge base of the compare, and no request names `base.sha` or the pulls files path + +#### Scenario: The base worktree +- **WHEN** the fetch of the pull request head into the local checkout succeeds +- **THEN** the base worktree of the review is at the merge base of the compare + +#### Scenario: A diff that names no reviewable file +- **WHEN** the diff names no reviewable file and the review posts its comment +- **THEN** the comment lists the files of the compare that the review read, less the deleted files, and the command reads the file list only one time + +### Requirement: A PR review refuses a compare at the file limit +The command `devops review pr` SHALL end with status 1 when the compare of the base branch and the head commit lists GitHub's limit of files for one comparison, with a message that names the limit and `devops review branch`, and SHALL read no diff. + +#### Scenario: The compare lists 300 files +- **WHEN** the compare of the base branch and the head commit lists 300 files +- **THEN** the command exits 1, its message names 300 files and `devops review branch`, and it makes no diff request + +### Requirement: The PR analysis reads the files of the compare of its base branch +The command `devops ai analyze pr` SHALL read the files of a pull request from the compare of the tip of its base branch and its head commit, and MUST NOT read the pulls files endpoint. A compare that lists GitHub's limit of files SHALL give an analysis of the listed files and a warning that names the limit. + +#### Scenario: A moved merge base +- **WHEN** the pulls files endpoint lists a file that the compare of the base branch and the head commit does not list +- **THEN** the analysis holds only the files of the compare, and the command reads only the pull request and the compare + +#### Scenario: The compare lists 300 files +- **WHEN** the compare of the base branch and the head commit lists 300 files +- **THEN** the command exits 0, the analysis holds the 300 files, and a warning names the limit of 300 files diff --git a/openspec/changes/5346-review-pr-merge-base/tasks.md b/openspec/changes/5346-review-pr-merge-base/tasks.md new file mode 100644 index 0000000000..c01e703fde --- /dev/null +++ b/openspec/changes/5346-review-pr-merge-base/tasks.md @@ -0,0 +1,39 @@ +# Tasks + +## 1. Read the merge base and the diff of a compare in the GitHub client + +Kind: behavior. Changes: `src/devops_cli/github/client.py`, `tests/github/test_github_client.py`, `tests/fixtures/github/hello_world_pull_request.json`, `tests/roadmap/test_roadmap_draft_readiness.py`. + +- [x] 1.1 `tests/github/test_github_client.py::test_the_files_of_a_comparison_come_with_its_merge_base` and `test_the_compare_diff_is_read_as_text` fail: the recorded compare of the base branch and the head commit of octocat/Hello-World pull request 158 gives its files and its merge base, and the client has no merge base in `CompareFiles` and no `get_compare_diff` + - Verification: `$ uv run devops ci test tests/github/test_github_client.py` fails on the base +- [x] 1.2 Add `merge_base` to `_CompareFiles` and `CompareFiles`, and add `get_compare_diff`, which shares `_read_diff` with `get_pr_diff`. Delete `get_pull_files`, `get_merge_base` and `_Comparison`, and move their tests to the compare read. Replace the recorded pages of the pulls files endpoint with the recorded compare in the fixture + - Verification: `$ uv run devops ci test tests/github/test_github_client.py tests/roadmap/test_roadmap_draft_readiness.py` passes + +## 2. Review a pull request at the merge base of its base branch + +Kind: behavior. Changes: `src/devops_cli/ai/review/runner.py`, `src/devops_cli/commands/review.py`, `src/devops_cli/lang/en/messages.py`, `tests/support/fakes/github.py`, `tests/commands/test_review_scope.py`, `tests/commands/test_review_pr_post.py`, `tests/ai/review/test_review_runner.py`, `tests/ai/review/test_review_path_routing.py`, `tests/ai/client/test_batch_2_review_defects.py`, `tests/git/test_review_worktree_regression.py`. + +- [x] 2.1 `tests/commands/test_review_scope.py::test_a_pr_review_reads_the_changes_at_the_merge_base_of_its_base_branch` fails: the payload's `base.sha` is not the merge base, the pulls endpoints still list the stale file `main_only.py`, and the review pages hold that file. `test_a_pr_review_refuses_a_comparison_at_the_file_limit` and `tests/git/test_review_worktree_regression.py::test_run_pr_review_workflow_with_worktree` fail too + - Verification: `$ uv run devops ci test tests/commands/test_review_scope.py tests/git/test_review_worktree_regression.py` fails on the base +- [x] 2.2 In `_prepare_pr_content`, read the compare of `pull.base.ref` and `pull.head.sha` in the base repository, end the command with `MESSAGES.review.pr_compare_at_file_limit` at the file limit, and read the diff with `get_compare_diff` from the merge base. Give the compare to `_materialize_pr_head` and `_pr_base_revision`, read the conventions and the base text at the merge base, and set `BaseRevision.revision` to it. Give the base worktree that revision, and drop the `pull` parameter of `_run_pr_review_workflow`. List the comment files from the base revision in `resolve_pr_files`. Add `route_compare_diff` and `route_pull_request_changes` to the GitHub fake, and delete `route_merge_base`. Run `uv run devops docs generate` + - Verification: `$ uv run devops ci test tests/commands/test_review_scope.py tests/commands/test_review_pr_post.py tests/ai/review/test_review_runner.py tests/ai/review/test_review_path_routing.py tests/ai/client/test_batch_2_review_defects.py tests/git/test_review_worktree_regression.py` passes + +## 3. Analyze the files of the compare of the base branch + +Kind: behavior. Changes: `src/devops_cli/commands/analyze.py`, `src/devops_cli/lang/en/messages.py`, `tests/commands/test_analyze.py`, `tests/git/test_ai_task_metadata.py`. + +- [x] 3.1 `tests/commands/test_analyze.py::test_analyze_pr_reads_the_files_at_the_merge_base_of_its_base_branch` and `test_analyze_pr_warns_that_a_comparison_at_the_file_limit_can_miss_files` fail: the analysis reads the pulls files endpoint, which lists the stale file `main_only.py` + - Verification: `$ uv run devops ci test tests/commands/test_analyze.py` fails on the base +- [x] 3.2 In `devops ai analyze pr`, read the files with `get_compare_files` of `pull.base.ref` and `pull.head.sha` in the base repository, and warn with `MESSAGES.analyze.pr_compare_at_file_limit` at the file limit. Run `uv run devops docs generate` + - Verification: `$ uv run devops ci test tests/commands/test_analyze.py tests/git/test_ai_task_metadata.py` passes + +## 4. Documents + +Kind: documents. Changes: `docs/SELF_IMPROVEMENT.md`, `src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md`. + +- [x] 4.1 Say in `docs/SELF_IMPROVEMENT.md` that `devops review pr` reads the conventions at the merge base of the head commit and the tip of the base branch, and name the compare reads of `devops_cli.github.client` in the knowledge base + - Verification: `$ uv run devops ci docs` + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md b/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md index ccb5ecf5f6..bcbd2349b8 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md @@ -162,7 +162,7 @@ from devops_cli.ai.review_schema import Finding - **Ecosystem Role**: Sans-I/O GitHub REST client. It builds each request and decodes each answer. It sends nothing itself. - **Codebase Integration**: - `devops_cli.github.session` and `devops_cli.github.session_transport`: Send every REST request as the one identity of the process, read every `Link` page, and raise the typed GitHub errors. See ADR 0006. - - `devops_cli.github.client`: Reads pull requests, their files, files at a commit, merge bases and repositories through the session. It posts review comments through the session. + - `devops_cli.github.client`: Reads pull requests, the files, the merge base and the diff of a compare of two commits, files at a commit and repositories through the session. It posts review comments through the session. #### `cryptography` ([Dedicated Manual](libraries/cryptography.md)) - **Pinned Version**: `cryptography==50.0.2` diff --git a/src/devops_cli/ai/review/runner.py b/src/devops_cli/ai/review/runner.py index b43f81d1a3..e1ba3374fa 100644 --- a/src/devops_cli/ai/review/runner.py +++ b/src/devops_cli/ai/review/runner.py @@ -36,6 +36,7 @@ from devops_cli.config.constants import ( CONST_GIT_MAIN_BRANCH, CONST_GIT_NAME_STATUS_CHANGE_TYPES, + CONST_GITHUB_COMPARE_FILES_LIMIT, CONST_GITHUB_PR_FILE_CHANGE_TYPES, ) from devops_cli.config.defaults import ( @@ -77,7 +78,7 @@ if TYPE_CHECKING: from devops_cli.ai.review.pipeline import ReviewPipelineOrchestrator - from devops_cli.github.client import GitHubClient, PullRequest, PullRequestFile + from devops_cli.github.client import CompareFiles, GitHubClient, PullRequest, PullRequestFile from devops_cli.security.tool_executor import SandboxToolExecutor, ToolExecutor logger = logging.getLogger(__name__) @@ -266,17 +267,15 @@ def format_pr_review_comment( return f"## 🤖 AI Code Review\n\n{sections}\n" -def resolve_pr_files(pages: list[str], repo_name: str, number: int) -> list[str]: - """Extract changed file paths from PR pages, or from the pull request's files when the diff - holds none.""" - from devops_cli.github.session import get_github_session +def resolve_pr_files(pages: list[str], base_revision: BaseRevision | None) -> list[str]: + """Extract changed file paths from PR pages, or, when the diff holds none, the files of the + compare that the review read, less the deleted ones.""" from devops_cli.review.diff import diff_file_names all_files = sorted(list({fn for page in pages for fn in diff_file_names(page)})) - if all_files: + if all_files or base_revision is None: return all_files - files = get_github_session().client.get_pull_files(repo_name, number) - return [f.filename for f in files if f.status != "removed"] + return [c.path for c in base_revision.changes if c.change_type != "deleted"] def post_pr_review_comment( @@ -285,6 +284,7 @@ def post_pr_review_comment( head_dir: Path, repo_name: str, number: int, + base_revision: BaseRevision | None, ) -> None: """Post formatted review comment to GitHub PR.""" from devops_cli.dry_run import is_dry_run @@ -292,7 +292,7 @@ def post_pr_review_comment( from devops_cli.lang import MESSAGES from devops_cli.output import print_success, print_warning - all_files = resolve_pr_files(pages, repo_name, number) + all_files = resolve_pr_files(pages, base_revision) comment_body = format_pr_review_comment( reviews=reviews, files=all_files, @@ -926,7 +926,11 @@ def _prepare_pr_content( """Fetch PR details, diff blocks, and title for PR review target. The repository is `repo_arg`, or with none, the origin of the repository at `checkout`, - which the command gives (#2127). With `head_dir`, the PR head's changed files are written + which the command gives (#2127). The files and the diff are those of the compare of the tip of + the PR's base branch and its head commit, which is the diff a squash merge applies: the + payload's `base.sha` and the pulls files and diff endpoints keep a stale base after a merge + commit moves the merge base (#5346). A compare at GitHub's file limit ends the command, since + the review cannot read every file. With `head_dir`, the PR head's changed files are written under it, and the base revision they are compared with is returned; without it, there is none. """ @@ -949,14 +953,21 @@ def _prepare_pr_content( print_info(fetch_msg, prefix=False) gh = get_github_session().client pull = gh.get_pull(repo, number) - diff = gh.get_pr_diff(repo, number) + base_repo = pull.base.repository or repo + compared = gh.get_compare_files(base_repo, pull.base.ref, pull.head.sha) + if compared.truncated: + limit_err = MESSAGES.review.pr_compare_at_file_limit.format( + number=number, limit=CONST_GITHUB_COMPARE_FILES_LIMIT + ) + print_error(limit_err, prefix=False) + raise typer.Exit(1) + diff = gh.get_compare_diff(base_repo, compared.merge_base, pull.head.sha) title = f"PR #{number}: {pull.title}" head_dir: Path | None = kwargs.get("head_dir") base_revision: BaseRevision | None = None if head_dir is not None: - pr_files = gh.get_pull_files(repo, number) - _materialize_pr_head(gh, repo, pull, head_dir, pr_files) - base_revision = _pr_base_revision(gh, repo, pull, pr_files) + _materialize_pr_head(gh, repo, pull, head_dir, compared) + base_revision = _pr_base_revision(gh, base_repo, compared) path_classes = load_path_classes(base_revision=base_revision) pages = [redact_text(p) for p in diff_blocks(diff, path_classes=path_classes)] if base_revision is not None and base_revision.changes: @@ -974,36 +985,36 @@ def _pr_changed_file(pr_file: PullRequestFile) -> ChangedFile: ) -def _pr_base_revision( - gh: GitHubClient, repo: str, pull: PullRequest, pr_files: Sequence[PullRequestFile] -) -> BaseRevision: +def _pr_base_revision(gh: GitHubClient, base_repo: str, compared: CompareFiles) -> BaseRevision: """The PR's changed files, and a reader for their text at its merge base in the base repo. - `pull.base.sha` is the base branch's tip, which can be ahead of the merge base: read there, - a PR branched earlier would list symbols added on the base since as removed. When GitHub has - no merge base for the two commits, nothing is read, and a modified file's delta stays - unknown; a comparison that fails to be read raises. + The merge base is the one GitHub compared the tip of the base branch from. The tip itself can + be ahead of it: read there, a PR branched earlier would list symbols added on the base since + as removed. The merge base is also the `revision` of the base worktree, since the fetch of + the PR head brings it to the local repository. """ - base_repo = pull.base.repository or repo - merge_base = gh.get_merge_base(base_repo, pull.base.sha, pull.head.sha) - if merge_base is None: - logger.debug("No merge base for %s...%s in %s", pull.base.sha, pull.head.sha, base_repo) + merge_base = compared.merge_base def read(path: str) -> str | None: - return gh.get_file_at(base_repo, path, merge_base) if merge_base else None + return gh.get_file_at(base_repo, path, merge_base) - return BaseRevision(changes=tuple(_pr_changed_file(f) for f in pr_files), read=read) + return BaseRevision( + changes=tuple(_pr_changed_file(f) for f in compared.files), + read=read, + revision=merge_base, + ) def _materialize_pr_head( - gh: GitHubClient, repo: str, pull: PullRequest, dest: Path, pr_files: Sequence[PullRequestFile] + gh: GitHubClient, repo: str, pull: PullRequest, dest: Path, compared: CompareFiles ) -> int: - """Write PR head's version of changed files, and base conventions, under `dest`.""" + """Write PR head's version of the changed files of `compared`, and the base conventions at + its merge base, under `dest`.""" from devops_cli.ai.review.review_environment import _TARGET_CONVENTIONS_CANDIDATES head_repo = pull.head.repository or repo base_repo = pull.base.repository or repo - changed = [f.filename for f in pr_files if f.status != "removed"] + changed = [f.filename for f in compared.files if f.status != "removed"] convention_files = set(_TARGET_CONVENTIONS_CANDIDATES) root = dest.resolve() written = 0 @@ -1012,7 +1023,7 @@ def _materialize_pr_head( target = (root / rel).resolve() if not target.is_relative_to(root): continue - text = gh.get_file_at(base_repo, rel, pull.base.sha) + text = gh.get_file_at(base_repo, rel, compared.merge_base) if text is not None: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(text, encoding="utf-8") diff --git a/src/devops_cli/commands/analyze.py b/src/devops_cli/commands/analyze.py index c758f11e84..8d2f4b4363 100644 --- a/src/devops_cli/commands/analyze.py +++ b/src/devops_cli/commands/analyze.py @@ -17,7 +17,11 @@ ) from devops_cli.ai.analyze.scanner import detect_language, sanitize_reference from devops_cli.ai.client import LLMClient -from devops_cli.config.constants import CONST_GIT_MAIN_BRANCH, CONST_MAX_FILE_SIZE_BYTES +from devops_cli.config.constants import ( + CONST_GIT_MAIN_BRANCH, + CONST_GITHUB_COMPARE_FILES_LIMIT, + CONST_MAX_FILE_SIZE_BYTES, +) from devops_cli.config.defaults import ( DEFAULT_CURRENT_PATH, DEFAULT_MATCH_ALL_PATTERN, @@ -33,7 +37,7 @@ from devops_cli.lang import HELP, MESSAGES from devops_cli.models.ai import AnalysisMetadata, FileAnalysisMeta from devops_cli.models.git import ChangedFile -from devops_cli.output.console import print_error, print_info +from devops_cli.output.console import print_error, print_info, print_warning app = new_typer( help=HELP.analyze.app, @@ -534,7 +538,20 @@ def analyze_pr( # noqa: C901 raise typer.Exit(1) pull = session.client.get_pull(repo_name, pr_number) - pull_files = session.client.get_pull_files(repo_name, pr_number) + # The files of the compare of the base branch and the head commit, which a squash merge + # applies: the pulls files endpoint keeps a stale base after a merge commit moves the merge + # base (#5346). + compared = session.client.get_compare_files( + pull.base.repository or repo_name, pull.base.ref, pull.head.sha + ) + if compared.truncated: + print_warning( + MESSAGES.analyze.pr_compare_at_file_limit.format( + number=pr_number, limit=CONST_GITHUB_COMPARE_FILES_LIMIT + ), + prefix=False, + ) + pull_files = compared.files file_metas: list[FileAnalysisMeta] = [] for f_file in pull_files: diff --git a/src/devops_cli/commands/review.py b/src/devops_cli/commands/review.py index ecec5fc82a..8f96861cd8 100644 --- a/src/devops_cli/commands/review.py +++ b/src/devops_cli/commands/review.py @@ -12,7 +12,6 @@ from devops_cli.ai.analyze.symbols import BaseRevision from devops_cli.ai.review_schema import ReviewResult from devops_cli.config.settings import Settings - from devops_cli.github.client import PullRequest from devops_cli.review.handoff import HandOff from devops_cli.review.score import Agreement, ScoreReport from devops_cli.roadmap.intake.intake_requests import SpendMeter @@ -707,7 +706,6 @@ def branch( def _run_pr_review_workflow( pages: list[str], title: str, - pull: PullRequest, number: int, head_dir: Path, base_revision: BaseRevision | None, @@ -724,11 +722,12 @@ def _run_pr_review_workflow( ) -> list[ReviewResult | str]: """Execute PR review workflow, using detached worktree if available, else partial context. - `checkout` is the local checkout of the PR's repository, which the command gives.""" + `checkout` is the local checkout of the PR's repository, which the command gives. The base + worktree is at the merge base that `base_revision` names, which the fetch of the PR head + brings (#5346).""" from devops_cli.core.repo import get_repo_origin_name from devops_cli.git.worktree import fetch_pr_head, review_worktrees_context - base_sha = pull.base.sha local_repo = get_repo_origin_name(checkout) if repo_arg is not None and local_repo is not None and repo_arg != local_repo: pr_commit = None @@ -759,7 +758,7 @@ def _run_pr_review_workflow( with review_worktrees_context( checkout, commit_rev=pr_commit, - base_rev=base_sha, + base_rev=base_revision.revision if base_revision is not None else None, session_id=session_id, ) as rw: return execute_review_workflow( @@ -911,13 +910,12 @@ def pr( checkout = find_repo_root(Path.cwd()) with tempfile.TemporaryDirectory(prefix=f"devops-review-pr-{number}-") as head_parent: head_dir = Path(head_parent) - pages, title, pull, repo_name, base_revision = _prepare_pr_content( + pages, title, _pull, repo_name, base_revision = _prepare_pr_content( number, repo, checkout=checkout, head_dir=head_dir ) reviews = _run_pr_review_workflow( pages, title, - pull, number, head_dir, base_revision, @@ -941,6 +939,7 @@ def pr( head_dir=head_dir, repo_name=repo_name, number=number, + base_revision=base_revision, ) diff --git a/src/devops_cli/github/client.py b/src/devops_cli/github/client.py index 644c0bfd92..86d5e19fcd 100755 --- a/src/devops_cli/github/client.py +++ b/src/devops_cli/github/client.py @@ -303,25 +303,22 @@ class _FileContents(BaseModel): content: str = "" -class _Comparison(BaseModel): - """What the compare endpoint says of two commits that devops-cli reads: their merge base.""" - - merge_base: str = Field(validation_alias=AliasPath("merge_base_commit", "sha")) - - class _CompareFiles(BaseModel): - """What the compare endpoint says of the files of two commits: each file their diff changes. - An answer with no `files` is no answer, and not an empty diff.""" + """What the compare endpoint says of two commits: the merge base it compares from, and each + file their diff changes. An answer with no `files` is no answer, and not an empty diff.""" + merge_base: str = Field(validation_alias=AliasPath("merge_base_commit", "sha")) files: list[PullRequestFile] class CompareFiles(NamedTuple): - """The files a compare answer lists, and whether the answer held GitHub's limit of - `CONST_GITHUB_COMPARE_FILES_LIMIT` files, so the list may be truncated.""" + """The files a compare answer lists, whether the answer held GitHub's limit of + `CONST_GITHUB_COMPARE_FILES_LIMIT` files, so the list may be truncated, and the merge base + commit that GitHub compared from.""" files: list[PullRequestFile] truncated: bool + merge_base: str def _read_as[M: BaseModel](model: type[M], answer: Any, *, path: str) -> M: @@ -458,11 +455,6 @@ def close_pull(self, repo: str, number: int) -> None: path = _repo_path(repo, f"pulls/{number}") self._session.rest("PATCH", path, body={"state": "closed"}) - def get_pull_files(self, repo: str, number: int) -> list[PullRequestFile]: - """Every file the pull request changes, read page by linked page.""" - path = _repo_path(repo, f"pulls/{number}/files?per_page={DEFAULT_GH_REST_PER_PAGE}") - return [_read_as(PullRequestFile, item, path=path) for item in self._session.paginate(path)] - def get_file_at(self, repo: str, path: str, ref: str) -> str | None: """A file's text at a commit; None when it is absent, binary or too large to fetch. @@ -490,32 +482,33 @@ def get_file_at(self, repo: str, path: str, ref: str) -> str | None: details={"path": endpoint[:CONST_MAX_ERROR_DETAIL_LENGTH]}, ) from exc - def get_merge_base(self, repo: str, base: str, head: str) -> str | None: - """The merge base of two commits from the compare endpoint; None when GitHub has none. + def get_compare_files(self, repo: str, base: str, head: str) -> CompareFiles: + """The files that `head` changes since its merge base with `base`, and that merge base, + from the compare endpoint. - A pull request's `base.sha` is a tip of the base branch that GitHub recorded earlier. It - can be ahead of the merge base, and GitHub does not move it when a merge commit moves the - merge base (#2530). So it is neither the merge base nor the current tip of the branch. - Only a 404 reads as None: any other failure raises the session's error. + `base` is a branch or a commit. GitHub compares from the merge base of the two, so with the + tip of a pull request's base branch this is the diff a squash merge applies (#2530). A pull + request's `base.sha` is a tip of the base branch that GitHub recorded earlier: GitHub does + not move it when a merge commit moves the merge base, and the pull request's own file list + and diff keep that stale base too. GitHub lists at most `CONST_GITHUB_COMPARE_FILES_LIMIT` + files of one comparison, so a list of that length reads as possibly truncated. A 404, for + two commits GitHub cannot compare, raises the session's not-found error. """ endpoint = _repo_path(repo, f"compare/{quote(base)}...{quote(head)}?per_page=1") - try: - comparison = self._session.rest("GET", endpoint) - except GitHubNotFoundError: - return None - return _read_as(_Comparison, comparison, path=endpoint).merge_base + compared = _read_as(_CompareFiles, self._session.rest("GET", endpoint), path=endpoint) + return CompareFiles( + files=compared.files, + truncated=len(compared.files) >= CONST_GITHUB_COMPARE_FILES_LIMIT, + merge_base=compared.merge_base, + ) - def get_compare_files(self, repo: str, base: str, head: str) -> CompareFiles: - """The files that `head` changes since its merge base with `base`, from the compare endpoint. + def get_compare_diff(self, repo: str, base: str, head: str) -> str: + """The unified diff of `head` since its merge base with `base`, from the compare endpoint. - `base` is a branch or a commit. GitHub compares from the merge base of the two, so with the - tip of a pull request's base branch this is the diff a squash merge applies (#2530). GitHub - lists at most `CONST_GITHUB_COMPARE_FILES_LIMIT` files of one comparison, so a list of that - length reads as possibly truncated. + With the merge base that `get_compare_files` gives, this is the diff of the files it lists + (#5346). GitHub sends a diff as text; any other answer raises `GitHubUnreadError`. """ - endpoint = _repo_path(repo, f"compare/{quote(base)}...{quote(head)}?per_page=1") - files = _read_as(_CompareFiles, self._session.rest("GET", endpoint), path=endpoint).files - return CompareFiles(files=files, truncated=len(files) >= CONST_GITHUB_COMPARE_FILES_LIMIT) + return self._read_diff(_repo_path(repo, f"compare/{quote(base)}...{quote(head)}")) def get_commit_pulls(self, repo: str, sha: str) -> list[CommitPull]: """Every pull request that GitHub associates with the commit `sha`, merged or not. @@ -690,7 +683,11 @@ def get_pr_diff(self, repo: str, number: int) -> str: GitHub sends a diff as text; any other answer, JSON or a body without a content type, raises `GitHubUnreadError`. A pull request with no changes returns an empty string. """ - path = _repo_path(repo, f"pulls/{number}") + return self._read_diff(_repo_path(repo, f"pulls/{number}")) + + def _read_diff(self, path: str) -> str: + """The diff GitHub serves at `path` in the diff media type, raising `GitHubUnreadError` + for an answer that is not text.""" diff = self._session.rest("GET", path, accept=CONST_GITHUB_DIFF_MEDIA_TYPE) if not isinstance(diff, str): raise GitHubUnreadError( diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 6a8c8061ce..6687f1ba8b 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -58,6 +58,11 @@ class ReviewMessages: "is read." ) fetching_pr: str = "Fetching PR #{number} from {repo}..." + pr_compare_at_file_limit: str = ( + "The compare of PR #{number} and its base branch lists {limit} files, GitHub's limit for " + "one comparison, so the review cannot read every file of the pull request. Review its " + "branch in a local checkout with `devops review branch`." + ) findings_saved: str = " ✓ findings saved → {path}" review_saved: str = "Review saved → {path}" session_not_kept: str = ( @@ -1129,6 +1134,11 @@ class AnalyzeMessages: path_not_exists: str = "Path '{path}' does not exist." git_branch_failed: str = "Could not determine active git branch." github_origin_failed: str = "Could not detect GitHub repository origin URL." + pr_compare_at_file_limit: str = ( + "The compare of PR #{number} and its base branch lists {limit} files, GitHub's limit for " + "one comparison: the analysis holds these files and can miss other files of the pull " + "request." + ) saved_metadata: str = "✓ Analysis metadata saved to [cyan]{path}[/cyan]" would_save_metadata: str = ( "[yellow][dry-run][/yellow] Would write analysis metadata to: [cyan]{path}[/cyan]" diff --git a/tests/ai/client/test_batch_2_review_defects.py b/tests/ai/client/test_batch_2_review_defects.py index ed127d42f9..4a8a4e908e 100644 --- a/tests/ai/client/test_batch_2_review_defects.py +++ b/tests/ai/client/test_batch_2_review_defects.py @@ -22,7 +22,7 @@ reset_verification_state, ) from devops_cli.config.settings import AIConfig -from devops_cli.github.client import CommitRef, PullRequest, PullRequestFile +from devops_cli.github.client import CommitRef, CompareFiles, PullRequest, PullRequestFile from devops_cli.github.session import get_github_session from devops_cli.models.ai import ChatMessage from tests.support.fakes.github import route_file @@ -133,25 +133,30 @@ def test_format_pr_review_comment_no_static_scanners_empty() -> None: def test_pr_review_conventions_loaded_from_base_ref( tmp_path: Path, github_api: GitHubApiFake ) -> None: - """Base branch conventions take precedence over PR head convention files.""" - route_file(github_api, "org/repo", "AGENTS.md", "base123", "BASE CONVENTIONS") + """Base branch conventions, at the merge base of the base branch and the head, take + precedence over PR head convention files.""" + route_file(github_api, "org/repo", "AGENTS.md", "merge123", "BASE CONVENTIONS") pull = PullRequest( title="Change the conventions", head=CommitRef(sha="head123", ref="feature", repository="fork/repo"), base=CommitRef(sha="base123", ref="main", repository="org/repo"), ) - pr_files = [ - PullRequestFile(filename=name, status=status, additions=1, changes=1) - for name, status in ( - ("AGENTS.md", "modified"), - ("src/foo.py", "modified"), - ) - ] + compared = CompareFiles( + files=[ + PullRequestFile(filename=name, status=status, additions=1, changes=1) + for name, status in ( + ("AGENTS.md", "modified"), + ("src/foo.py", "modified"), + ) + ], + truncated=False, + merge_base="merge123", + ) dest_dir = tmp_path / "target" dest_dir.mkdir() - _materialize_pr_head(get_github_session().client, "org/repo", pull, dest_dir, pr_files) + _materialize_pr_head(get_github_session().client, "org/repo", pull, dest_dir, compared) assert (dest_dir / "AGENTS.md").read_text(encoding="utf-8") == "BASE CONVENTIONS" diff --git a/tests/ai/review/test_review_path_routing.py b/tests/ai/review/test_review_path_routing.py index 0d9fde184e..74368d5b28 100644 --- a/tests/ai/review/test_review_path_routing.py +++ b/tests/ai/review/test_review_path_routing.py @@ -35,8 +35,8 @@ pull_request_file_payload, pull_request_payload, route_file, - route_merge_base, route_pull_request, + route_pull_request_changes, ) from tests.support.fakes.process import ProcessAnswer, ProcessCall from tests.support.fakes.scanners import ScannerFake @@ -252,21 +252,21 @@ def test_a_pr_review_reaches_the_personas_with_only_reviewable_files( tmp_path: Path, github_api: GitHubApiFake ) -> None: """Verify `devops review pr` pages hold only `src/app.py`, offline against the GitHub API fake.""" - route_pull_request( + pull = pull_request_payload( + title="Add the app and its paperwork", + head_sha="head", + head_repo="o/r", + base_sha="base", + base_repo="o/r", + ) + route_pull_request(github_api, "o/r", 1, pull) + route_pull_request_changes( github_api, - "o/r", - 1, - pull_request_payload( - title="Add the app and its paperwork", - head_sha="head", - head_repo="o/r", - base_sha="base", - base_repo="o/r", - ), - files=[pull_request_file_payload(rel, "added") for rel in _TEXT], + pull, + *[pull_request_file_payload(rel, "added") for rel in _TEXT], + merge_base="base", diff=_diff(tuple(_TEXT)), ) - route_merge_base(github_api, "o/r", "base", "head", "base") for rel, text in _TEXT.items(): route_file(github_api, "o/r", rel, "head", text) diff --git a/tests/ai/review/test_review_runner.py b/tests/ai/review/test_review_runner.py index 1ff1904361..25496797de 100644 --- a/tests/ai/review/test_review_runner.py +++ b/tests/ai/review/test_review_runner.py @@ -38,7 +38,11 @@ render_review_result, ) from devops_cli.review.session import ReviewSessionStore -from tests.support.fakes.github import pull_request_payload, route_pull_request +from tests.support.fakes.github import ( + pull_request_payload, + route_pull_request, + route_pull_request_changes, +) from tests.support.fakes.process import ProcessAnswer, ProcessFake from tests.support.paths import REPO_ROOT @@ -152,11 +156,12 @@ def test_prepare_content_helpers( ) assert (len(b_pages) >= 1, "feat/test" in b_title, b_target) == (True, True, "feat/test") - route_pull_request( + pull_payload = pull_request_payload(title="Mock PR Title", base_repo="owner/repo") + route_pull_request(github_api, "owner/repo", 123, pull_payload) + route_pull_request_changes( github_api, - "owner/repo", - 123, - pull_request_payload(title="Mock PR Title"), + pull_payload, + merge_base="merge789", diff="diff --git a/test.py b/test.py\n+content\n", ) pr_pages, pr_title, pull, repo, pr_base = _prepare_pr_content(123, repo_arg="owner/repo") @@ -180,11 +185,12 @@ def test_a_pr_review_with_no_repo_names_the_origin_of_the_checkout_it_gets( "git remote get-url origin", ProcessAnswer(stdout="git@github.com:example-org/app.git\n"), ) - route_pull_request( + pull_payload = pull_request_payload(title="Origin PR", base_repo="example-org/app") + route_pull_request(github_api, "example-org/app", 7, pull_payload) + route_pull_request_changes( github_api, - "example-org/app", - 7, - pull_request_payload(title="Origin PR"), + pull_payload, + merge_base="merge789", diff="diff --git a/app.py b/app.py\n+content\n", ) *_, repo, _base = _prepare_pr_content(7, checkout=checkout) diff --git a/tests/commands/test_analyze.py b/tests/commands/test_analyze.py index 25d045c6aa..c7464cbd61 100644 --- a/tests/commands/test_analyze.py +++ b/tests/commands/test_analyze.py @@ -19,6 +19,7 @@ from devops_cli.commands.analyze import ( app as analyze_app, ) +from devops_cli.config.constants import CONST_GITHUB_COMPARE_FILES_LIMIT from devops_cli.main import app from devops_cli.models.ai import AnalysisMetadata, FileAnalysisMeta from devops_cli.models.git import ChangedFile @@ -27,7 +28,9 @@ github_json, pull_request_file_payload, pull_request_payload, + route_compare_files, route_pull_request, + route_pull_request_changes, ) from tests.support.fakes.process import ProcessAnswer, ProcessCall from tests.support.github_identity import fail_the_github_lookup @@ -43,11 +46,13 @@ def _handle_remote_get_url(call: ProcessCall) -> ProcessAnswer: + """Answer `git remote get-url origin` with the GitHub URL that the checkout's config holds.""" cwd = Path(call.cwd) if call.cwd else Path.cwd() if (cwd / ".git" / "config").exists(): - cfg = (cwd / ".git" / "config").read_text(encoding="utf-8") - if "github.com" in cfg: - return ProcessAnswer(stdout="https://github.com/octocat/Hello-World.git\n") + for line in (cwd / ".git" / "config").read_text(encoding="utf-8").splitlines(): + key, _, url = line.strip().partition(" = ") + if key == "url" and "github.com" in url: + return ProcessAnswer(stdout=f"{url}\n") return ProcessAnswer(returncode=128, stderr="error: No such remote 'origin'\n") @@ -392,12 +397,10 @@ def test_ai_analyze_branch_and_pr_execution( src_dir.mkdir() worker_file = src_dir / "worker.py" worker_file.write_text("def do_work(): pass\n", encoding="utf-8") - route_pull_request( - github_api, - "org/repo", - 42, - pull_request_payload(title="Add worker"), - files=[pull_request_file_payload("src/worker.py")], + pull = pull_request_payload(title="Add worker", base_repo="org/repo") + route_pull_request(github_api, "org/repo", 42, pull) + route_pull_request_changes( + github_api, pull, pull_request_file_payload("src/worker.py"), merge_base="merge789" ) git_fake.answer( @@ -423,7 +426,7 @@ def test_ai_analyze_branch_and_pr_execution( assert github_api.requested == [ "GET https://api.github.com/repos/org/repo/pulls/42", - "GET https://api.github.com/repos/org/repo/pulls/42/files?per_page=100", + "GET https://api.github.com/repos/org/repo/compare/main...abc123?per_page=1", ] @@ -616,12 +619,13 @@ def test_analyze_pr_command( sample_file = tmp_path / "pr_mod.py" sample_file.write_text("def pr_func(): pass\n", encoding="utf-8") - route_pull_request( + pull = pull_request_payload(title="Add feature", base_repo="owner/repo") + route_pull_request(github_api, "owner/repo", 42, pull) + route_pull_request_changes( github_api, - "owner/repo", - 42, - pull_request_payload(title="Add feature"), - files=[pull_request_file_payload("pr_mod.py", additions=5, changes=5)], + pull, + pull_request_file_payload("pr_mod.py", additions=5, changes=5), + merge_base="merge789", ) git_fake.answer( @@ -634,46 +638,51 @@ def test_analyze_pr_command( assert res_pr_ok.exit_code == 0 -def test_analyze_pr_lists_the_title_and_the_files_of_every_page( +def _a_checkout_of(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, repo: str) -> None: + """Work in a checkout under `tmp_path` whose origin is `repo` on GitHub, and keep the + analysis under `tmp_path`.""" + root = tmp_path / "checkout" + (root / ".git").mkdir(parents=True) + (root / ".git" / "config").write_text( + f'[remote "origin"]\n\turl = https://github.com/{repo}.git\n', encoding="utf-8" + ) + monkeypatch.chdir(root) + monkeypatch.setenv("DEVOPS_CLI_DATA_ANALYSIS_DIR", str(tmp_path / "analysis")) + + +def _saved_analysis(tmp_path: Path, number: int) -> AnalysisMetadata: + """The analysis of pull request `number` that the command saved under `tmp_path`.""" + return AnalysisMetadata.model_validate_json( + (tmp_path / "analysis" / f"pr-{number}-metadata.json").read_text(encoding="utf-8") + ) + + +def test_analyze_pr_lists_the_title_and_the_files_of_the_recorded_comparison( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, github_api: GitHubApiFake, pin_github_session: str, ) -> None: - """For the recorded pull request, whose second page of files GitHub links, the analysis holds - the pull request's title and both changed files, with the token of the session on every read.""" + """For the recorded pull request, the analysis holds the pull request's title and both files + of the recorded compare of its base branch and its head commit, with the token of the session + on every read.""" recorded = json.loads( (FIXTURES / "github" / "hello_world_pull_request.json").read_text(encoding="utf-8") ) - first, second = recorded["files_pages"] + head = recorded["pull_request"]["head"]["sha"] github_api.route( "GET", "/repos/octocat/Hello-World/pulls/158", github_json(recorded["pull_request"]) ) github_api.route( "GET", - "/repos/octocat/Hello-World/pulls/158/files?per_page=100", - github_json(first["body"], headers={"link": first["link"]}), - ) - github_api.route( - "GET", - "/repositories/1296269/pulls/158/files?per_page=1&page=2", - github_json(second["body"], headers={"link": second["link"]}), + f"/repos/octocat/Hello-World/compare/master...{head}?per_page=1", + github_json(recorded["branch_comparison"]), ) - root = tmp_path / "checkout" - root.mkdir() - (root / ".git").mkdir(parents=True, exist_ok=True) - (root / ".git" / "config").write_text( - '[remote "origin"]\n\turl = https://github.com/octocat/Hello-World.git\n', - encoding="utf-8", - ) - monkeypatch.chdir(root) - monkeypatch.setenv("DEVOPS_CLI_DATA_ANALYSIS_DIR", str(tmp_path / "analysis")) + _a_checkout_of(tmp_path, monkeypatch, "octocat/Hello-World") result = runner.invoke(analyze_app, ["pr", "158", "--no-enhanced"]) - saved = AnalysisMetadata.model_validate_json( - (tmp_path / "analysis" / "pr-158-metadata.json").read_text(encoding="utf-8") - ) + saved = _saved_analysis(tmp_path, 158) assert ( result.exit_code, saved.project.title, @@ -684,12 +693,77 @@ def test_analyze_pr_lists_the_title_and_the_files_of_every_page( 0, "checkout PR #158 analysis: Update and rename README to README.md. Also Added Bolding", [("README", "removed"), ("README.md", "added")], - 3, + 2, {f"token {pin_github_session}"}, ) -@pytest.mark.parametrize("unreadable", ["the pull request", "its files"]) +def test_analyze_pr_reads_the_files_at_the_merge_base_of_its_base_branch( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, github_api: GitHubApiFake +) -> None: + """A merge of the base branch into the pull request moved its merge base, and GitHub kept + the payload's `base.sha` and the pulls files list at the old base (#5346). The analysis holds + the files of the compare of the base branch and the head commit, and no request names + `base.sha` or the pulls files path.""" + pull = pull_request_payload(base_sha="stale456", base_repo="owner/repo") + route_pull_request( + github_api, + "owner/repo", + 42, + pull, + files=[pull_request_file_payload("pr_mod.py"), pull_request_file_payload("main_only.py")], + ) + route_pull_request_changes( + github_api, pull, pull_request_file_payload("pr_mod.py"), merge_base="merge789" + ) + _a_checkout_of(tmp_path, monkeypatch, "owner/repo") + + result = runner.invoke(analyze_app, ["pr", "42", "--no-enhanced"]) + + assert ( + result.exit_code, + [meta.path for meta in _saved_analysis(tmp_path, 42).files], + github_api.requested, + ) == ( + 0, + ["pr_mod.py"], + [ + "GET https://api.github.com/repos/owner/repo/pulls/42", + "GET https://api.github.com/repos/owner/repo/compare/main...abc123?per_page=1", + ], + ) + + +def test_analyze_pr_warns_that_a_comparison_at_the_file_limit_can_miss_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, github_api: GitHubApiFake +) -> None: + """GitHub lists at most `CONST_GITHUB_COMPARE_FILES_LIMIT` files of one comparison. The + analysis of a list at that limit holds the listed files, and a warning names the limit.""" + pull = pull_request_payload(base_repo="owner/repo") + route_pull_request(github_api, "owner/repo", 42, pull) + route_compare_files( + github_api, + "owner/repo", + "main", + "abc123", + *[ + pull_request_file_payload(f"src/{number}.py") + for number in range(CONST_GITHUB_COMPARE_FILES_LIMIT) + ], + merge_base="merge789", + ) + _a_checkout_of(tmp_path, monkeypatch, "owner/repo") + + result = runner.invoke(analyze_app, ["pr", "42", "--no-enhanced"]) + + assert ( + result.exit_code, + len(_saved_analysis(tmp_path, 42).files), + f"{CONST_GITHUB_COMPARE_FILES_LIMIT} files" in " ".join(result.output.split()), + ) == (0, CONST_GITHUB_COMPARE_FILES_LIMIT, True) + + +@pytest.mark.parametrize("unreadable", ["the pull request", "its comparison"]) def test_analyze_pr_ends_with_the_github_error_when_the_pull_request_cannot_be_read( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -697,26 +771,21 @@ def test_analyze_pr_ends_with_the_github_error_when_the_pull_request_cannot_be_r github_api: GitHubApiFake, unreadable: str, ) -> None: - """A 500 that outlasts the retries, on the pull request or on its files, ends the command with - the session's message and status 1, and prints no traceback.""" + """A 500 that outlasts the retries, on the pull request or on the compare of its base branch + and its head, ends the command with the session's message and status 1, and prints no + traceback.""" recorded = json.loads( (FIXTURES / "github" / "hello_world_pull_request.json").read_text(encoding="utf-8") ) - pull = "/repos/octocat/Hello-World/pulls/158" + repo = "/repos/octocat/Hello-World" + head = recorded["pull_request"]["head"]["sha"] failure = github_json({"message": "Server Error"}, status=500) if unreadable == "the pull request": - github_api.route("GET", pull, failure) + github_api.route("GET", f"{repo}/pulls/158", failure) else: - github_api.route("GET", pull, github_json(recorded["pull_request"])) - github_api.route("GET", f"{pull}/files?per_page=100", failure) - root = tmp_path / "checkout" - root.mkdir() - (root / ".git").mkdir(parents=True, exist_ok=True) - (root / ".git" / "config").write_text( - '[remote "origin"]\n\turl = https://github.com/octocat/Hello-World.git\n', - encoding="utf-8", - ) - monkeypatch.chdir(root) + github_api.route("GET", f"{repo}/pulls/158", github_json(recorded["pull_request"])) + github_api.route("GET", f"{repo}/compare/master...{head}?per_page=1", failure) + _a_checkout_of(tmp_path, monkeypatch, "octocat/Hello-World") result = cli("ai", "analyze", "pr", "158", "--no-enhanced") diff --git a/tests/commands/test_review_pr_post.py b/tests/commands/test_review_pr_post.py index 642f91c66e..35b8d783e2 100644 --- a/tests/commands/test_review_pr_post.py +++ b/tests/commands/test_review_pr_post.py @@ -15,6 +15,7 @@ pull_request_file_payload, pull_request_payload, route_pull_request, + route_pull_request_changes, ) if TYPE_CHECKING: @@ -162,16 +163,11 @@ def test_comment_with_findings_renders_findings_and_model_notes() -> None: def _route_the_pull_request( api: GitHubApiFake, *, files: list[dict[str, Any]], diff: str, comments: bool ) -> None: - """Serve pull request 42 of org/repo, with `files` and `diff`; with `comments`, GitHub also - accepts a comment on it.""" - route_pull_request( - api, - "org/repo", - 42, - pull_request_payload(title="Test PR", head_repo="org/repo", base_repo="org/repo"), - files=files, - diff=diff, - ) + """Serve pull request 42 of org/repo, whose compare with its base branch holds `files` and + `diff`; with `comments`, GitHub also accepts a comment on it.""" + pull = pull_request_payload(title="Test PR", head_repo="org/repo", base_repo="org/repo") + route_pull_request(api, "org/repo", 42, pull) + route_pull_request_changes(api, pull, *files, merge_base="merge789", diff=diff) if comments: api.route("POST", "/repos/org/repo/issues/42/comments", github_json({"id": 1}, status=201)) @@ -271,39 +267,11 @@ def _post_the_review_without_a_model(cli: Callable[..., Any]) -> Any: return cli("review", "pr", "42", "--repo", "org/repo", "--post", "--no-group-analysis") -def test_devops_review_pr_post_stops_when_the_files_of_the_pull_request_cannot_be_read( - cli: Callable[..., Any], github_api: GitHubApiFake -) -> None: - """A diff of routed files names no file, so the comment lists the pull request's files. When - GitHub fails that second read, the command exits 1 and posts nothing: a comment that names - no file would look like a review of an empty change.""" - _route_the_pull_request( - github_api, - files=[pull_request_file_payload("openspec/changes/1-x/tasks.md", "added")], - diff="diff --git a/openspec/changes/1-x/tasks.md b/openspec/changes/1-x/tasks.md\n+- [x] Done.\n", - comments=True, - ) - files = "/repos/org/repo/pulls/42/files?per_page=100" - github_api.route( - "GET", - files, - github_json([pull_request_file_payload("openspec/changes/1-x/tasks.md", "added")]), - github_json({"message": "Server Error"}, status=500), - ) - - result = _post_the_review_without_a_model(cli) - - assert result.exit_code == 1 - assert isinstance(result.exception, SystemExit) - assert _posted(github_api) == [] - assert "(HTTP 500)" in result.output - - def test_devops_review_pr_post_names_the_files_the_pull_request_leaves_in_place( cli: Callable[..., Any], github_api: GitHubApiFake ) -> None: - """A diff of routed files names no file, so the comment lists the pull request's files, and a - file the pull request removes is not one of the files checked.""" + """A diff of routed files names no file, so the comment lists the files of the compare that + the review read, and a file the pull request removes is not one of the files checked.""" _route_the_pull_request( github_api, files=[ diff --git a/tests/commands/test_review_scope.py b/tests/commands/test_review_scope.py index 2f2ef45baa..a4c8884d49 100644 --- a/tests/commands/test_review_scope.py +++ b/tests/commands/test_review_scope.py @@ -1,5 +1,5 @@ """A review reads the code under review: the PR's own files, each file's own pages, every lockfile -(#515), and the PR's base at its merge base (#593).""" +(#515), and the PR's base at the merge base of its base branch (#593, #5346).""" from __future__ import annotations @@ -26,17 +26,20 @@ run_orchestrator_review, ) from devops_cli.ai.review_schema import SavedFinding -from devops_cli.github.client import CommitRef, PullRequest, PullRequestFile +from devops_cli.config.constants import CONST_GITHUB_COMPARE_FILES_LIMIT +from devops_cli.github.client import CommitRef, CompareFiles, PullRequest, PullRequestFile from devops_cli.github.session import get_github_session from devops_cli.models.git import ChangedFile +from devops_cli.review.diff import diff_file_names from tests.support.fakes.github import ( github_json, - github_text, pull_request_file_payload, pull_request_payload, + route_compare_diff, + route_compare_files, route_file, - route_merge_base, route_pull_request, + route_pull_request_changes, ) from tests.support.paths import FIXTURES @@ -57,6 +60,11 @@ def _pull() -> PullRequest: ) +def _compared(*files: PullRequestFile) -> CompareFiles: + """The compare of the base branch of `_pull()` and its head: `files`, from `_MERGE_BASE`.""" + return CompareFiles(files=list(files), truncated=False, merge_base=_MERGE_BASE) + + def _read_in(api: GitHubApiFake, repo: str) -> list[tuple[str, str]]: """The path and ref of each file of `repo` the fake was asked for, in order.""" contents = f"/repos/{repo}/contents/" @@ -71,24 +79,25 @@ def test_a_pr_checkout_carries_no_review_guards_file_from_the_base( tmp_path: Path, github_api: GitHubApiFake, pin_github_session: str ) -> None: """Verify a pull request checkout takes `AGENTS.md` from the base and no `.devops/review.md` (#1916).""" - route_file(github_api, "base/app", "AGENTS.md", "base456", "# Conventions\n") - route_file(github_api, "base/app", ".devops/review.md", "base456", "# Review rules\n") + route_file(github_api, "base/app", "AGENTS.md", _MERGE_BASE, "# Conventions\n") + route_file(github_api, "base/app", ".devops/review.md", _MERGE_BASE, "# Review rules\n") - _materialize_pr_head(get_github_session().client, "base/app", _pull(), tmp_path, []) + _materialize_pr_head(get_github_session().client, "base/app", _pull(), tmp_path, _compared()) assert ( (tmp_path / "AGENTS.md").read_text(encoding="utf-8"), (tmp_path / ".devops/review.md").exists(), - (".devops/review.md", "base456") in _read_in(github_api, "base/app"), + (".devops/review.md", _MERGE_BASE) in _read_in(github_api, "base/app"), ) == ("# Conventions\n", False, False) def test_a_pr_review_reads_the_pr_heads_files_and_conventions( tmp_path: Path, github_api: GitHubApiFake, pin_github_session: str ) -> None: - """Verify changed files are written from head repo, and conventions are safely loaded from base (#658).""" + """Verify changed files are written from head repo, and conventions are safely loaded from + the base at the merge base (#658, #5346).""" route_file(github_api, "fork/app", "src/app.py", "abc123", "print('head version')\n") - route_file(github_api, "base/app", "AGENTS.md", "base456", "# Conventions\n") + route_file(github_api, "base/app", "AGENTS.md", _MERGE_BASE, "# Conventions\n") files = [ PullRequestFile(filename=name, status=status, additions=1, changes=1) for name, status in ( @@ -99,7 +108,7 @@ def test_a_pr_review_reads_the_pr_heads_files_and_conventions( ] written = _materialize_pr_head( - get_github_session().client, "base/app", _pull(), tmp_path, files + get_github_session().client, "base/app", _pull(), tmp_path, _compared(*files) ) assert ( @@ -131,23 +140,23 @@ def test_the_pr_command_reviews_against_the_pr_head( """Verify the review's target directory holds the PR head's files, not the local checkout.""" from tests.support.fakes.model import LLMResponse - route_pull_request( + pull = pull_request_payload( + title="Change the app", + head_sha="abc123", + base_sha="base456", + head_repo="fork/app", + base_repo="base/app", + ) + route_pull_request(github_api, "base/app", 7, pull) + route_pull_request_changes( github_api, - "base/app", - 7, - pull_request_payload( - title="Change the app", - head_sha="abc123", - base_sha="base456", - head_repo="fork/app", - base_repo="base/app", - ), - files=[pull_request_file_payload("app.py", "added")], + pull, + pull_request_file_payload("app.py", "added"), + merge_base=_MERGE_BASE, diff="diff --git a/app.py b/app.py\n--- /dev/null\n+++ b/app.py\n@@ -0,0 +1 @@\n+head\n", ) route_file(github_api, "fork/app", "app.py", "abc123", "head\n") - route_file(github_api, "base/app", "AGENTS.md", "base456", "# Conventions\n") - route_merge_base(github_api, "base/app", "base456", "abc123", _MERGE_BASE) + route_file(github_api, "base/app", "AGENTS.md", _MERGE_BASE, "# Conventions\n") model_fake.answer(LLMResponse(content="[]", model="fake-model")) @@ -161,32 +170,27 @@ def test_the_pr_command_reviews_against_the_pr_head( assert "Files Reviewed 1" in result.stdout -def test_a_pr_review_of_the_recorded_pull_request_reads_both_pages_of_files( +def test_a_pr_review_of_the_recorded_pull_request_reads_the_compare_of_its_base_branch( tmp_path: Path, github_api: GitHubApiFake, pin_github_session: str ) -> None: - """The recorded pull request lists its files on two pages, and its fork was deleted, so GitHub - reports its head repository as null: the review has the title and both files, and reads the - head's text from the base repository, at the head commit.""" + """The recorded compare of the base branch and the head commit lists both files of the pull + request, whose fork was deleted, so GitHub reports its head repository as null: the review has + the title and both files, and reads the head's text from the base repository, at the head + commit.""" recorded = json.loads( (FIXTURES / "github" / "hello_world_pull_request.json").read_text(encoding="utf-8") ) - first, second = recorded["files_pages"] + comparison = recorded["branch_comparison"] repo = "octocat/Hello-World" + github_api.route("GET", f"/repos/{repo}/pulls/158", github_json(recorded["pull_request"])) github_api.route( "GET", - f"/repos/{repo}/pulls/158", - github_json(recorded["pull_request"]), - github_text("diff --git a/README.md b/README.md\n+x\n", media_type="text/plain"), + f"/repos/{repo}/compare/master...{_HEAD_OF_158}?per_page=1", + github_json(comparison), ) - github_api.route( - "GET", - f"/repos/{repo}/pulls/158/files?per_page=100", - github_json(first["body"], headers={"link": first["link"]}), - ) - github_api.route( - "GET", - "/repositories/1296269/pulls/158/files?per_page=1&page=2", - github_json(second["body"], headers={"link": second["link"]}), + merge_base = comparison["merge_base_commit"]["sha"] + route_compare_diff( + github_api, repo, merge_base, _HEAD_OF_158, "diff --git a/README.md b/README.md\n+x\n" ) route_file(github_api, repo, "README.md", _HEAD_OF_158, "**Hello World!**\n") @@ -197,6 +201,7 @@ def test_a_pr_review_of_the_recorded_pull_request_reads_both_pages_of_files( title, pull.head.repository, base_revision.changes, + base_revision.revision, (tmp_path / "README.md").read_text(encoding="utf-8"), [path for path, ref in _read_in(github_api, repo) if ref == _HEAD_OF_158], {request.headers["authorization"] for request in github_api.sent}, @@ -207,36 +212,132 @@ def test_a_pr_review_of_the_recorded_pull_request_reads_both_pages_of_files( ChangedFile(change_type="deleted", path="README"), ChangedFile(change_type="added", path="README.md"), ), + merge_base, "**Hello World!**\n", ["README.md"], {f"token {pin_github_session}"}, ) +def test_a_pr_review_reads_the_changes_at_the_merge_base_of_its_base_branch( + tmp_path: Path, github_api: GitHubApiFake +) -> None: + """A merge of the base branch into the pull request moved its merge base, and GitHub kept + the payload's `base.sha` and the file list of the pulls endpoints at the old base (#5346). + The review reads the files and the diff of the compare of the base branch and the head + commit, and the base text and the conventions at the merge base of that compare. No request + names `base.sha` or the pulls files path, and the diff of the pulls endpoint is not read.""" + pull = pull_request_payload(base_sha="stale456") + route_pull_request( + github_api, + "base/app", + 7, + pull, + files=[pull_request_file_payload("mod.py"), pull_request_file_payload("main_only.py")], + diff="diff --git a/main_only.py b/main_only.py\n@@ -1 +1 @@\n-y = 1\n+y = 2\n", + ) + route_pull_request_changes( + github_api, + pull, + pull_request_file_payload("mod.py"), + merge_base=_MERGE_BASE, + diff="diff --git a/mod.py b/mod.py\n@@ -1 +1 @@\n-x = 1\n+x = 2\n", + ) + route_file(github_api, "fork/app", "mod.py", "abc123", "x = 2\n") + for ref, mod, conventions in ( + (_MERGE_BASE, "x = 1\n", "# Conventions at the merge base\n"), + ("stale456", "x = 0\n", "# Conventions at the stale base\n"), + ): + route_file(github_api, "base/app", "mod.py", ref, mod) + route_file(github_api, "base/app", "AGENTS.md", ref, conventions) + + pages, _title, _pull, _repo, base_revision = _prepare_pr_content( + 7, "base/app", head_dir=tmp_path + ) + + assert base_revision is not None + assert ( + [name for page in pages for name in diff_file_names(page)], + base_revision.changes, + base_revision.read("mod.py"), + base_revision.revision, + (tmp_path / "AGENTS.md").read_text(encoding="utf-8"), + (tmp_path / "main_only.py").exists(), + [request for request in github_api.requested if "/contents/" not in request], + {ref for _path, ref in _read_in(github_api, "base/app")}, + ) == ( + ["mod.py"], + (ChangedFile(change_type="modified", path="mod.py"),), + "x = 1\n", + _MERGE_BASE, + "# Conventions at the merge base\n", + False, + [ + "GET https://api.github.com/repos/base/app/pulls/7", + "GET https://api.github.com/repos/base/app/compare/main...abc123?per_page=1", + f"GET https://api.github.com/repos/base/app/compare/{_MERGE_BASE}...abc123", + ], + {_MERGE_BASE}, + ) + + +def test_a_pr_review_refuses_a_comparison_at_the_file_limit( + cli: Callable[..., Any], github_api: GitHubApiFake +) -> None: + """GitHub lists at most `CONST_GITHUB_COMPARE_FILES_LIMIT` files of one comparison. A list at + that limit can miss files of the pull request, and the review would miss their changes: the + command ends with status 1 and a message that names the limit, and reads no diff.""" + route_pull_request(github_api, "base/app", 7, pull_request_payload()) + route_compare_files( + github_api, + "base/app", + "main", + "abc123", + *[ + pull_request_file_payload(f"src/{number}.py") + for number in range(CONST_GITHUB_COMPARE_FILES_LIMIT) + ], + merge_base=_MERGE_BASE, + ) + + result = cli("review", "pr", "7", "--repo", "base/app", "--pre-analysis-only") + + output = " ".join(result.output.split()) + assert ( + result.exit_code, + f"{CONST_GITHUB_COMPARE_FILES_LIMIT} files" in output, + "devops review branch" in output, + [request for request in github_api.requested if "/compare/" in request], + ) == ( + 1, + True, + True, + ["GET https://api.github.com/repos/base/app/compare/main...abc123?per_page=1"], + ) + + def test_a_pr_review_reads_the_base_at_the_merge_base_and_records_the_delta( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, github_api: GitHubApiFake ) -> None: """Verify a PR review reads each modified or renamed Python file from the base repository at the merge base, a renamed one at its old path, and records the delta in the session (#593). - `pull.base.sha` is the base branch's tip: read there, symbols added on the base since the - branch point would count as removed by the PR. + `pull.base.sha` is a tip of the base branch that GitHub recorded earlier: read there, symbols + added on the base since the branch point would count as removed by the PR. """ monkeypatch.setenv("DEVOPS_CLI_DATA_ANALYSIS_DIR", str(tmp_path / "analysis")) - route_pull_request( + pull = pull_request_payload() + route_pull_request(github_api, "base/app", 7, pull) + route_pull_request_changes( github_api, - "base/app", - 7, - pull_request_payload(), - files=[ - pull_request_file_payload("mod.py", "modified"), - pull_request_file_payload("new_name.py", "renamed", previous_filename="old_name.py"), - pull_request_file_payload("added.py", "added"), - pull_request_file_payload("gone.py", "removed"), - ], + pull, + pull_request_file_payload("mod.py", "modified"), + pull_request_file_payload("new_name.py", "renamed", previous_filename="old_name.py"), + pull_request_file_payload("added.py", "added"), + pull_request_file_payload("gone.py", "removed"), + merge_base=_MERGE_BASE, diff="diff --git a/mod.py b/mod.py\n@@ -1,5 +1,2 @@\n-def legacy_helper():\n", ) - route_merge_base(github_api, "base/app", "base456", "abc123", _MERGE_BASE) for repo, path, ref, text in ( ("fork/app", "mod.py", "abc123", "def keep():\n return 1\n"), ( @@ -294,7 +395,10 @@ def test_a_pr_review_reads_the_base_at_the_merge_base_and_records_the_delta( } compared = [r for r in github_api.requested if "/compare/" in r] assert (compared, source_base_reads, deltas) == ( - ["GET https://api.github.com/repos/base/app/compare/base456...abc123?per_page=1"], + [ + "GET https://api.github.com/repos/base/app/compare/main...abc123?per_page=1", + f"GET https://api.github.com/repos/base/app/compare/{_MERGE_BASE}...abc123", + ], [("mod.py", _MERGE_BASE), ("old_name.py", _MERGE_BASE)], { "mod.py": ([], ["legacy_helper"], ["keep"]), @@ -308,17 +412,17 @@ def test_a_pr_review_reads_the_merge_base_from_the_base_repository_the_pull_requ tmp_path: Path, github_api: GitHubApiFake ) -> None: """GitHub serves a pull request under the old name of a renamed repository, and reports the - base repository by its full name: the merge base and the base files are read there, not under + base repository by its full name: the comparison and the base files are read there, not under the name the review was asked for.""" - route_pull_request( + pull = pull_request_payload() + route_pull_request(github_api, "old/app", 7, pull) + route_pull_request_changes( github_api, - "old/app", - 7, - pull_request_payload(), - files=[pull_request_file_payload("mod.py")], + pull, + pull_request_file_payload("mod.py"), + merge_base=_MERGE_BASE, diff="diff --git a/mod.py b/mod.py\n@@ -1 +1 @@\n-x = 1\n+x = 2\n", ) - route_merge_base(github_api, "base/app", "base456", "abc123", _MERGE_BASE) route_file(github_api, "fork/app", "mod.py", "abc123", "x = 2\n") route_file(github_api, "base/app", "mod.py", _MERGE_BASE, "x = 1\n") @@ -331,22 +435,25 @@ def test_a_pr_review_reads_the_merge_base_from_the_base_repository_the_pull_requ _read_in(github_api, "old/app"), ) == ( "x = 1\n", - ["GET https://api.github.com/repos/base/app/compare/base456...abc123?per_page=1"], + [ + "GET https://api.github.com/repos/base/app/compare/main...abc123?per_page=1", + f"GET https://api.github.com/repos/base/app/compare/{_MERGE_BASE}...abc123", + ], [], ) def _route_a_modified_python_file(api: GitHubApiFake) -> None: """Serve pull request 7 of base/app, which modifies mod.py, with its head text and merge base.""" - route_pull_request( + pull = pull_request_payload() + route_pull_request(api, "base/app", 7, pull) + route_pull_request_changes( api, - "base/app", - 7, - pull_request_payload(), - files=[pull_request_file_payload("mod.py")], + pull, + pull_request_file_payload("mod.py"), + merge_base=_MERGE_BASE, diff="diff --git a/mod.py b/mod.py\n@@ -1 +1 @@\n-x = 1\n+x = 2\n", ) - route_merge_base(api, "base/app", "base456", "abc123", _MERGE_BASE) route_file(api, "fork/app", "mod.py", "abc123", "x = 2\n") diff --git a/tests/fixtures/github/hello_world_pull_request.json b/tests/fixtures/github/hello_world_pull_request.json index 6cb18301a1..445e6be7c6 100644 --- a/tests/fixtures/github/hello_world_pull_request.json +++ b/tests/fixtures/github/hello_world_pull_request.json @@ -1,5 +1,5 @@ { - "about": "GitHub's answers about pull request 158 of octocat/Hello-World, GitHub's own example repository, read on 2026-10-22 with a read-only token. The pull request has two changed files and a head repository that was deleted (`head.repo` is null). The files are the two pages of `GET /repos/octocat/Hello-World/pulls/158/files?per_page=1`, with the `Link` header GitHub sent with each, so the listing needs a second request. The pull request lost the objects that name people (its author and its head's), `head.label` and the empty lists of assignees and reviewers; the comparison kept only the merge base commit, without its authors; every other field is as GitHub sent it.", + "about": "GitHub's answers about pull request 158 of octocat/Hello-World, GitHub's own example repository, read on 2026-10-22 with a read-only token. The pull request has two changed files and a head repository that was deleted (`head.repo` is null). The pull request lost the objects that name people (its author and its head's), `head.label` and the empty lists of assignees and reviewers; the comparison kept only the merge base commit, without its authors; every other field is as GitHub sent it. `branch_comparison` is the answer to `GET /repos/octocat/Hello-World/compare/master...ec18ca7bca5202d8e139a58b25757dc161255245?per_page=1`, read on 2026-11-13: the compare of the tip of the base branch and the head commit, which lists the two changed files. It lost its list of commits and kept only the sha of its merge base commit; its other fields are as GitHub sent them.", "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/158", "id": 18272016, @@ -202,42 +202,6 @@ "deletions": 1, "changed_files": 2 }, - "files_pages": [ - { - "link": "; rel=\"next\", ; rel=\"last\"", - "body": [ - { - "sha": "980a0d5f19a64b4b30a87d4206aade58726b60e3", - "filename": "README", - "status": "removed", - "additions": 0, - "deletions": 1, - "changes": 1, - "blob_url": "https://github.com/octocat/Hello-World/blob/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README", - "raw_url": "https://github.com/octocat/Hello-World/raw/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README", - "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/README?ref=7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", - "patch": "@@ -1 +0,0 @@\n-Hello World!" - } - ] - }, - { - "link": "; rel=\"prev\", ; rel=\"first\"", - "body": [ - { - "sha": "c6ec10f5e39efe7479feb317b299e93cca5b9129", - "filename": "README.md", - "status": "added", - "additions": 1, - "deletions": 0, - "changes": 1, - "blob_url": "https://github.com/octocat/Hello-World/blob/ec18ca7bca5202d8e139a58b25757dc161255245/README.md", - "raw_url": "https://github.com/octocat/Hello-World/raw/ec18ca7bca5202d8e139a58b25757dc161255245/README.md", - "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/README.md?ref=ec18ca7bca5202d8e139a58b25757dc161255245", - "patch": "@@ -0,0 +1 @@\n+**Hello World!**" - } - ] - } - ], "comparison": { "url": "https://api.github.com/repos/octocat/Hello-World/compare/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d...ec18ca7bca5202d8e139a58b25757dc161255245", "html_url": "https://github.com/octocat/Hello-World/compare/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d...ec18ca7bca5202d8e139a58b25757dc161255245", @@ -263,6 +227,43 @@ } } }, + "branch_comparison": { + "url": "https://api.github.com/repos/octocat/Hello-World/compare/master...ec18ca7bca5202d8e139a58b25757dc161255245", + "html_url": "https://github.com/octocat/Hello-World/compare/master...ec18ca7bca5202d8e139a58b25757dc161255245", + "status": "ahead", + "ahead_by": 1, + "behind_by": 0, + "total_commits": 1, + "merge_base_commit": { + "sha": "7fd1a60b01f91b314f59955a4e4d4e80d8edf11d" + }, + "files": [ + { + "additions": 0, + "blob_url": "https://github.com/octocat/Hello-World/blob/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README", + "changes": 1, + "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/README?ref=7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", + "deletions": 1, + "filename": "README", + "patch": "@@ -1 +0,0 @@\n-Hello World!", + "raw_url": "https://github.com/octocat/Hello-World/raw/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README", + "sha": "980a0d5f19a64b4b30a87d4206aade58726b60e3", + "status": "removed" + }, + { + "additions": 1, + "blob_url": "https://github.com/octocat/Hello-World/blob/ec18ca7bca5202d8e139a58b25757dc161255245/README.md", + "changes": 1, + "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/README.md?ref=ec18ca7bca5202d8e139a58b25757dc161255245", + "deletions": 0, + "filename": "README.md", + "patch": "@@ -0,0 +1 @@\n+**Hello World!**", + "raw_url": "https://github.com/octocat/Hello-World/raw/ec18ca7bca5202d8e139a58b25757dc161255245/README.md", + "sha": "c6ec10f5e39efe7479feb317b299e93cca5b9129", + "status": "added" + } + ] + }, "readme_contents": { "name": "README", "path": "README", diff --git a/tests/git/test_ai_task_metadata.py b/tests/git/test_ai_task_metadata.py index 5c6148d8a5..7c9e77f59a 100644 --- a/tests/git/test_ai_task_metadata.py +++ b/tests/git/test_ai_task_metadata.py @@ -18,6 +18,7 @@ pull_request_file_payload, pull_request_payload, route_pull_request, + route_pull_request_changes, ) if TYPE_CHECKING: @@ -141,12 +142,10 @@ def test_metadata_task_model_override_used_by_analyze_branch_and_pr( src_dir.mkdir() worker_file = src_dir / "worker.py" worker_file.write_text("def do_work(): pass\n", encoding="utf-8") - route_pull_request( - github_api, - "org/repo", - 42, - pull_request_payload(title="Add worker"), - files=[pull_request_file_payload("src/worker.py")], + pull = pull_request_payload(title="Add worker", base_repo="org/repo") + route_pull_request(github_api, "org/repo", 42, pull) + route_pull_request_changes( + github_api, pull, pull_request_file_payload("src/worker.py"), merge_base="merge789" ) recorded_configs: list[AIConfig] = [] diff --git a/tests/git/test_review_worktree_regression.py b/tests/git/test_review_worktree_regression.py index 93e11058d2..ac3f1accc9 100644 --- a/tests/git/test_review_worktree_regression.py +++ b/tests/git/test_review_worktree_regression.py @@ -304,8 +304,6 @@ def test_run_pr_review_workflow_partial_context(tmp_path: Path) -> None: from devops_cli.commands.review import _run_pr_review_workflow - pull = MagicMock() - pull.base.sha = "base-sha" head_dir = tmp_path / "head_dir" head_dir.mkdir() @@ -316,7 +314,6 @@ def test_run_pr_review_workflow_partial_context(tmp_path: Path) -> None: result = _run_pr_review_workflow( pages=["page1"], title="PR #42: Test", - pull=pull, number=42, head_dir=head_dir, base_revision=None, @@ -337,14 +334,15 @@ def test_run_pr_review_workflow_partial_context(tmp_path: Path) -> None: def test_run_pr_review_workflow_with_worktree(tmp_path: Path) -> None: - """When fetch_pr_head succeeds, review runs against detached worktree with partial_context=False.""" + """When fetch_pr_head succeeds, review runs against detached worktree with partial_context=False, + and the base worktree is at the merge base that the base revision names (#5346).""" from unittest.mock import MagicMock, patch + from devops_cli.ai.analyze.symbols import BaseRevision from devops_cli.commands.review import _run_pr_review_workflow from devops_cli.git.worktree import ReviewWorktrees - pull = MagicMock() - pull.base.sha = "base-sha" + base_revision = BaseRevision(changes=(), read=lambda _path: None, revision="merge-sha") head_dir = tmp_path / "head_dir" head_dir.mkdir() wt_dir = tmp_path / "commit_wt" @@ -361,10 +359,9 @@ def test_run_pr_review_workflow_with_worktree(tmp_path: Path) -> None: result = _run_pr_review_workflow( pages=["page1"], title="PR #42: Test", - pull=pull, number=42, head_dir=head_dir, - base_revision=None, + base_revision=base_revision, summary=False, clients=MagicMock(), stage_flags=MagicMock(), @@ -378,4 +375,8 @@ def test_run_pr_review_workflow_with_worktree(tmp_path: Path) -> None: assert result == [] mock_exec.assert_called_once() _, kwargs = mock_exec.call_args - assert (kwargs["partial_context"], kwargs["target_dir"]) == (False, wt_dir) + assert ( + kwargs["partial_context"], + kwargs["target_dir"], + mock_ctx.call_args.kwargs["base_rev"], + ) == (False, wt_dir, "merge-sha") diff --git a/tests/github/test_github_client.py b/tests/github/test_github_client.py index 2c5d3e90bf..873f7a49df 100644 --- a/tests/github/test_github_client.py +++ b/tests/github/test_github_client.py @@ -1,4 +1,4 @@ -"""Tests for the GitHub client: the typed pull request, file, merge base, repository and issue +"""Tests for the GitHub client: the typed pull request, comparison, file, repository and issue comment calls it makes through the GitHub session, and the gh label client (#891).""" from __future__ import annotations @@ -21,6 +21,7 @@ ) from devops_cli.github.client import ( CommitRef, + CompareFiles, GhCliClient, PullRequest, PullRequestFile, @@ -41,6 +42,8 @@ from tests.support.paths import FIXTURES if TYPE_CHECKING: + from collections.abc import Callable + from tests.support.fakes.dns import DnsFake from tests.support.fakes.github import GitHubApiFake @@ -51,12 +54,12 @@ (FIXTURES / "github" / "hello_world_repositories.json").read_text(encoding="utf-8") ) _PULL = "/repos/octocat/Hello-World/pulls/158" -_FILES = f"{_PULL}/files?per_page=100" _BASE_SHA = "7fd1a60b01f91b314f59955a4e4d4e80d8edf11d" _HEAD_SHA = "ec18ca7bca5202d8e139a58b25757dc161255245" _README = _RECORDED["readme_contents"] _README_AT_BASE = f"/repos/octocat/Hello-World/contents/README?ref={_BASE_SHA}" _COMPARE = f"/repos/octocat/Hello-World/compare/{_BASE_SHA}...{_HEAD_SHA}?per_page=1" +_BRANCH_COMPARE = f"/repos/octocat/Hello-World/compare/master...{_HEAD_SHA}?per_page=1" _ORG_REPOS = "/orgs/octocat/repos?type=all&per_page=100" _USER_OWNED_REPOS = "/user/repos?affiliation=owner&visibility=all&per_page=100" @@ -66,18 +69,6 @@ def _client() -> Any: return get_github_session().client -def _route_the_recorded_pull_request(api: GitHubApiFake) -> None: - """Answer the pull request, and its two pages of files with the `Link` GitHub sent.""" - api.route("GET", _PULL, github_json(_RECORDED["pull_request"])) - first, second = _RECORDED["files_pages"] - api.route("GET", _FILES, github_json(first["body"], headers={"link": first["link"]})) - api.route( - "GET", - "/repositories/1296269/pulls/158/files?per_page=1&page=2", - github_json(second["body"], headers={"link": second["link"]}), - ) - - def _carried(api: GitHubApiFake) -> set[str]: """The authorization every request the fake received carried.""" return {request.headers["authorization"] for request in api.sent} @@ -110,7 +101,7 @@ def test_a_pull_request_is_read_with_its_title_and_both_commits( """The recorded pull request has a title, a base in octocat/Hello-World and a head whose repository GitHub reports as null, since the fork it came from was deleted: that head has no repository rather than a wrong one.""" - _route_the_recorded_pull_request(github_api) + github_api.route("GET", _PULL, github_json(_RECORDED["pull_request"])) pull = _client().get_pull("octocat/Hello-World", 158) assert (pull, github_api.requested, _carried(github_api)) == ( PullRequest( @@ -162,31 +153,33 @@ def test_a_repository_name_is_encoded_in_the_request(github_api: GitHubApiFake) ] -def test_the_files_of_a_pull_request_come_from_every_page( +def test_the_files_of_a_comparison_come_with_its_merge_base( github_api: GitHubApiFake, pin_github_session: str ) -> None: - """The recorded listing links a second page: both files are read, in order, with the token.""" - _route_the_recorded_pull_request(github_api) - files = _client().get_pull_files("octocat/Hello-World", 158) - assert (files, github_api.requested, _carried(github_api)) == ( - [ - PullRequestFile(filename="README", status="removed", additions=0, changes=1), - PullRequestFile(filename="README.md", status="added", additions=1, changes=1), - ], - [ - f"GET https://api.github.com{_FILES}", - "GET https://api.github.com/repositories/1296269/pulls/158/files?per_page=1&page=2", - ], + """The recorded compare of the base branch and the head commit lists both files and names + the commit GitHub compared from, in one request with the token of the session.""" + github_api.route("GET", _BRANCH_COMPARE, github_json(_RECORDED["branch_comparison"])) + compared = _client().get_compare_files("octocat/Hello-World", "master", _HEAD_SHA) + assert (compared, github_api.requested, _carried(github_api)) == ( + CompareFiles( + files=[ + PullRequestFile(filename="README", status="removed", additions=0, changes=1), + PullRequestFile(filename="README.md", status="added", additions=1, changes=1), + ], + truncated=False, + merge_base=_BASE_SHA, + ), + [f"GET https://api.github.com{_BRANCH_COMPARE}"], {f"token {pin_github_session}"}, ) def test_a_renamed_file_names_its_previous_path(github_api: GitHubApiFake) -> None: """GitHub sends `previous_filename` for a renamed file only.""" - renamed = {**_RECORDED["files_pages"][1]["body"][0], "status": "renamed"} - renamed["previous_filename"] = "README" - github_api.route("GET", _FILES, github_json([renamed])) - assert _client().get_pull_files("octocat/Hello-World", 158) == [ + recorded = _RECORDED["branch_comparison"] + renamed = {**recorded["files"][1], "status": "renamed", "previous_filename": "README"} + github_api.route("GET", _BRANCH_COMPARE, github_json({**recorded, "files": [renamed]})) + assert _client().get_compare_files("octocat/Hello-World", "master", _HEAD_SHA).files == [ PullRequestFile( filename="README.md", status="renamed", @@ -197,12 +190,15 @@ def test_a_renamed_file_names_its_previous_path(github_api: GitHubApiFake) -> No ] -def test_a_page_with_a_malformed_file_is_unread(github_api: GitHubApiFake) -> None: +def test_a_comparison_with_a_malformed_file_is_unread(github_api: GitHubApiFake) -> None: """A file without a status raises the unread error, so no list that misses it is returned.""" - github_api.route("GET", _FILES, github_json([{"filename": "README"}])) + recorded = _RECORDED["branch_comparison"] + github_api.route( + "GET", _BRANCH_COMPARE, github_json({**recorded, "files": [{"filename": "README"}]}) + ) with pytest.raises(GitHubUnreadError) as raised: - _client().get_pull_files("octocat/Hello-World", 158) - assert raised.value.details["path"] == _FILES + _client().get_compare_files("octocat/Hello-World", "master", _HEAD_SHA) + assert raised.value.details["path"] == _BRANCH_COMPARE def test_a_file_is_read_as_the_text_of_its_contents( @@ -282,20 +278,6 @@ def test_a_file_that_could_not_be_read_raises_instead_of_reading_as_absent( assert str(raised.value) != "" or getattr(raised.value, "error_code", None) is not None -def test_the_merge_base_is_read_from_the_compare_endpoint( - github_api: GitHubApiFake, pin_github_session: str -) -> None: - """The recorded comparison names the commit the pull request branched from, and asks for one - commit only.""" - github_api.route("GET", _COMPARE, github_json(_RECORDED["comparison"])) - merge_base = _client().get_merge_base("octocat/Hello-World", _BASE_SHA, _HEAD_SHA) - assert (merge_base, github_api.requested, _carried(github_api)) == ( - _BASE_SHA, - [f"GET https://api.github.com{_COMPARE}"], - {f"token {pin_github_session}"}, - ) - - def test_the_compare_files_are_read_with_the_limit_flag( github_api: GitHubApiFake, pin_github_session: str ) -> None: @@ -303,11 +285,12 @@ def test_the_compare_files_are_read_with_the_limit_flag( GitHub's limit of 300 files is a possibly truncated list.""" two = [pull_request_file_payload("README"), pull_request_file_payload("README.md", "added")] at_the_limit = [pull_request_file_payload(f"docs/{number}.md") for number in range(300)] + merge_base = {"merge_base_commit": {"sha": _BASE_SHA}} github_api.route( "GET", _COMPARE, - github_json({"files": two}), - github_json({"files": at_the_limit}), + github_json({**merge_base, "files": two}), + github_json({**merge_base, "files": at_the_limit}), ) whole = _client().get_compare_files("octocat/Hello-World", _BASE_SHA, _HEAD_SHA) capped = _client().get_compare_files("octocat/Hello-World", _BASE_SHA, _HEAD_SHA) @@ -334,9 +317,14 @@ def test_a_compare_answer_with_no_files_is_unread(github_api: GitHubApiFake) -> _client().get_compare_files("octocat/Hello-World", _BASE_SHA, _HEAD_SHA) -def test_a_comparison_github_does_not_find_has_no_merge_base(github_api: GitHubApiFake) -> None: - """GitHub's 404 for two commits it cannot compare is no merge base.""" - assert _client().get_merge_base("octocat/Hello-World", _BASE_SHA, "unknown") is None +def test_a_comparison_github_does_not_find_raises_the_not_found_error( + github_api: GitHubApiFake, +) -> None: + """GitHub's 404 for two commits it cannot compare is the not-found error, not an empty + list of files.""" + with pytest.raises(GitHubNotFoundError) as raised: + _client().get_compare_files("octocat/Hello-World", _BASE_SHA, "unknown") + assert raised.value.error_code == "GITHUB_NOT_FOUND" @pytest.mark.parametrize( @@ -345,7 +333,9 @@ def test_a_comparison_github_does_not_find_has_no_merge_base(github_api: GitHubA pytest.param( github_json({"message": "Server Error"}, status=502), GitHubUnreadError, id="502" ), - pytest.param(github_json({"status": "ahead"}), GitHubUnreadError, id="no-merge-base"), + pytest.param( + github_json({"status": "ahead", "files": []}), GitHubUnreadError, id="no-merge-base" + ), ], ) def test_a_comparison_that_could_not_be_read_raises( @@ -354,7 +344,7 @@ def test_a_comparison_that_could_not_be_read_raises( """A 5xx that outlasts the retries, or a comparison without its merge base, is unread.""" github_api.route("GET", _COMPARE, answer) with pytest.raises(error) as raised: - _client().get_merge_base("octocat/Hello-World", _BASE_SHA, _HEAD_SHA) + _client().get_compare_files("octocat/Hello-World", _BASE_SHA, _HEAD_SHA) assert str(raised.value) != "" or getattr(raised.value, "error_code", None) is not None @@ -512,6 +502,25 @@ def test_get_pr_diff_normal_and_redirect( ) +def test_the_compare_diff_is_read_as_text( + github_api: GitHubApiFake, pin_github_session: str +) -> None: + """The diff of two commits is one session request to the compare endpoint, with the diff + media type: the diff of `head` since its merge base with `base`.""" + github_api.route( + "GET", + "/repos/octo/repo/compare/merge789...abc123", + github_text("diff --git a/foo b/foo\n+line", media_type=CONST_GITHUB_DIFF_MEDIA_TYPE), + ) + diff = _client().get_compare_diff("octo/repo", "merge789", "abc123") + carried = {(r.headers["accept"], r.headers["authorization"]) for r in github_api.sent} + assert (diff, github_api.requested, carried) == ( + "diff --git a/foo b/foo\n+line", + ["GET https://api.github.com/repos/octo/repo/compare/merge789...abc123"], + {(CONST_GITHUB_DIFF_MEDIA_TYPE, f"token {pin_github_session}")}, + ) + + def test_get_pr_diff_empty_diff_returns_empty_string( github_api: GitHubApiFake, pin_github_session: str ) -> None: @@ -531,14 +540,31 @@ def test_get_pr_diff_empty_diff_returns_empty_string( pytest.param(github_json({"number": 42}), id="json"), ], ) +@pytest.mark.parametrize( + ("path", "read"), + [ + pytest.param( + "/repos/octo/repo/pulls/42", lambda client: client.get_pr_diff("octo/repo", 42), id="pr" + ), + pytest.param( + "/repos/octo/repo/compare/merge789...abc123", + lambda client: client.get_compare_diff("octo/repo", "merge789", "abc123"), + id="compare", + ), + ], +) def test_an_answer_that_is_no_diff_raises_the_unread_error( - github_api: GitHubApiFake, pin_github_session: str, answer: httpx2.Response + github_api: GitHubApiFake, + pin_github_session: str, + answer: httpx2.Response, + path: str, + read: Callable[[Any], str], ) -> None: """A diff GitHub did not send as text is unread, not an empty or stringified diff.""" - github_api.route("GET", "/repos/octo/repo/pulls/42", answer) + github_api.route("GET", path, answer) with pytest.raises(GitHubUnreadError) as raised: - _client().get_pr_diff("octo/repo", 42) - assert raised.value.details["path"] == "/repos/octo/repo/pulls/42" + read(_client()) + assert raised.value.details["path"] == path @pytest.fixture diff --git a/tests/roadmap/test_roadmap_draft_readiness.py b/tests/roadmap/test_roadmap_draft_readiness.py index e7864c88cf..2afffc8bff 100644 --- a/tests/roadmap/test_roadmap_draft_readiness.py +++ b/tests/roadmap/test_roadmap_draft_readiness.py @@ -293,6 +293,7 @@ def test_read_draft_with_active_change_and_no_pull_arg() -> None: ), ], truncated=False, + merge_base="base123", ) client.get_file_at.return_value = _COMPLETE_TASKS @@ -424,6 +425,7 @@ def test_read_draft_implement_kind_with_no_change_folder_in_files() -> None: client.get_compare_files.return_value = CompareFiles( files=[PullRequestFile(filename="src/main.py", status="modified")], truncated=False, + merge_base="base123", ) draft = read_draft("dan-petty/devops-cli", 335, pull=pull, store=store, client=client) diff --git a/tests/support/fakes/github.py b/tests/support/fakes/github.py index 964edcbfb5..d10ed0204d 100644 --- a/tests/support/fakes/github.py +++ b/tests/support/fakes/github.py @@ -29,9 +29,9 @@ (`run_gh` and the quota refresh). `pull_request_payload`, `pull_request_file_payload`, `route_pull_request`, `route_file`, -`route_merge_base` and `route_compare_files` give a test a pull request to read: the fields -devops-cli reads of one, and the routes that answer the reads a review or an analysis makes of it -(#891, #2530). +`route_compare_files`, `route_compare_diff` and `route_pull_request_changes` give a test a pull +request to read: the fields devops-cli reads of one, and the routes that answer the reads a +review or an analysis makes of it (#891, #2530, #5346). `RunnerSession` is a session whose listings a scripted gh runner answers, for the roadmap store tests that script gh for the board as well. @@ -200,15 +200,6 @@ def route_file(api: GitHubApiFake, repo: str, path: str, ref: str, text: str) -> ) -def route_merge_base(api: GitHubApiFake, repo: str, base: str, head: str, sha: str) -> None: - """Answer the comparison of `base` and `head` in `repo` with `sha` as their merge base.""" - api.route( - "GET", - f"/repos/{repo}/compare/{base}...{head}?per_page=1", - github_json({"merge_base_commit": {"sha": sha}}), - ) - - def route_compare_files( api: GitHubApiFake, repo: str, @@ -226,6 +217,32 @@ def route_compare_files( ) +def route_compare_diff(api: GitHubApiFake, repo: str, base: str, head: str, diff: str) -> None: + """Answer the diff of `head` since its merge base with `base` in `repo` with `diff`, as the + compare endpoint sends it in the diff media type.""" + api.route( + "GET", + f"/repos/{repo}/compare/{quote(base)}...{quote(head)}", + github_text(diff, media_type=CONST_GITHUB_DIFF_MEDIA_TYPE), + ) + + +def route_pull_request_changes( + api: GitHubApiFake, + pull: Mapping[str, Any], + *files: Mapping[str, Any], + merge_base: str, + diff: str = "", +) -> None: + """Answer the reads of the changes of `pull`, a `pull_request_payload`, in its base + repository: the compare of its base branch and its head commit with `files` and + `merge_base`, and `diff` as the diff of the head since `merge_base` (#5346).""" + repo = pull["base"]["repo"]["full_name"] + head = pull["head"]["sha"] + route_compare_files(api, repo, pull["base"]["ref"], head, *files, merge_base=merge_base) + route_compare_diff(api, repo, merge_base, head, diff) + + def route_installation_repositories(api: GitHubApiFake, repos: Sequence[str]) -> None: """Answer the read of the App's installation repositories with `repos`.""" repositories = [ From 03b6aac40f11087e735ce1d7f31ef0a9fed37906 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 13 Nov 2026 08:09:26 +0000 Subject: [PATCH 2/3] docs(review): name the merge base of a pull request as its base revision BaseRevision.revision now holds the merge base of a pull request, so its docstring tells that. The diff media type is also the media type of a comparison diff. The test of the posted comment shows that the command reads the file list of the compare one time only. --- docs/SELF_IMPROVEMENT.md | 16 ++++++++-------- .../5346-review-pr-merge-base/proposal.md | 2 +- src/devops_cli/ai/analyze/symbols.py | 6 ++++-- src/devops_cli/config/constants.py | 2 +- tests/commands/test_review_pr_post.py | 6 ++++-- 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/docs/SELF_IMPROVEMENT.md b/docs/SELF_IMPROVEMENT.md index d236afbf00..d07e8cdb4a 100644 --- a/docs/SELF_IMPROVEMENT.md +++ b/docs/SELF_IMPROVEMENT.md @@ -742,14 +742,14 @@ project enforces, the inputs the project trusts, or house rules for its document A change is reviewed under the conventions it started from, so it cannot loosen its own review (#946). `devops review branch` reads conventions with git at the merge base of the branch and its base (at `HEAD` for uncommitted changes), not from the working tree, and `devops review pr` reads -them at the merge base of the pull request's head commit and the tip of its base branch, the base -of the diff that the squash merge applies (#5346). A base with no local branch, as in a CI checkout of a feature, -is `origin/`, and the checked-out branch is never its own base: with no base at all the diff -fails. The lookup also stops at a defect corpus's root, which its manifest marks, read at the same -revision. It reads only regular files: a conventions file that is a link is skipped, on disk and -at a revision, so a reviewed tree cannot bring a file -from outside it into the prompts. Each review's `profile.json` records `conventions_digest`, a digest of the conventions -its prompts carried, empty when they carried none. +them at the merge base of the pull request's head commit and the tip of its base branch, the base of +the diff that the squash merge applies (#5346). A base with no local branch, as in a CI checkout of +a feature, is `origin/`, and the checked-out branch is never its own base: with no base at all +the diff fails. The lookup also stops at a defect corpus's root, which its manifest marks, read at +the same revision. It reads only regular files: a conventions file that is a link is skipped, on +disk and at a revision, so a reviewed tree cannot bring a file from outside it into the prompts. +Each review's `profile.json` records `conventions_digest`, a digest of the conventions its prompts +carried, empty when they carried none. ### Synthetic Defect Corpora diff --git a/openspec/changes/5346-review-pr-merge-base/proposal.md b/openspec/changes/5346-review-pr-merge-base/proposal.md index b794fe8df9..c013640383 100644 --- a/openspec/changes/5346-review-pr-merge-base/proposal.md +++ b/openspec/changes/5346-review-pr-merge-base/proposal.md @@ -28,7 +28,7 @@ None. ## Impact -- Code: `src/devops_cli/github/client.py`, `src/devops_cli/ai/review/runner.py`, `src/devops_cli/commands/review.py`, `src/devops_cli/commands/analyze.py`, `src/devops_cli/lang/en/messages.py` +- Code: `src/devops_cli/github/client.py`, `src/devops_cli/ai/review/runner.py`, `src/devops_cli/commands/review.py`, `src/devops_cli/commands/analyze.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/ai/analyze/symbols.py` (the docstring of `BaseRevision.revision`), `src/devops_cli/config/constants.py` (the comment of `CONST_GITHUB_DIFF_MEDIA_TYPE`) - Docs: `docs/SELF_IMPROVEMENT.md`, `src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md` - Tests: `tests/github/test_github_client.py`, `tests/commands/test_review_scope.py`, `tests/commands/test_review_pr_post.py`, `tests/commands/test_analyze.py`, `tests/ai/review/test_review_runner.py`, `tests/ai/review/test_review_path_routing.py`, `tests/ai/client/test_batch_2_review_defects.py`, `tests/git/test_review_worktree_regression.py`, `tests/git/test_ai_task_metadata.py`, `tests/roadmap/test_roadmap_draft_readiness.py`, `tests/support/fakes/github.py`, `tests/fixtures/github/hello_world_pull_request.json` diff --git a/src/devops_cli/ai/analyze/symbols.py b/src/devops_cli/ai/analyze/symbols.py index 8f92cf39e3..a71b3bdb21 100644 --- a/src/devops_cli/ai/analyze/symbols.py +++ b/src/devops_cli/ai/analyze/symbols.py @@ -33,8 +33,10 @@ class BaseRevision: on disk: a branch that is not checked out, or one whose checkout has uncommitted edits the diff leaves out. Without it the reviewed files on disk are the head. - `revision` names the base in the local repository, when `read` reads it there; a pull - request's base, read from its repository on GitHub, has none. + `revision` names the base in the local repository: the revision that `read` reads there, or + the merge base of a pull request, which `read` reads from its repository on GitHub and the + fetch of the pull request head brings to the local repository (#5346). Without it, the base + has no local name. """ changes: tuple[ChangedFile, ...] diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 853b82518e..b0d7476d6e 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -1027,7 +1027,7 @@ CONST_GITHUB_USER_AGENT: Final[str] = CONST_APP_NAME CONST_GITHUB_API_VERSION: Final[str] = "2022-11-28" CONST_GITHUB_HEADER_API_VERSION: Final[str] = "x-github-api-version" -# The media type GitHub serves a pull request's unified diff as. +# The media type GitHub serves the unified diff of a pull request or of a comparison as. CONST_GITHUB_DIFF_MEDIA_TYPE: Final[str] = "application/vnd.github.diff" # GitHub lists at most this many files of one compare answer, so a list of this length may be # truncated (#2530). diff --git a/tests/commands/test_review_pr_post.py b/tests/commands/test_review_pr_post.py index 35b8d783e2..9671b3232c 100644 --- a/tests/commands/test_review_pr_post.py +++ b/tests/commands/test_review_pr_post.py @@ -271,7 +271,8 @@ def test_devops_review_pr_post_names_the_files_the_pull_request_leaves_in_place( cli: Callable[..., Any], github_api: GitHubApiFake ) -> None: """A diff of routed files names no file, so the comment lists the files of the compare that - the review read, and a file the pull request removes is not one of the files checked.""" + the review read, and a file the pull request removes is not one of the files checked. The + command reads the file list one time only (#5346).""" _route_the_pull_request( github_api, files=[ @@ -285,5 +286,6 @@ def test_devops_review_pr_post_names_the_files_the_pull_request_leaves_in_place( result = _post_the_review_without_a_model(cli) posted = _posted(github_api) - assert (result.exit_code, len(posted)) == (0, 1) + file_lists = [r for r in github_api.requested if "/compare/main...abc123?per_page=1" in r] + assert (result.exit_code, len(posted), len(file_lists)) == (0, 1, 1) assert "- **Files checked:** `openspec/changes/1-x/tasks.md`\n" in posted[0][1]["body"] From 99b6f10605c6ca3d372487f4d9490bab8779b4b3 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 13 Nov 2026 08:01:34 +0000 Subject: [PATCH 3/3] docs(openspec): archive 5346-review-pr-merge-base Move the change of #5346 to the archive and add the living capability pr-squash-diff. --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/pr-squash-diff/spec.md | 0 .../tasks.md | 0 openspec/specs/pr-squash-diff/spec.md | 39 +++++++++++++++++++ 6 files changed, 39 insertions(+) rename openspec/changes/{5346-review-pr-merge-base => archive/2026-11-13-5346-review-pr-merge-base}/.openspec.yaml (100%) rename openspec/changes/{5346-review-pr-merge-base => archive/2026-11-13-5346-review-pr-merge-base}/design.md (100%) rename openspec/changes/{5346-review-pr-merge-base => archive/2026-11-13-5346-review-pr-merge-base}/proposal.md (100%) rename openspec/changes/{5346-review-pr-merge-base => archive/2026-11-13-5346-review-pr-merge-base}/specs/pr-squash-diff/spec.md (100%) rename openspec/changes/{5346-review-pr-merge-base => archive/2026-11-13-5346-review-pr-merge-base}/tasks.md (100%) create mode 100644 openspec/specs/pr-squash-diff/spec.md diff --git a/openspec/changes/5346-review-pr-merge-base/.openspec.yaml b/openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/.openspec.yaml similarity index 100% rename from openspec/changes/5346-review-pr-merge-base/.openspec.yaml rename to openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/.openspec.yaml diff --git a/openspec/changes/5346-review-pr-merge-base/design.md b/openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/design.md similarity index 100% rename from openspec/changes/5346-review-pr-merge-base/design.md rename to openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/design.md diff --git a/openspec/changes/5346-review-pr-merge-base/proposal.md b/openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/proposal.md similarity index 100% rename from openspec/changes/5346-review-pr-merge-base/proposal.md rename to openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/proposal.md diff --git a/openspec/changes/5346-review-pr-merge-base/specs/pr-squash-diff/spec.md b/openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/specs/pr-squash-diff/spec.md similarity index 100% rename from openspec/changes/5346-review-pr-merge-base/specs/pr-squash-diff/spec.md rename to openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/specs/pr-squash-diff/spec.md diff --git a/openspec/changes/5346-review-pr-merge-base/tasks.md b/openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/tasks.md similarity index 100% rename from openspec/changes/5346-review-pr-merge-base/tasks.md rename to openspec/changes/archive/2026-11-13-5346-review-pr-merge-base/tasks.md diff --git a/openspec/specs/pr-squash-diff/spec.md b/openspec/specs/pr-squash-diff/spec.md new file mode 100644 index 0000000000..813cd9d914 --- /dev/null +++ b/openspec/specs/pr-squash-diff/spec.md @@ -0,0 +1,39 @@ +# pr-squash-diff Specification + +## Purpose +Which changes of a pull request `devops review pr` and `devops ai analyze pr` read: the files and the diff that the squash merge applies, which is the compare of the tip of the base branch and the head commit, and not the stale base of the pull request payload. + +## Requirements + +### Requirement: A PR review reads the diff that the squash merge applies +The command `devops review pr` SHALL read the files and the diff of a pull request from the compare of the tip of its base branch and its head commit, and SHALL read the base text and the base conventions at the merge base of that compare. It MUST NOT read the pulls files endpoint or the diff of the pulls endpoint, and MUST NOT read a file at the `base.sha` of the pull request payload. + +#### Scenario: A moved merge base +- **WHEN** a merge of the base branch into the pull request moved its merge base, the payload's `base.sha` and the pulls files and diff endpoints still name the old base, and the compare of the base branch and the head commit names another merge base +- **THEN** the review pages hold only the files of the compare, the base text and the conventions are read at the merge base of the compare, and no request names `base.sha` or the pulls files path + +#### Scenario: The base worktree +- **WHEN** the fetch of the pull request head into the local checkout succeeds +- **THEN** the base worktree of the review is at the merge base of the compare + +#### Scenario: A diff that names no reviewable file +- **WHEN** the diff names no reviewable file and the review posts its comment +- **THEN** the comment lists the files of the compare that the review read, less the deleted files, and the command reads the file list only one time + +### Requirement: A PR review refuses a compare at the file limit +The command `devops review pr` SHALL end with status 1 when the compare of the base branch and the head commit lists GitHub's limit of files for one comparison, with a message that names the limit and `devops review branch`, and SHALL read no diff. + +#### Scenario: The compare lists 300 files +- **WHEN** the compare of the base branch and the head commit lists 300 files +- **THEN** the command exits 1, its message names 300 files and `devops review branch`, and it makes no diff request + +### Requirement: The PR analysis reads the files of the compare of its base branch +The command `devops ai analyze pr` SHALL read the files of a pull request from the compare of the tip of its base branch and its head commit, and MUST NOT read the pulls files endpoint. A compare that lists GitHub's limit of files SHALL give an analysis of the listed files and a warning that names the limit. + +#### Scenario: A moved merge base +- **WHEN** the pulls files endpoint lists a file that the compare of the base branch and the head commit does not list +- **THEN** the analysis holds only the files of the compare, and the command reads only the pull request and the compare + +#### Scenario: The compare lists 300 files +- **WHEN** the compare of the base branch and the head commit lists 300 files +- **THEN** the command exits 0, the analysis holds the 300 files, and a warning names the limit of 300 files