diff --git a/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/.openspec.yaml b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/.openspec.yaml new file mode 100644 index 0000000000..bbe8b39365 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-17 diff --git a/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/design.md b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/design.md new file mode 100644 index 0000000000..9855b67bef --- /dev/null +++ b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/design.md @@ -0,0 +1,45 @@ +# Design + +## Decisions + +### One no-CI rule in the merge-readiness verdict + +`_judge_checks` decides that no check can start, so `devops pr check-readiness`, `devops pr +ready` and `devops pr monitor` share one verdict. The verdict sets `no_ci`, adds an INFO advisory +and adds no `CHECKS_PENDING` blocker. `devops pr ready` reads `no_ci` instead of the branch-wide +workflow count. + +### Read the workflow triggers at the head commit + +`GitHubClient.pull_request_workflow_at` lists `.github/workflows` at the head commit, reads each +YAML file and parses its `on` key. A workflow that lists `pull_request` or `pull_request_target` +can start a check on the pull request. A missing folder means no CI. A folder that holds only +`push` or `workflow_dispatch` workflows also means no CI. + +YAML 1.1 reads a bare `on` key as the boolean `True`, so the parser reads both keys. + +### Fail closed on an unread workflow + +A read error, or a workflow file that is not valid YAML, keeps the pending check. An unread +workflow is no proof that no check can start, so `devops pr ready` waits (exit 8) and +`devops pr monitor` waits until its timeout rather than report a pull request ready. + +### A conflict stops the monitor before the pending check + +Once the no-CI rule removes the pending stand-in, the monitor's settled result names the merge +conflict at once. It no longer sleeps for a check that no workflow will start. + +### Remove `count_workflows` + +The branch-wide count reads no trigger and no head commit, so it answered the wrong question. No +caller remains after this change. + +## Rejected alternatives + +- **Keep `count_workflows`:** it counts workflows on any branch and ignores triggers, so it + reports CI for a workflow that cannot run on a pull request. +- **Fix each command separately:** three copies drift, and #5142 already left `pr monitor` and + `check-readiness` behind. +- **Read the workflow file names only:** a workflow with only `push` or `workflow_dispatch` + triggers cannot start a check on the pull request. +- **Treat an unread workflow as no CI:** that reports a pull request ready on no evidence. diff --git a/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/proposal.md b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/proposal.md new file mode 100644 index 0000000000..36d8b947dc --- /dev/null +++ b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/proposal.md @@ -0,0 +1,46 @@ +# Proposal: #5144 + +## Why + +`devops pr monitor` and `devops pr check-readiness` take the head commit of a pull request with no +check as a running check. In a repository with no GitHub Actions workflow no check will start, so +`check-readiness` exits 1 with a pending-check blocker and `pr monitor` waits until its timeout and +exits 3. Pull request #5142 (#3767) excused that case for `devops pr ready` only. Closes #5144. + +## What Changes + +- The merge-readiness verdict reads the workflows at the head commit and their triggers. A + repository with no workflow, or none that lists `pull_request` or `pull_request_target`, has no + CI for the pull request. +- The verdict adds an INFO advisory and no pending-check blocker when no workflow can start a + check on the pull request, so `devops pr check-readiness` exits 0 and `devops pr monitor` + settles on its first poll. +- `devops pr ready` uses the same verdict instead of `GitHubClient.count_workflows`. +- A workflow read that fails keeps the pending check, so all three commands fail closed. + +## Capabilities + +### Modified + +- `pr-merge-readiness`: the verdict, `devops pr check-readiness`, `devops pr ready` and + `devops pr monitor` share one no-CI decision. + +## Impact + +`devops pr check-readiness`, `devops pr ready` and `devops pr monitor` no longer wait for a check +that a repository without a pull-request workflow cannot start. `GitHubClient.count_workflows` is +removed, since its branch-wide count ignores the triggers and the head commit. + +## Feasibility + +Confirmed against the issue and the code at `origin/main`: `_judge_checks` in +`src/devops_cli/github/merge_readiness.py` holds the pending stand-in, `_no_ci` in +`src/devops_cli/commands/pr.py` used `GitHubClient.count_workflows`, and +`CheckVerdictSummary.reports_nothing` detects the stand-in. `GitHubClient.get_file_at` already +reads a file at a ref, and PyYAML is a project dependency. + +## Existing Tool Considered + +No open tool or library covers this need. The change uses the existing GitHub contents endpoint +and PyYAML, adds no dependency, and costs about 8,000 tokens and one engineer-day to build and +test. diff --git a/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/specs/pr-merge-readiness/spec.md b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/specs/pr-merge-readiness/spec.md new file mode 100644 index 0000000000..823dd363fa --- /dev/null +++ b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/specs/pr-merge-readiness/spec.md @@ -0,0 +1,99 @@ +## MODIFIED Requirements + +### Requirement: pr ready does not wait for checks in a repository with no CI + +When the head commit of the pull request reports no check run and no commit status, the merge +readiness verdict SHALL read the workflows at that commit and their triggers. When no workflow +lists `pull_request` or `pull_request_target`, no check can start. Then the verdict SHALL add no +pending-check blocker and SHALL name the missing CI in an INFO advisory. `devops pr ready` SHALL +say so, SHALL NOT judge the checks or warn of them, and SHALL mark the pull request ready with no +`--force`. + +#### Scenario: A repository with no CI + +- **WHEN** the head commit reports no check and holds no workflow file +- **THEN** `pr ready` names the repository, says that it has no workflow that runs on a pull + request, marks the pull request ready, and exits 0 with no warning about "no checks reported" + +#### Scenario: A push-only workflow + +- **WHEN** the head commit reports no check and holds one workflow with only `push` and + `workflow_dispatch` triggers +- **THEN** `pr ready` marks the pull request ready and exits 0 + +### Requirement: pr ready waits for checks that a workflow can start + +When the head commit reports no check and holds a workflow that lists `pull_request` or +`pull_request_target`, `devops pr ready` SHALL wait for the checks as before. A read of the +workflows that fails SHALL keep the pending check, so `devops pr ready` SHALL exit 8 and marks +nothing. + +#### Scenario: Checks that have not started + +- **WHEN** the head commit reports no check and holds a workflow that lists `pull_request` +- **THEN** `pr ready` exits 8 and marks nothing + +#### Scenario: The workflows cannot be read + +- **WHEN** the head commit reports no check and GitHub answers the read of the workflows with an + error +- **THEN** `pr ready` exits 8 and marks nothing + +## ADDED Requirements + +### Requirement: The verdict reads the workflow triggers at the head commit + +The merge-readiness verdict SHALL read `.github/workflows` at the head commit and the `on` key of +each workflow file. A 404, an empty folder, or a folder whose workflows all list other triggers +SHALL mean that no CI can run on the pull request. + +#### Scenario: A pull-request workflow keeps the pending check + +- **WHEN** a test gives the head commit one workflow whose `on` key lists `pull_request` and + gives no check runs +- **THEN** the verdict holds `BlockerKind.CHECKS_PENDING` and `pending_checks` holds + `no checks reported` + +#### Scenario: A push-only workflow suppresses the pending check + +- **WHEN** a test gives the head commit one workflow with only `push` and `workflow_dispatch` + triggers and gives no check runs +- **THEN** the verdict holds no `BlockerKind.CHECKS_PENDING` blocker and holds the no-CI advisory + +#### Scenario: An unread workflow fails closed + +- **WHEN** a test makes the workflow read fail and gives no check runs +- **THEN** the verdict holds `BlockerKind.CHECKS_PENDING` and `pending_checks` holds + `no checks reported` + +### Requirement: check-readiness reports a repository with no CI + +`devops pr check-readiness` SHALL exit 0 with the no-CI advisory when no workflow can run on the +head commit and no other blocker applies. + +#### Scenario: check-readiness on a repository with no CI + +- **WHEN** a test runs `devops pr check-readiness` for a pull request whose head commit holds no + workflow and no check +- **THEN** the test asserts exit code 0 and that the output contains the no-CI advisory + +### Requirement: pr monitor does not wait for a repository with no CI + +`devops pr monitor` SHALL settle on its first poll when no workflow can run on the head commit +and no other blocker applies. + +#### Scenario: pr monitor on a repository with no CI + +- **WHEN** a test runs `devops pr monitor` with a fake clock for a pull request whose head commit + holds no workflow and no check +- **THEN** the test asserts exit code 0 and that the monitor made no sleep call + +### Requirement: pr monitor stops on a conflict before pending checks + +`devops pr monitor` SHALL report a merge conflict and stop before it waits on the pending +no-checks stand-in. + +#### Scenario: Conflict with no checks + +- **WHEN** a test gives the verdict a `mergeable_state` of `dirty` and no check runs +- **THEN** the output names the merge conflict and the monitor made no sleep call diff --git a/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/tasks.md b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/tasks.md new file mode 100644 index 0000000000..bf874d3171 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-5144-pr-monitor-fits-a-repository-with/tasks.md @@ -0,0 +1,19 @@ +# Tasks + +## 1. Behavior + +- [x] 1.1 Write the failing tests for a head commit with no check and no pull-request workflow, a + pull-request workflow, a push-only workflow, and an unread workflow. + - Verification: `$ uv run devops ci test tests/github/test_merge_readiness.py` +- [x] 1.2 Read the workflow triggers at the head commit and suppress the pending check when no + workflow can start one. + - Verification: `$ uv run devops ci test tests/github/test_merge_readiness.py tests/commands/test_pr.py` +- [x] 1.3 Make `devops pr ready` read the verdict's no-CI decision and remove `count_workflows`. + - Verification: `$ uv run devops ci test tests/commands/test_pr.py` + +## 2. Documents + +- [x] 2.1 Update the `pr-merge-readiness` specification with the head-workflow rule. + - Verification: `$ uv run devops openspec check` +- [x] 2.2 Archive the change into the main specification. + - Verification: `$ uv run devops openspec archive 5144-pr-monitor-fits-a-repository-with` diff --git a/openspec/specs/pr-merge-readiness/spec.md b/openspec/specs/pr-merge-readiness/spec.md index 592dd045df..329a2e61ec 100644 --- a/openspec/specs/pr-merge-readiness/spec.md +++ b/openspec/specs/pr-merge-readiness/spec.md @@ -125,22 +125,43 @@ The verdict SHALL hold one blocker of the kind body form for each problem that ` - **THEN** `merge_conflict` returns None and the row posts no comment ### Requirement: pr ready does not wait for checks in a repository with no CI -When the head commit of the pull request reports no check run and no commit status, and the repository has no GitHub Actions workflow, no check will start. Then `devops pr ready` SHALL say so, SHALL NOT judge the checks or warn of them, and SHALL mark the pull request ready with no `--force`. + +When the head commit of the pull request reports no check run and no commit status, the merge +readiness verdict SHALL read the workflows at that commit and their triggers. When no workflow +lists `pull_request` or `pull_request_target`, no check can start. Then the verdict SHALL add no +pending-check blocker and SHALL name the missing CI in an INFO advisory. `devops pr ready` SHALL +say so, SHALL NOT judge the checks or warn of them, and SHALL mark the pull request ready with no +`--force`. #### Scenario: A repository with no CI -- **WHEN** the head commit reports no check and the repository has no workflow -- **THEN** `pr ready` names the repository, says that it has no GitHub Actions workflow, marks the pull request ready, and exits 0 with no warning about "no checks reported" + +- **WHEN** the head commit reports no check and holds no workflow file +- **THEN** `pr ready` names the repository, says that it has no workflow that runs on a pull + request, marks the pull request ready, and exits 0 with no warning about "no checks reported" + +#### Scenario: A push-only workflow + +- **WHEN** the head commit reports no check and holds one workflow with only `push` and + `workflow_dispatch` triggers +- **THEN** `pr ready` marks the pull request ready and exits 0 ### Requirement: pr ready waits for checks that a workflow can start -When the head commit reports no check and the repository has a GitHub Actions workflow, `devops pr ready` SHALL wait for the checks as before. A read of the workflows that fails SHALL stop the command with exit 1 and the error. + +When the head commit reports no check and holds a workflow that lists `pull_request` or +`pull_request_target`, `devops pr ready` SHALL wait for the checks as before. A read of the +workflows that fails SHALL keep the pending check, so `devops pr ready` SHALL exit 8 and marks +nothing. #### Scenario: Checks that have not started -- **WHEN** the head commit reports no check and the repository has 2 workflows + +- **WHEN** the head commit reports no check and holds a workflow that lists `pull_request` - **THEN** `pr ready` exits 8 and marks nothing #### Scenario: The workflows cannot be read -- **WHEN** the head commit reports no check and GitHub answers the read of the workflows with an error -- **THEN** `pr ready` exits 1 and marks nothing + +- **WHEN** the head commit reports no check and GitHub answers the read of the workflows with an + error +- **THEN** `pr ready` exits 8 and marks nothing ### Requirement: Readiness reads the file list at the merge base The command `devops pr check-readiness` SHALL read the files a pull request changes from the compare endpoint of the tip of the base branch and the head commit, and MUST NOT compare from the `base.sha` of the pull request payload. @@ -267,3 +288,60 @@ The stage eval evidence SHALL hold a number beside `before` and beside `after`, #### Scenario: A model flag with no name is refused - **WHEN** the body holds `--model` with no name - **THEN** `stage_eval_problems` names the flag + +### Requirement: The verdict reads the workflow triggers at the head commit + +The merge-readiness verdict SHALL read `.github/workflows` at the head commit and the `on` key of +each workflow file. A 404, an empty folder, or a folder whose workflows all list other triggers +SHALL mean that no CI can run on the pull request. + +#### Scenario: A pull-request workflow keeps the pending check + +- **WHEN** a test gives the head commit one workflow whose `on` key lists `pull_request` and + gives no check runs +- **THEN** the verdict holds `BlockerKind.CHECKS_PENDING` and `pending_checks` holds + `no checks reported` + +#### Scenario: A push-only workflow suppresses the pending check + +- **WHEN** a test gives the head commit one workflow with only `push` and `workflow_dispatch` + triggers and gives no check runs +- **THEN** the verdict holds no `BlockerKind.CHECKS_PENDING` blocker and holds the no-CI advisory + +#### Scenario: An unread workflow fails closed + +- **WHEN** a test makes the workflow read fail and gives no check runs +- **THEN** the verdict holds `BlockerKind.CHECKS_PENDING` and `pending_checks` holds + `no checks reported` + +### Requirement: check-readiness reports a repository with no CI + +`devops pr check-readiness` SHALL exit 0 with the no-CI advisory when no workflow can run on the +head commit and no other blocker applies. + +#### Scenario: check-readiness on a repository with no CI + +- **WHEN** a test runs `devops pr check-readiness` for a pull request whose head commit holds no + workflow and no check +- **THEN** the test asserts exit code 0 and that the output contains the no-CI advisory + +### Requirement: pr monitor does not wait for a repository with no CI + +`devops pr monitor` SHALL settle on its first poll when no workflow can run on the head commit +and no other blocker applies. + +#### Scenario: pr monitor on a repository with no CI + +- **WHEN** a test runs `devops pr monitor` with a fake clock for a pull request whose head commit + holds no workflow and no check +- **THEN** the test asserts exit code 0 and that the monitor made no sleep call + +### Requirement: pr monitor stops on a conflict before pending checks + +`devops pr monitor` SHALL report a merge conflict and stop before it waits on the pending +no-checks stand-in. + +#### Scenario: Conflict with no checks + +- **WHEN** a test gives the verdict a `mergeable_state` of `dirty` and no check runs +- **THEN** the output names the merge conflict and the monitor made no sleep call diff --git a/src/devops_cli/commands/pr.py b/src/devops_cli/commands/pr.py index 2d67582194..6f7d44a223 100644 --- a/src/devops_cli/commands/pr.py +++ b/src/devops_cli/commands/pr.py @@ -41,7 +41,6 @@ parse_update_error, plan_update_single_pr, ) -from devops_cli.github.check_verdict import CheckVerdictSummary from devops_cli.github.client import PullStatus from devops_cli.github.defect_classifier import ( PRHardeningAudit, @@ -1410,15 +1409,11 @@ def _handle_pr_ready_failure(stderr_text: str, number: int) -> None: print_error(f"Failed to mark PR #{number} ready: {clean_err or 'Unknown error'}", safe=True) -def _no_ci(repo: str, checks: CheckVerdictSummary | None) -> bool: - """Whether no check will come for the pull request (#3767): its head commit reports no check - run and no commit status, and `repo` has no GitHub Actions workflow to start one. A read that - fails raises the error of the session.""" - if checks is None or not checks.reports_nothing: - return False - from devops_cli.github.session import get_github_session - - return get_github_session().client.count_workflows(repo) == 0 +def _no_ci(verdict: MergeReadiness) -> bool: + """Whether no check will come for the pull request (#3767, #5144): the merge-readiness verdict + reads the workflows at its head and finds none that runs on a pull request, so it excuses the + missing checks. A workflow read that fails keeps the pending check, so the verdict says no.""" + return verdict.no_ci def _validate_pr_ready(number: int, owner: str, repo_name: str, pr_data: dict[str, Any]) -> Draft: @@ -1436,7 +1431,7 @@ def _validate_pr_ready(number: int, owner: str, repo_name: str, pr_data: dict[st repo = f"{owner}/{repo_name}" pull = PullStatus.model_validate(pr_data) try: - no_ci = _no_ci(repo, verdict.checks) + no_ci = _no_ci(verdict) checks = None if no_ci else verdict.checks draft = read_draft(repo, number, pull=pull, checks=checks, declared=True) except (GitHubOperationError, GitHubUnreadError) as exc: diff --git a/src/devops_cli/github/client.py b/src/devops_cli/github/client.py index 3a4e0a27e7..6246856db8 100755 --- a/src/devops_cli/github/client.py +++ b/src/devops_cli/github/client.py @@ -8,9 +8,10 @@ from collections.abc import Mapping, Sequence from datetime import datetime from http import HTTPStatus -from typing import TYPE_CHECKING, Any, NamedTuple +from typing import TYPE_CHECKING, Any, Final, NamedTuple from urllib.parse import quote, urlencode +import yaml from pydantic import ( AliasChoices, AliasPath, @@ -42,6 +43,10 @@ from devops_cli.github.session import GitHubSession +_WORKFLOWS_DIR: Final[str] = ".github/workflows" +_PULL_REQUEST_TRIGGERS: Final[frozenset[str]] = frozenset({"pull_request", "pull_request_target"}) + + class RepoInfo(BaseModel): name: str full_name: str @@ -271,10 +276,6 @@ class _LabelName(BaseModel): name: str -class _WorkflowCount(BaseModel): - total_count: int - - class _CommentText(BaseModel): body: str = "" @@ -378,6 +379,14 @@ class _FileContents(BaseModel): content: str = "" +class _DirectoryEntry(BaseModel): + """One item of a contents endpoint answer for a directory: a file or a directory.""" + + type: str + name: str + path: str + + class _CompareFiles(BaseModel): """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.""" @@ -396,6 +405,32 @@ class CompareFiles(NamedTuple): merge_base: str +def _runs_on_pull_request(text: str) -> bool: + """Whether workflow `text` lists a trigger that starts it on a pull request. + + YAML 1.1 reads a bare `on` key as the boolean `True`, so both keys are read. A document that + is no workflow mapping, and a trigger that is absent or malformed, starts no check on a pull + request. A file that is not valid YAML raises `GitHubUnreadError`, so its caller keeps the + pending check rather than call the repository one with no CI. + """ + try: + document = yaml.safe_load(text) + except yaml.YAMLError as exc: + raise GitHubUnreadError(f"GitHub's workflow file is not valid YAML: {exc}") from exc + if not isinstance(document, dict): + return False + triggers = document.get("on", document.get(True)) + if isinstance(triggers, str): + return triggers in _PULL_REQUEST_TRIGGERS + if isinstance(triggers, list): + return any( + trigger in _PULL_REQUEST_TRIGGERS for trigger in triggers if isinstance(trigger, str) + ) + if isinstance(triggers, dict): + return any(str(trigger) in _PULL_REQUEST_TRIGGERS for trigger in triggers) + return False + + def _read_as[M: BaseModel](model: type[M], answer: Any, *, path: str) -> M: """`answer` as a `model`, raising `GitHubUnreadError` naming `path` when it is none.""" try: @@ -680,11 +715,30 @@ def search_issue_bodies(self, repo: str, phrase: str) -> list[IssueSearchHit]: break return hits - def count_workflows(self, repo: str) -> int: - """How many GitHub Actions workflows the repository has (#3767). One item of one page - holds the total, so the read lists no workflow.""" - path = _repo_path(repo, "actions/workflows?per_page=1") - return _read_as(_WorkflowCount, self._session.rest("GET", path), path=path).total_count + def pull_request_workflow_at(self, repo: str, ref: str) -> bool: + """Whether a workflow at `ref` can start a check on a pull request (#5144). + + It lists the workflow files of `.github/workflows` at `ref` and reads each one's triggers: + a workflow that lists `pull_request` or `pull_request_target` can start a check. A + repository with no workflow file, or none with such a trigger, has no CI for the pull + request. A read that fails raises the session's error, so its caller keeps the pending + check rather than call it no CI. A directory answer that is no list reads as no workflow. + """ + endpoint = _repo_path(repo, f"contents/{_WORKFLOWS_DIR}?{urlencode({'ref': ref})}") + try: + answer = self._session.rest("GET", endpoint) + except GitHubNotFoundError: + return False + if not isinstance(answer, list): + return False + for item in answer: + entry = _read_as(_DirectoryEntry, item, path=endpoint) + if entry.type != "file" or not entry.name.endswith((".yml", ".yaml")): + continue + text = self.get_file_at(repo, entry.path, ref) + if text is not None and _runs_on_pull_request(text): + return True + return False def get_job_run_times( self, repo: str, *, workflow: str, branch: str, job: str, count: int diff --git a/src/devops_cli/github/merge_readiness.py b/src/devops_cli/github/merge_readiness.py index 6e42e03f0e..8986a4c52a 100644 --- a/src/devops_cli/github/merge_readiness.py +++ b/src/devops_cli/github/merge_readiness.py @@ -34,7 +34,7 @@ CONST_PR_CLOSING_ISSUES_PAGE, ) from devops_cli.core.repo import find_repo_root -from devops_cli.exceptions.git import GitHubOperationError +from devops_cli.exceptions.git import GitHubOperationError, GitHubUnreadError from devops_cli.github.check_verdict import ( CheckBucket, CheckVerdictSummary, @@ -126,7 +126,8 @@ class MergeReadiness: `pending_checks` names the checks still running, a blocker unless `allow_pending_checks` excused them. `checks` is the read of the head commit's checks, None when the payload names no head commit. `threads_to_show` are the review threads that block it, for a caller to list. - `grounding` is what the item rules judged, None where they do not apply. + `grounding` is what the item rules judged, None where they do not apply. `no_ci` is true when + no workflow can start a check on the pull request, so the missing checks block nothing. """ blocking: tuple[Blocker, ...] = () @@ -135,6 +136,7 @@ class MergeReadiness: checks: CheckVerdictSummary | None = None threads_to_show: tuple[ReviewThread, ...] = () grounding: Grounding | None = None + no_ci: bool = False @property def blockers(self) -> tuple[str, ...]: @@ -162,6 +164,7 @@ class _Verdict: checks: CheckVerdictSummary | None = None threads: list[ReviewThread] = field(default_factory=list) grounding: Grounding | None = None + no_ci: bool = False def block(self, kind: BlockerKind, text: str) -> None: self.blocking.append(Blocker(kind, text)) @@ -180,6 +183,7 @@ def frozen(self) -> MergeReadiness: checks=self.checks, threads_to_show=tuple(self.threads), grounding=self.grounding, + no_ci=self.no_ci, ) @@ -256,6 +260,19 @@ def _judge_draft(verdict: _Verdict, pr_data: dict[str, Any], pr_num: int, allow: ) +def _can_run_on_pull_request(owner: str, repo_name: str, head_sha: str, reads: _Reads) -> bool: + """Whether a workflow at `head_sha` can start a check on the pull request. + + A repository with no such workflow has no CI for the pull request (#5144). A read that fails + returns True, so the pending check stays: an unread workflow is no proof of no CI. + """ + try: + session = reads.session or get_github_session() + return session.client.pull_request_workflow_at(f"{owner}/{repo_name}", head_sha) + except GitHubOperationError, GitHubUnreadError: + return True + + def _judge_checks( verdict: _Verdict, head_sha: str, @@ -267,7 +284,8 @@ def _judge_checks( """Failing or unread checks block; running ones block unless excused. With `commit_statuses` off, the checks are the check runs only: a token without the `statuses` - permission reads them, and no request goes to the commit status endpoint (#2877).""" + permission reads them, and no request goes to the commit status endpoint (#2877). A head + commit that reports no check is no blocker where no workflow can start one (#5144).""" if not head_sha: return if reads.commit_statuses: @@ -295,6 +313,12 @@ def _judge_checks( BlockerKind.CHECKS_FAILING, f"PR #{pr_num} has {len(failing)} failing check(s): {', '.join(failing)}.", ) + if checks.reports_nothing and not _can_run_on_pull_request(owner, repo_name, head_sha, reads): + verdict.no_ci = True + verdict.inform( + MESSAGES.pr.readiness_no_ci.format(repo=f"{owner}/{repo_name}", number=pr_num) + ) + return verdict.pending.extend(pending) if not pending: return diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 6099843ba7..a50ffc542c 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -1749,8 +1749,12 @@ class PRMessages: pr_marked_ready_success: str = "PR #{number} marked as ready for review." pr_already_ready: str = "PR #{number} is already marked ready for review." ready_no_ci: str = ( - "{repo} has no GitHub Actions workflow, and PR #{number} has no checks. No check will " - "start, so there is nothing to wait for." + "{repo} has no workflow that runs on a pull request, and PR #{number} has no checks. " + "No check will start, so there is nothing to wait for." + ) + readiness_no_ci: str = ( + "{repo} has no workflow that runs on a pull request, and PR #{number} has no checks. " + "No check will start, so there is nothing to wait for." ) pr_already_merged: str = "PR #{number} is already merged into base branch '{base}'." pr_closed_unmerged: str = "PR #{number} is closed without being merged." diff --git a/tests/commands/test_pr.py b/tests/commands/test_pr.py index 49096e8dc6..346f0ffef1 100644 --- a/tests/commands/test_pr.py +++ b/tests/commands/test_pr.py @@ -461,21 +461,51 @@ def _ready(cli: Callable[..., Any], *flags: str) -> tuple[int, str]: return result.exit_code, " ".join(result.output.split()) -_WORKFLOWS = f"/repos/{_REPO}/actions/workflows?per_page=1" +_WORKFLOWS_DIR = f"/repos/{_REPO}/contents/.github/workflows?ref={_HEAD}" +_PULL_REQUEST_WORKFLOW = """name: CI +on: + pull_request: +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: "true" +""" +_PUSH_ONLY_WORKFLOW = """name: Release +on: [push, workflow_dispatch] +jobs: + release: + runs-on: ubuntu-latest + steps: + - run: "true" +""" def _no_checks(github: _GitHub, workflows: int | None) -> None: - """The head commit reports no check run and no commit status. The repository has `workflows` - GitHub Actions workflows, and None leaves their read unanswered.""" + """The head commit reports no check run and no commit status. `workflows` says what the head + holds: 0 no workflow at all, 1 a push-only workflow, 2 a pull-request workflow, and None an + unread workflow folder.""" github.checks() github.answer( "/status", ProcessAnswer(stdout=json.dumps({"state": "pending", "statuses": [], "total_count": 0})), ) - if workflows is not None: - github.api.route( - "GET", _WORKFLOWS, github_json({"total_count": workflows, "workflows": []}) - ) + if workflows == 0: + return + if workflows is None: + github.api.route("GET", _WORKFLOWS_DIR, github_json({"message": "Forbidden"}, status=403)) + return + name, text = ( + ("ci.yml", _PULL_REQUEST_WORKFLOW) + if workflows == 2 + else ("release.yml", _PUSH_ONLY_WORKFLOW) + ) + github.api.route( + "GET", + _WORKFLOWS_DIR, + github_json([{"type": "file", "name": name, "path": f".github/workflows/{name}"}]), + ) + route_file(github.api, _REPO, f".github/workflows/{name}", _HEAD, text) _SCENARIOS = { @@ -500,7 +530,7 @@ def _no_checks(github: _GitHub, workflows: int | None) -> None: ("unresolved-thread", 0, True), ("no-ci", 0, True), ("checks-not-started", 8, False), - ("workflows-unread", 1, False), + ("workflows-unread", 8, False), ], ) def test_pr_ready_exits_on_the_checks_of_the_verdict( @@ -551,7 +581,31 @@ def test_pr_ready_says_that_a_repository_with_no_ci_has_nothing_to_wait_for( exit_code, output = _ready(cli) assert ( exit_code, - f"{_REPO} has no GitHub Actions workflow" in output, + f"{_REPO} has no workflow that runs on a pull request" in output, + "no checks reported" in output, + ) == (0, True, False), output + + +def test_pr_ready_marks_a_pull_request_ready_when_only_push_workflows_exist( + cli: Callable[..., Any], draft: _GitHub +) -> None: + """A workflow that only runs on push cannot start a check on the pull request, so `pr ready` + reads the head's workflows rather than the repository's workflow count (#5144).""" + _no_checks(draft, 1) + exit_code, output = _ready(cli) + assert (exit_code, _readied(draft), "has no checks" in output) == (0, True, True), output + + +def test_check_readiness_reports_a_repository_with_no_ci( + cli: Callable[..., Any], github: _GitHub +) -> None: + """The pending stand-in for a head commit with no check does not block where no workflow can + start one, and the verdict says why (#5144).""" + _no_checks(github, 0) + exit_code, output = _readiness(cli) + assert ( + exit_code, + "has no workflow that runs on a pull request" in output, "no checks reported" in output, ) == (0, True, False), output @@ -817,6 +871,31 @@ def test_the_monitor_waits_for_the_checks_and_names_every_blocker( ) == (1, 2, True, True), output +def test_the_monitor_reports_a_conflict_before_it_waits_for_a_check( + cli: Callable[..., Any], monitored: _GitHub, clock: ClockFake +) -> None: + """A dirty pull request in a repository with no CI names the conflict and settles at once + instead of waiting for the pending stand-in (#5144).""" + monitored.pull(_pr(mergeable=False, mergeable_state="dirty")) + _no_checks(monitored, 0) + exit_code, output = _monitor(cli, "--timeout", "600") + assert ( + exit_code, + clock.waits, + "PR #335 has merge conflicts with base branch 'main'." in output, + ) == (2, [], True), output + + +def test_the_monitor_does_not_wait_for_a_repository_with_no_ci( + cli: Callable[..., Any], monitored: _GitHub, clock: ClockFake +) -> None: + """No check can start without a pull-request workflow, so the monitor settles on the first + poll and sleeps for nothing instead of waiting out the timeout (#5144).""" + _no_checks(monitored, 0) + exit_code, output = _monitor(cli, "--timeout", "600") + assert (exit_code, clock.waits, "READY FOR MERGING" in output) == (0, [], True), output + + def test_a_missing_priority_label_warns_and_pr_ready_still_marks_it( cli: Callable[..., Any], draft: _GitHub ) -> None: diff --git a/tests/github/test_merge_readiness.py b/tests/github/test_merge_readiness.py index 324c703bbc..1ba8c959f7 100644 --- a/tests/github/test_merge_readiness.py +++ b/tests/github/test_merge_readiness.py @@ -33,6 +33,7 @@ github_json, next_page, route_compare_files, + route_file, ) from tests.support.fakes.process import ProcessAnswer, ProcessFake @@ -46,6 +47,40 @@ _COMPARE = f"/repos/{_REPO}/compare/main...{_HEAD}?per_page=1" _STATUS = f"repos/{_REPO}/commits/{_HEAD}/status" _CHANGES_DIR = f"repos/{_REPO}/contents/openspec/changes?ref={_BASE}" +_WORKFLOWS_DIR = f"/repos/{_REPO}/contents/.github/workflows?ref={_HEAD}" +_PULL_REQUEST_WORKFLOW = """name: CI +on: + pull_request: +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: "true" +""" +_PUSH_ONLY_WORKFLOW = """name: Release +on: [push, workflow_dispatch] +jobs: + release: + runs-on: ubuntu-latest + steps: + - run: "true" +""" +_STRING_PULL_REQUEST_WORKFLOW = """name: CI +on: pull_request +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: "true" +""" +_NO_TRIGGER_WORKFLOW = """name: None +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: "true" +""" +_INVALID_WORKFLOW = "name: [unclosed\n" _THREADS = "GetReviewThreads" _CLOSING = "closingIssuesReferences" _ARCHIVE_704 = { @@ -156,6 +191,15 @@ def closing(self, *issues: dict[str, Any], total: int | None = None) -> None: payload = {"data": {"repository": {"pullRequest": {"closingIssuesReferences": references}}}} self.answer(_CLOSING, ProcessAnswer(stdout=json.dumps(payload))) + def workflows(self, *files: tuple[str, str]) -> None: + """Answer the head's workflow folder with `files`, each named and holding its text.""" + entries = [ + {"type": "file", "name": name, "path": f".github/workflows/{name}"} for name, _ in files + ] + self.api.route("GET", _WORKFLOWS_DIR, github_json(entries)) + for name, text in files: + route_file(self.api, _REPO, f".github/workflows/{name}", _HEAD, text) + def gh_sent(self) -> list[str]: """Each gh command run, as one string.""" return [" ".join(call.argv) for call in self.gh.calls] @@ -504,12 +548,104 @@ def test_the_verdict_keeps_the_checks_it_read(github: _GitHub, tmp_path: Path) - ] -def test_a_commit_with_no_check_and_no_status_is_still_running( +def test_a_commit_with_no_check_waits_while_a_pull_request_workflow_can_start_one( github: _GitHub, tmp_path: Path ) -> None: github.checks() + github.workflows(("ci.yml", _PULL_REQUEST_WORKFLOW)) verdict = _assess(tmp_path) assert verdict.blockers == ("PR #335 has 1 check(s) still running: no checks reported.",) + assert verdict.no_ci is False + + +def test_a_repository_with_no_pull_request_workflow_has_no_ci( + github: _GitHub, tmp_path: Path +) -> None: + """The head commit reports no check and no workflow at it runs on a pull request, so no check + can start: the missing check blocks nothing and an INFO advisory says why (#5144).""" + github.checks() + verdict = _assess(tmp_path) + assert (verdict.kinds, verdict.pending_checks, verdict.no_ci) == (frozenset(), (), True) + assert [(advisory.level, advisory.text) for advisory in verdict.advisories] == [ + ( + AdvisoryLevel.INFO, + "dan-petty/devops-cli has no workflow that runs on a pull request, and PR #335 has " + "no checks. No check will start, so there is nothing to wait for.", + ) + ] + + +def test_a_workflow_with_only_push_and_dispatch_triggers_has_no_ci( + github: _GitHub, tmp_path: Path +) -> None: + github.checks() + github.workflows(("release.yml", _PUSH_ONLY_WORKFLOW)) + verdict = _assess(tmp_path) + assert (verdict.kinds, verdict.no_ci) == (frozenset(), True) + + +def test_an_unread_workflow_keeps_the_pending_check(github: _GitHub, tmp_path: Path) -> None: + """A workflow read that fails is no proof of no CI, so the pending check stays and blocks.""" + github.checks() + github.api.route("GET", _WORKFLOWS_DIR, github_json({"message": "Forbidden"}, status=403)) + verdict = _assess(tmp_path) + assert (BlockerKind.CHECKS_PENDING in verdict.kinds, verdict.no_ci) == (True, False) + + +def test_a_string_pull_request_trigger_keeps_the_pending_check( + github: _GitHub, tmp_path: Path +) -> None: + github.checks() + github.workflows(("ci.yml", _STRING_PULL_REQUEST_WORKFLOW)) + verdict = _assess(tmp_path) + assert (BlockerKind.CHECKS_PENDING in verdict.kinds, verdict.no_ci) == (True, False) + + +def test_a_workflow_file_that_is_no_mapping_has_no_ci(github: _GitHub, tmp_path: Path) -> None: + github.checks() + github.workflows(("list.yml", "- one\n- two\n")) + verdict = _assess(tmp_path) + assert (verdict.kinds, verdict.no_ci) == (frozenset(), True) + + +def test_a_workflow_with_no_trigger_has_no_ci(github: _GitHub, tmp_path: Path) -> None: + github.checks() + github.workflows(("none.yml", _NO_TRIGGER_WORKFLOW)) + verdict = _assess(tmp_path) + assert (verdict.kinds, verdict.no_ci) == (frozenset(), True) + + +def test_a_workflow_file_that_is_not_valid_yaml_keeps_the_pending_check( + github: _GitHub, tmp_path: Path +) -> None: + github.checks() + github.workflows(("broken.yml", _INVALID_WORKFLOW)) + verdict = _assess(tmp_path) + assert (BlockerKind.CHECKS_PENDING in verdict.kinds, verdict.no_ci) == (True, False) + + +def test_a_workflow_folder_entry_that_is_no_file_is_skipped( + github: _GitHub, tmp_path: Path +) -> None: + github.checks() + entries = [ + {"type": "dir", "name": "nested", "path": ".github/workflows/nested"}, + {"type": "file", "name": "README.md", "path": ".github/workflows/README.md"}, + {"type": "file", "name": "ci.yml", "path": ".github/workflows/ci.yml"}, + ] + github.api.route("GET", _WORKFLOWS_DIR, github_json(entries)) + route_file(github.api, _REPO, ".github/workflows/ci.yml", _HEAD, _PULL_REQUEST_WORKFLOW) + verdict = _assess(tmp_path) + assert BlockerKind.CHECKS_PENDING in verdict.kinds + + +def test_a_workflow_folder_answer_that_is_no_list_has_no_ci( + github: _GitHub, tmp_path: Path +) -> None: + github.checks() + github.api.route("GET", _WORKFLOWS_DIR, github_json({"type": "file"})) + verdict = _assess(tmp_path) + assert (verdict.kinds, verdict.no_ci) == (frozenset(), True) def test_a_failed_combined_commit_status_beyond_the_listed_ones_blocks( diff --git a/tests/support/roadmap_implement.py b/tests/support/roadmap_implement.py index ec9dbf5f96..ade76e3177 100644 --- a/tests/support/roadmap_implement.py +++ b/tests/support/roadmap_implement.py @@ -28,7 +28,13 @@ from devops_cli.roadmap.implement.implement_trace import ImplementTrace from devops_cli.roadmap.stores.store import ItemField, StageRecordKey from tests.support.fakes.clock import ClockFake -from tests.support.fakes.github import API, GitHubApiFake, github_json, route_compare_files +from tests.support.fakes.github import ( + API, + GitHubApiFake, + github_json, + route_compare_files, + route_file, +) from tests.support.fakes.process import ProcessAnswer, ProcessCall, ProcessFake from tests.support.fakes.roadmap_store import InMemoryRoadmapStore from tests.support.implement_step import WINDOW, command_text, git_for_real @@ -352,6 +358,17 @@ def long_run_trace() -> ImplementTrace: RUNNING: dict[str, Any] = {**PASS, "status": "in_progress", "conclusion": None} _PULL_API = f"api repos/{STAGE_REPO}/pulls/{PULL}" _THREADS_QUERY = "GetReviewThreads" + +# The repository's pull-request workflow, so a head commit with no check waits for one (#5144). +_WORKFLOW = """name: CI +on: + pull_request: +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: "true" +""" _ARCHIVED_FILE = { "filename": f"openspec/changes/archive/2026-10-29-{CHANGE}/proposal.md", "status": "added", @@ -453,6 +470,16 @@ def _route_checks(self, sha: str, runs: list[dict[str, Any]]) -> None: path = f"/repos/{STAGE_REPO}/commits/{sha}/check-runs?per_page=100" self.api.route("GET", path, github_json({"total_count": len(runs), "check_runs": runs})) + def _route_workflow(self, sha: str) -> None: + """Answer the head's workflow folder with the repository's pull-request workflow.""" + entry = {"type": "file", "name": "ci.yml", "path": ".github/workflows/ci.yml"} + self.api.route( + "GET", + f"/repos/{STAGE_REPO}/contents/.github/workflows?ref={sha}", + github_json([entry]), + ) + route_file(self.api, STAGE_REPO, ".github/workflows/ci.yml", sha, _WORKFLOW) + def _pull(self, _call: ProcessCall) -> subprocess.CompletedProcess[str]: if self.stale > 0: self.stale -= 1 @@ -463,6 +490,7 @@ def _pull(self, _call: ProcessCall) -> subprocess.CompletedProcess[str]: self.heads.append(sha) runs = self.runs[min(self.heads.index(sha), len(self.runs) - 1)] self._route_checks(sha, runs) + self._route_workflow(sha) route_compare_files(self.api, STAGE_REPO, "main", sha, _ARCHIVED_FILE, merge_base="c" * 40) repo = {"full_name": STAGE_REPO, "default_branch": "main"} dirty = self.conflict