From 547404c3c78646ed4d9f0b44d7b342cbdfd96e6e Mon Sep 17 00:00:00 2001 From: leolord Date: Thu, 15 Oct 2026 14:41:42 +0800 Subject: [PATCH 01/21] feat[ci]: add AI review disposition checks Problem: - AI review findings need explicit, auditable handling before merge. Solution: - Require each configured bot to complete review for the current PR head. - Validate authorized dispositions, supporting evidence, and resolved threads. - Add a reusable workflow, integration examples, and setup documentation. Test: - Add unit tests for disposition rules, permissions, pagination, and API failures. - Tests not run for this draft. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 70 +++ .gitignore | 3 + docs/AI_REVIEW_DISPOSITION.md | 156 +++++++ docs/examples/ai-review-disposition.yml | 34 ++ docs/examples/ai-review-events.yml | 17 + scripts/check_ai_review_disposition.py | 442 ++++++++++++++++++ scripts/tests/test_ai_review_disposition.py | 371 +++++++++++++++ 7 files changed, 1093 insertions(+) create mode 100644 .github/workflows/reusable-ai-review-disposition.yml create mode 100644 docs/AI_REVIEW_DISPOSITION.md create mode 100644 docs/examples/ai-review-disposition.yml create mode 100644 docs/examples/ai-review-events.yml create mode 100644 scripts/check_ai_review_disposition.py create mode 100644 scripts/tests/test_ai_review_disposition.py diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml new file mode 100644 index 0000000..ec4a970 --- /dev/null +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -0,0 +1,70 @@ +name: Reusable - AI Review Disposition + +on: + workflow_call: + inputs: + bot-logins: + description: 'Comma-separated GitHub logins; every bot must complete review' + required: true + type: string + pr-number: + description: 'PR to check; 0 checks all open PRs in the caller repository' + required: false + type: number + default: 0 + jira-url: + description: 'Optional trusted Jira base URL, e.g. https://example.atlassian.net' + required: false + type: string + default: '' + shared-ref: + description: 'Trusted revision of this repository; pin alongside workflow uses' + required: false + type: string + default: main + secrets: + shared-read-token: + description: 'Optional read-only token for checkout when shared CI repo is private' + required: false + +permissions: + contents: read + pull-requests: read + issues: read + checks: write + +jobs: + disposition: + name: Evaluate AI Review Dispositions + runs-on: ubuntu-latest + timeout-minutes: 15 + # All scans for a repository must serialize. Pending scans may be coalesced; + # each scan reads live state for every open PR, not an event snapshot. + concurrency: + group: ai-review-disposition-${{ github.repository }} + cancel-in-progress: false + steps: + - name: Checkout trusted shared scripts + uses: actions/checkout@v4 + with: + repository: IS-Model-Framework/.github + token: ${{ secrets.shared-read-token || github.token }} + ref: ${{ inputs.shared-ref }} + path: .ci-shared + persist-credentials: false + sparse-checkout: scripts + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.11' + + - name: Publish check on each PR head commit + env: + GH_TOKEN: ${{ github.token }} + AI_REVIEW_BOTS: ${{ inputs.bot-logins }} + AI_REVIEW_JIRA_URL: ${{ inputs.jira-url }} + PR_NUMBER: ${{ inputs.pr-number }} + run: | + python .ci-shared/scripts/check_ai_review_disposition.py \ + --pr-number "$PR_NUMBER" diff --git a/.gitignore b/.gitignore index b7faf40..d21fd39 100644 --- a/.gitignore +++ b/.gitignore @@ -205,3 +205,6 @@ cython_debug/ marimo/_static/ marimo/_lsp/ __marimo__/ + +*.DS_Store +*.serena diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md new file mode 100644 index 0000000..3dba504 --- /dev/null +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -0,0 +1,156 @@ +# AI Review / Disposition Check + +目标:所有需要响应的 AI inline findings 都有可审计的处理记录,并且对话已 Resolve。检查不要求采纳 AI 建议,也不代替 Human Review。 + +本仓库提供 [Python 检查器](../scripts/check_ai_review_disposition.py)、[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) 和两个项目接入示例。规则单独运行,不并入现有 `CI Result`:代码 CI 与 review 的完成时间不同,回复评论也不应该重新运行测试。 + +## 合并条件 + +```text +每个指定 AI Bot 已完成当前 head SHA 的 review +AND 每个 AI finding 有授权人员的有效 disposition +AND 每个 finding 的 conversation 已 Resolve +``` + +检查范围为配置的 Bot 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding;Bot 应把不同问题分成不同 threads。以人类评论开头的 thread 不计入,PR 顶层评论/总结也不计为 finding。尚未提交的 pending review 不计入已发布 findings。 + +Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。`AI_REVIEW_BOTS` 中的每个 Bot 都必须完成 review。空配置是错误,不会当作“无 AI 问题”通过。 + +回复者必须是 PR 作者或当前拥有仓库 `write` / `maintain` / `admin` 权限的人员。其他人员的回复不生效;GitHub Bot 和已配置的 AI 服务账号不能自行 disposition。仅有组织成员身份不足以授权回复。 + +| Disposition | 必须提供的字段 | 检查的证据 | +| --- | --- | --- | +| Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,必须仍在当前 PR 的 commits 中 | +| Rejected | `Reason` | 非空拒绝理由 | +| Invalid | `Reason` | 非空误报理由 | +| Deferred | `Reason`、`Tracking` | 存在且开放的 GitHub Issue,或指定 Jira 域名下的 ticket URL | + +`Fix` 证明提交引用有效;工具不判断该提交是否真正修复问题。理由的充分性、Jira ticket 的存在与状态,以及 deferral 的业务可接受性由 Human Review 审查。当前版本不支持无 tracking 的口头豁免;若未来接入审批,应验证审批人的身份及审批记录,而不是接受 Contributor 自填 `Approved: yes`。 + +## Contributor 回复格式 + +直接在对应 inline thread 中回复。第一行必须是 `Disposition: ...`,每个字段单独一行;允许空行和字段名/状态大小写变化。不要加引号、Markdown 引用、代码块或额外字段。`Reason` 保持一行,可以用中文。 + +Accepted: + +```text +Disposition: Accepted +Reason: 已补充空数组边界判断,并增加回归测试。 +Fix: 0123456789abcdef0123456789abcdef01234567 +``` + +Rejected: + +```text +Disposition: Rejected +Reason: 调用入口已验证该条件,此处不会收到负数输入。 +``` + +Invalid: + +```text +Disposition: Invalid +Reason: 此实现使用异步执行,评论所述的同步调用路径不存在。 +``` + +Deferred: + +```text +Disposition: Deferred +Reason: 本次先完成兼容修复,性能优化在后续版本处理。 +Tracking: https://github.com/IS-Model-Framework/example/issues/42 +``` + +配置 `AI_REVIEW_JIRA_URL=https://example.atlassian.net` 后,也接受 `Tracking: https://example.atlassian.net/browse/PROJ-123`。不接受任意 HTTPS 链接、裸 ticket 编号或 PR 链接。GitHub Issue 需要当前 token 可读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 + +采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。AI 编辑 finding 或追加 inline 回复后,需要重新确认 disposition,并重新提交完成 review 的标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 + +有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 + +## AI Bot 完成协议 + +Bot 的 review 流程必须遵守: + +1. 对固定的 PR head SHA 生成 findings,用 inline threads 发布。 +2. 全部 findings 发布完毕后,提交一个非 pending 的 review,其正文包含独立一行: + + ```text + AI-Review-Complete: <当前 PR 的完整 head SHA> + ``` + +3. review 本身的 `commit.oid` 也必须等于该 SHA。没有 findings 时仍需要这个 review;这样“零问题”和“尚未开始 review”不会混淆。 +4. 当前 head 改变后,重新 review 并提交新完成标记。后续提交的新 review 未含标记、review 被 dismissed,或者 Bot 在完成标记之后继续增加/编辑 finding,均阻断通过。 + +这是本工具的集成协议,不是 GitHub 自带的字段。现有 Bot 若不能提供该标记,需要修改其发布流程;不能仅凭 “没有 unresolved threads” 推断 review 已完成。不要在 findings 尚未全部发布时写入完成标记。 + +## Actions 接入 + +`.github` 仓库的 workflow 不会自动在所有组织项目执行。每个目标项目需要 caller workflow,并由组织 ruleset 覆盖目标仓库。 + +1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 与 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 复制到目标项目 `.github/workflows/`,合入默认分支。 +2. 在组织/仓库 Variables 设置 `AI_REVIEW_BOTS` 为准确的 login 列表,逗号分隔。需要 Jira 时设置 `AI_REVIEW_JIRA_URL`。示例中的 Bot 名称不是实际默认配置。 +3. 生产环境将 caller 的 `uses: ...@main` 与 `shared-ref: main` 同时固定到本仓库同一个已审核 commit SHA。共享脚本从可信 CI 仓库加载,完全不 checkout PR 代码。 +4. 为 `GITHUB_TOKEN` 提供 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。如果组织 CI 仓库是 private,还需要开启 reusable workflow 的组织访问,并通过可选 secret `shared-read-token` 提供 CI 仓库的只读 checkout token;caller 的 `GITHUB_TOKEN` 不会自动获得其他 private 仓库的读取权限。 +5. 完成一次运行后,将 **`AI Review / Disposition Check`** 加入 ruleset 的 Required Status Checks,检查来源选择 GitHub Actions。保持现有 Human Review / approval 规则。 + +选择的是脚本通过 Checks API 发布到 PR **head commit** 上的 Check,不是 `Evaluate AI Review Dispositions` 这个 Actions job。`pull_request_target`、`issue_comment`、`workflow_run` 的 `GITHUB_SHA` 不一定是 PR head;直接使用 job success 作合并门禁会关联到错误提交。 + +| 事件 | 示例中的路径 | +| --- | --- | +| PR opened / reopened / synchronize / ready_for_review | `pull_request_target` 调用可信检查器 | +| Review submitted / edited / dismissed | 无权限的 event collector → 默认分支 `workflow_run` → 检查器 | +| Inline comment created / edited / deleted | 同上 | +| PR 顶层评论 created / edited / deleted | `issue_comment` 触发复查,可用一条 “AI review recheck” 评论重新计算 | +| Resolve / Unresolve | Actions 不直接支持此事件;手动复查、顶层评论,或 App webhook → `repository_dispatch` | +| Bot 用 `GITHUB_TOKEN` 发布 review/comments | 通常不会触发后续 Actions;review workflow 结束后显式复查,或改用 App token 发布 | + +collector 不运行 PR 内容、不上传 artifact。后续有写权限的 `workflow_run` 不信任 collector 输出,而是读取 GitHub API 的实时状态,支持 fork PR 的评论事件。每次默认检查所有 open PR,绕开 fork 的 `workflow_run.pull_requests` 可能为空,以及同一 PR 密集事件被 concurrency 合并的问题。 + +所有扫描使用仓库级 concurrency,`cancel-in-progress: false`。发布 Check 后发生 API 错误会标记 failure;超时/取消可能留下 in-progress Check,仍然阻止合并。通过之前再完整读取一次 review 数据,发现提交或评论变化就失败。扫描规模大时应改用 App,按 PR 串行处理。 + +手动复查可在 Actions 页面运行 `AI Review Disposition`。单独调试某个 PR: + +```bash +GH_TOKEN="" python scripts/check_ai_review_disposition.py \ + --repository IS-Model-Framework/example \ + --pr-number 128 \ + --bots 'reviewer[bot]' +``` + +这条命令会通过 Checks API 写入 PR Check,不是 dry-run。Token 通过环境变量提供;不应提交到仓库。未指定 PR(`--pr-number 0`)时检查全部 open PR。退出码:0 全部通过,1 存在未处理项,2 参数/API 等执行错误。 + +## 严格组织门禁:GitHub App + +Actions 方案适合初期接入,但不保证评论变化后瞬间撤销 success:事件排队、运行延迟、Resolve/Unresolve 缺少原生 trigger,都会留下状态更新窗口。需要严格覆盖 thread 状态变化时,建议组织安装专用 GitHub App,用同一个检查器作为执行核心: + +```mermaid +flowchart LR + A[PR / Review / Comment / Thread webhook] --> B[验证签名并按 PR 串行排队] + B --> C[将当前 head 的固定 Check 标记 in_progress] + C --> D[分页读取实时 reviews / threads / comments / commits] + D --> E{完成协议 + disposition + resolved} + E -->|满足| F[success] + E -->|未满足或 API 失败| G[failure] + F --> H[Human Review 与 Required Approval] +``` + +App 应订阅 `pull_request`、`pull_request_review`、`pull_request_review_comment`、`pull_request_review_thread` 的相关 actions,并支持 Check rerequest;用 webhook signature 与 delivery ID 校验/去重,每个 PR 串行更新同一个 head 的 Check,变化时立即撤销旧 success。重试失败保持阻断,并以定期 reconciliation 恢复漏发/丢失事件。 + +权限为 Pull requests read、Contents read、Issues read、Checks write;安装 token 只覆盖获授权仓库。若调用跨仓库 Issue,需要相应仓库访问权限。当前提交未包含 App 的 webhook 服务、部署或持久化账本。 + +GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和“执行 merge”做成一个原子事务。高要求场景还应启用分支保护的 conversation resolution,并通过受控 merge 入口在合并前再次核验。AI findings 被删除后,实时 API 不再保留它们;若要求删除也必须留痕,App 需要持久化 finding ID 与 disposition 历史。此版本不会把 API 数据当作不可删改的审计账本。 + +该 Check 以 PR head 为对象;当前不支持 merge queue 生成的合成 SHA。使用 merge queue 的项目需要另外设计 `merge_group` 的成员 PR 核验,不能直接沿用此 caller 作为队列 required check。 + +## 验证与参考 + +```bash +python -m unittest discover -s scripts/tests -v +``` + +测试覆盖处理状态、回复权限、完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot Review → 回复 → Resolve → 复查 → Required Check 试运行。 + +- [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) +- [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) +- [Checks API:发布并更新 Check Runs](https://docs.github.com/en/rest/checks/runs) +- [Reusable workflows 的组织接入与权限](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml new file mode 100644 index 0000000..3cb4732 --- /dev/null +++ b/docs/examples/ai-review-disposition.yml @@ -0,0 +1,34 @@ +# Copy to each project's .github/workflows/ai-review-disposition.yml. +# Both this file and the event collector must exist on the default branch. +name: AI Review Disposition + +on: + pull_request_target: + types: [opened, reopened, synchronize, ready_for_review] + workflow_run: + workflows: [AI Review Events] + types: [completed] + issue_comment: + types: [created, edited, deleted] + repository_dispatch: + types: [ai-review-state-changed] + workflow_dispatch: + +permissions: + contents: read + pull-requests: read + issues: read + checks: write + +jobs: + disposition: + if: ${{ github.event_name != 'issue_comment' || github.event.issue.pull_request }} + uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main + with: + # Set this repository/organization variable to exact bot logins. + bot-logins: ${{ vars.AI_REVIEW_BOTS }} + jira-url: ${{ vars.AI_REVIEW_JIRA_URL }} + shared-ref: main + # If the shared CI repository is private: + # secrets: + # shared-read-token: ${{ secrets.CI_READ_TOKEN }} diff --git a/docs/examples/ai-review-events.yml b/docs/examples/ai-review-events.yml new file mode 100644 index 0000000..f97de8b --- /dev/null +++ b/docs/examples/ai-review-events.yml @@ -0,0 +1,17 @@ +# Copy to each project's .github/workflows/ai-review-events.yml. +# This unprivileged collector never checks out or executes PR code. +name: AI Review Events + +on: + pull_request_review: + types: [submitted, edited, dismissed] + pull_request_review_comment: + types: [created, edited, deleted] + +permissions: {} + +jobs: + notify: + runs-on: ubuntu-latest + steps: + - run: echo "AI review state changed; trusted evaluator will read live API state" diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py new file mode 100644 index 0000000..a4b7cea --- /dev/null +++ b/scripts/check_ai_review_disposition.py @@ -0,0 +1,442 @@ +#!/usr/bin/env python3 +"""Check AI review completion and explicit dispositions without running PR code.""" + +import argparse +import json +import os +import re +import sys +from collections import Counter +from urllib.error import HTTPError +from urllib.parse import quote, urlparse +from urllib.request import Request, urlopen + +CHECK_NAME = "AI Review / Disposition Check" +STATUSES = ("Accepted", "Rejected", "Deferred", "Invalid") +AUTHOR_FIELDS = "author { login __typename }" +COMMENT_FIELDS = f""" + id body url createdAt updatedAt {AUTHOR_FIELDS} + pullRequestReview {{ state }} +""" +PAGE_FIELDS = "pageInfo { hasNextPage endCursor }" + + +def actor_login(author): + author = author or {} + login = author.get("login", "").lower() + if author.get("__typename") == "Bot" and not login.endswith("[bot]"): + login += "[bot]" + return login + + +class GitHub: + def __init__(self, token, api_url): + self.token = token + self.api_url = api_url.rstrip("/") + self.graphql_url = ( + "https://api.github.com/graphql" + if self.api_url == "https://api.github.com" + else self.api_url.removesuffix("/v3") + "/graphql" + ) + + def request(self, method, path, body=None): + url = self.graphql_url if path == "graphql" else self.api_url + path + request = Request( + url, + data=json.dumps(body).encode() if body is not None else None, + method=method, + headers={ + "Authorization": f"Bearer {self.token}", + "Accept": "application/vnd.github+json", + "Content-Type": "application/json", + }, + ) + with urlopen(request, timeout=30) as response: + return json.load(response) + + def graphql(self, query, variables): + result = self.request("POST", "graphql", {"query": query, "variables": variables}) + if result.get("errors"): + raise RuntimeError("GitHub GraphQL returned errors; refusing partial data") + return result["data"] + + def connection(self, repository, number, field, selection): + owner, name = repository.split("/") + cursor = None + nodes = [] + while True: + query = f""" + query($owner: String!, $name: String!, $number: Int!, $cursor: String) {{ + repository(owner: $owner, name: $name) {{ + pullRequest(number: $number) {{ + {field}(first: 100, after: $cursor) {{ + nodes {{ {selection} }} {PAGE_FIELDS} + }} + }} + }} + }} + """ + data = self.graphql( + query, {"owner": owner, "name": name, "number": number, "cursor": cursor} + ) + page = data["repository"]["pullRequest"][field] + nodes.extend(page["nodes"]) + if not page["pageInfo"]["hasNextPage"]: + return nodes + cursor = page["pageInfo"]["endCursor"] + + def comments(self, thread): + page = thread.pop("comments") + comments = list(page["nodes"]) + while page["pageInfo"]["hasNextPage"]: + query = f""" + query($id: ID!, $cursor: String) {{ + node(id: $id) {{ ... on PullRequestReviewThread {{ + comments(first: 100, after: $cursor) {{ + nodes {{ {COMMENT_FIELDS} }} {PAGE_FIELDS} + }} + }} }} + }} + """ + data = self.graphql( + query, {"id": thread["id"], "cursor": page["pageInfo"]["endCursor"]} + ) + page = data["node"]["comments"] + comments.extend(page["nodes"]) + return comments + + def open_prs(self, repository): + page = 1 + while True: + pulls = self.request( + "GET", f"/repos/{repository}/pulls?state=open&per_page=100&page={page}" + ) + yield from (pr["number"] for pr in pulls) + if len(pulls) < 100: + return + page += 1 + + +def snapshot(api, repository, number): + pr = api.request("GET", f"/repos/{repository}/pulls/{number}") + reviews = api.connection( + repository, + number, + "reviews", + f"id body state submittedAt {AUTHOR_FIELDS} commit {{ oid }}", + ) + threads = api.connection( + repository, + number, + "reviewThreads", + f"""id isResolved isOutdated + comments(first: 100) {{ nodes {{ {COMMENT_FIELDS} }} {PAGE_FIELDS} }}""", + ) + for thread in threads: + thread["comments"] = api.comments(thread) + commits = api.connection(repository, number, "commits", "commit { oid }") + current = api.request("GET", f"/repos/{repository}/pulls/{number}") + if current["head"]["sha"] != pr["head"]["sha"]: + raise RuntimeError("PR head changed while reading review data; rerun required") + return { + "head": pr["head"]["sha"], + "author": pr["user"]["login"].lower(), + "state": current["state"], + "reviews": reviews, + "threads": threads, + "commits": [node["commit"]["oid"] for node in commits], + } + + +def parse_disposition(body): + lines = [line.strip() for line in body.strip().splitlines() if line.strip()] + if not lines or not lines[0].lower().startswith("disposition:"): + return None + fields = {} + for line in lines: + key, separator, value = line.partition(":") + key = key.lower() + if ( + not separator + or key not in {"disposition", "reason", "fix", "tracking"} + or key in fields + or not value.strip() + ): + return {"error": "Use one nonempty value per field, without duplicate fields"} + fields[key] = value.strip() + status = fields["disposition"].capitalize() + if status not in STATUSES: + return {"error": "Disposition must be Accepted / Rejected / Deferred / Invalid"} + fields["disposition"] = status + if not fields.get("reason"): + fields["error"] = "Reason is required" + return fields + + +def tracking_target(value, server_url, jira_url): + server = urlparse(server_url) + target = urlparse(value) + if target.query or target.fragment or target.username or target.password: + return None + if target.scheme == server.scheme and target.netloc == server.netloc: + prefix = server.path.rstrip("/") + match = re.fullmatch( + re.escape(prefix) + r"/([\w.-]+)/([\w.-]+)/issues/([1-9]\d*)", target.path + ) + if match: + return ("github", *match.groups()) + if jira_url: + jira = urlparse(jira_url.rstrip("/")) + if ( + target.scheme == "https" + and target.netloc == jira.netloc + and re.fullmatch( + re.escape(jira.path) + r"/browse/[A-Z][A-Z0-9_]*-[1-9]\d*", target.path + ) + ): + return ("jira", value) + return None + + +def evaluate(data, bots, authorized, tracking_valid): + """Pure policy; API-dependent identity and tracking checks are supplied by caller.""" + errors = [] + findings = [] + completed_at = {} + for bot in sorted(bots): + reviews = [ + review + for review in data["reviews"] + if actor_login(review.get("author")) == bot and review["state"] != "PENDING" + ] + latest = max(reversed(reviews), key=lambda r: r["submittedAt"] or "", default=None) + marker = f"AI-Review-Complete: {data['head']}" + if ( + not latest + or latest["state"] == "DISMISSED" + or (latest.get("commit") or {}).get("oid") != data["head"] + or marker not in [line.strip() for line in latest["body"].splitlines()] + ): + errors.append(f"{bot}: missing completed review for current head") + else: + completed_at[bot] = latest["submittedAt"] + + for thread in data["threads"]: + comments = [ + comment + for comment in thread["comments"] + if (comment.get("pullRequestReview") or {}).get("state") != "PENDING" + ] + if not comments: + continue + root = comments[0] + if actor_login(root.get("author")) not in bots: + continue + for bot in bots: + if bot in completed_at and any( + actor_login(c.get("author")) == bot and c["updatedAt"] > completed_at[bot] + for c in comments + ): + error = f"{bot}: findings changed after review completion" + if error not in errors: + errors.append(error) + bot_activity = max( + c["updatedAt"] for c in comments if actor_login(c.get("author")) in bots + ) + candidates = [] + for comment in comments[1:]: + author = comment.get("author") or {} + login = actor_login(author) + fields = parse_disposition(comment["body"]) + if ( + fields is not None + and author.get("__typename") == "User" + and login not in bots + and authorized(login, data["author"]) + ): + candidates.append((comment, fields)) + latest = max(reversed(candidates), key=lambda c: c[0]["updatedAt"], default=None) + status = "Unaddressed" + reason = "No authorized disposition reply" + if latest: + comment, fields = latest + status = fields.get("disposition", "Unaddressed") + reason = fields.get("error", "") + if comment["updatedAt"] < bot_activity: + reason = "AI comment changed after disposition; reply again" + elif not reason and status == "Accepted": + fix = fields.get("fix", "").lower() + if not re.fullmatch(r"[0-9a-f]{40}", fix) or fix not in data["commits"]: + reason = "Fix must be a full commit SHA in the current PR" + elif not reason and status == "Deferred": + if not tracking_valid(fields.get("tracking", "")): + reason = "Tracking must reference an open GitHub issue or configured Jira URL" + if not reason and not thread["isResolved"]: + reason = "Disposition is valid; resolve the conversation" + findings.append({ + "id": thread["id"], + "url": root["url"], + "status": status, + "error": reason, + }) + return {"errors": errors, "findings": findings} + + +def passed(result): + return not result["errors"] and not any(f["error"] for f in result["findings"]) + + +def summary(number, head, result): + counts = Counter(f["status"] for f in result["findings"]) + remaining = sum(bool(f["error"]) for f in result["findings"]) + lines = [ + f"## PR #{number} · AI Review Disposition", + "", + f"Head: `{head}`", + "", + f"Findings: {len(result['findings'])}; unresolved requirements: {remaining}", + "", + "| Accepted | Rejected | Deferred | Invalid | Unaddressed |", + "| --- | --- | --- | --- | --- |", + "| " + " | ".join(str(counts[s]) for s in (*STATUSES, "Unaddressed")) + " |", + "", + ] + lines.extend(f"- {error}" for error in result["errors"]) + blocked = [f for f in result["findings"] if f["error"]] + for finding in blocked[:100]: + lines.append(f"- [{finding['status']}]({finding['url']}): {finding['error']}") + if len(blocked) > 100: + lines.append(f"- {len(blocked) - 100} additional blocked findings") + return "\n".join(lines) + + +def check_pr(api, repository, number, bots, server_url, jira_url): + pr = api.request("GET", f"/repos/{repository}/pulls/{number}") + if pr["state"] != "open": + return True + head = pr["head"]["sha"] + check = api.request( + "POST", + f"/repos/{repository}/check-runs", + {"name": CHECK_NAME, "head_sha": head, "status": "in_progress"}, + ) + permissions = {} + tracking = {} + + def authorized(login, author): + if login == author: + return True + if login not in permissions: + try: + response = api.request( + "GET", f"/repos/{repository}/collaborators/{quote(login, safe='')}/permission" + ) + permissions[login] = response["permission"] in {"admin", "maintain", "write"} + except HTTPError as error: + if error.code != 404: + raise + permissions[login] = False + return permissions[login] + + def tracking_valid(value): + if value not in tracking: + target = tracking_target(value, server_url, jira_url) + valid = False + if target and target[0] == "jira": + valid = True + elif target: + _, owner, name, issue = target + try: + item = api.request("GET", f"/repos/{owner}/{name}/issues/{issue}") + valid = item["state"] == "open" and "pull_request" not in item + except HTTPError as error: + if error.code != 404: + raise + tracking[value] = valid + return tracking[value] + + try: + data = snapshot(api, repository, number) + if data["head"] != head or data["state"] != "open": + raise RuntimeError("PR changed before evaluation; rerun required") + result = evaluate(data, bots, authorized, tracking_valid) + if passed(result): + # A second read catches comments/commits changed during pagination. + if snapshot(api, repository, number) != data: + result["errors"].append( + "PR review data changed during evaluation; rerun required" + ) + ok = passed(result) + report = summary(number, head, result) + except Exception as error: + ok = False + # Avoid printing tokens, response bodies, or attacker-controlled exception text. + report = ( + f"PR #{number}: evaluation failed ({type(error).__name__}); rerun required." + ) + api.request( + "PATCH", + f"/repos/{repository}/check-runs/{check['id']}", + { + "status": "completed", + "conclusion": "success" if ok else "failure", + "output": {"title": "Passed" if ok else "Failed", "summary": report[:60000]}, + }, + ) + # PR comment text is never emitted, including Actions workflow command sequences. + print(report) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: + stream.write(report + "\n\n") + return ok + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY")) + parser.add_argument("--pr-number", type=int, default=0, help="0: all open PRs") + parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) + parser.add_argument("--jira-url", default=os.environ.get("AI_REVIEW_JIRA_URL", "")) + args = parser.parse_args() + bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + if ( + not bots + or any(not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots) + or not args.repository + or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository) + or args.pr_number < 0 + or not token + ): + parser.error( + "Valid repository, nonempty bot logins, PR number >= 0 and token required" + ) + if args.jira_url: + jira = urlparse(args.jira_url) + if jira.scheme != "https" or not jira.netloc or jira.query or jira.fragment: + parser.error("Jira URL must be an HTTPS base URL") + api = GitHub(token, os.environ.get("GITHUB_API_URL", "https://api.github.com")) + numbers = [args.pr_number] if args.pr_number else api.open_prs(args.repository) + success = True + for number in numbers: + # Keep checking other PRs when one has unaddressed findings. + success = ( + check_pr( + api, + args.repository, + number, + bots, + os.environ.get("GITHUB_SERVER_URL", "https://github.com"), + args.jira_url, + ) + and success + ) + return 0 if success else 1 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except Exception as failure: + print(f"Disposition check failed: {type(failure).__name__}", file=sys.stderr) + sys.exit(2) diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py new file mode 100644 index 0000000..0d7ea07 --- /dev/null +++ b/scripts/tests/test_ai_review_disposition.py @@ -0,0 +1,371 @@ +import copy +import unittest +from unittest.mock import patch + +from scripts.check_ai_review_disposition import ( + CHECK_NAME, + GitHub, + check_pr, + evaluate, + parse_disposition, + passed, + snapshot, + summary, + tracking_target, +) + +HEAD = "a" * 40 +FIX = "b" * 40 +BOT = "reviewer[bot]" + + +def comment(body, login="contributor", timestamp="2026-10-09T02:00:00Z"): + return { + "id": "comment-" + login, + "body": body, + "url": "https://github.com/org/repo/pull/128#discussion_r1", + "createdAt": timestamp, + "updatedAt": timestamp, + "author": {"login": login, "__typename": "Bot" if login == BOT else "User"}, + "pullRequestReview": {"state": "COMMENTED"}, + } + + +def fixture(body=None, resolved=True): + comments = [comment("Please fix this", BOT, "2026-10-09T01:00:00Z")] + if body: + comments.append(comment(body)) + return { + "head": HEAD, + "author": "contributor", + "state": "open", + "commits": [FIX, HEAD], + "reviews": [ + { + "id": "review-1", + "body": f"AI-Review-Complete: {HEAD}", + "state": "COMMENTED", + "submittedAt": "2026-10-09T01:30:00Z", + "author": {"login": BOT}, + "commit": {"oid": HEAD}, + } + ], + "threads": [ + { + "id": "thread-1", + "isResolved": resolved, + "isOutdated": False, + "comments": comments, + } + ], + } + + +def result(data, bots=None, authorized=None, tracking_valid=None): + return evaluate( + data, + bots or {BOT}, + authorized or (lambda login, author: login in {author, "maintainer"}), + tracking_valid or (lambda value: value == "https://github.com/org/repo/issues/42"), + ) + + +class PolicyTests(unittest.TestCase): + def test_all_dispositions_pass_with_required_evidence(self): + replies = [ + f"Disposition: Accepted\nReason: Added bounds check\nFix: {FIX}", + "Disposition: Rejected\nReason: This input is already validated upstream", + "Disposition: Invalid\nReason: The reported method does not exist", + ( + "Disposition: Deferred\nReason: Follow-up agreed\n" + "Tracking: https://github.com/org/repo/issues/42" + ), + ] + for body in replies: + with self.subTest(body=body): + self.assertTrue(passed(result(fixture(body)))) + + def test_resolve_alone_does_not_pass(self): + evaluation = result(fixture()) + self.assertFalse(passed(evaluation)) + self.assertEqual(evaluation["findings"][0]["status"], "Unaddressed") + + def test_valid_reply_still_needs_resolve(self): + data = fixture("Disposition: Rejected\nReason: Covered upstream", resolved=False) + self.assertIn("resolve", result(data)["findings"][0]["error"]) + + def test_outdated_findings_still_block(self): + data = fixture() + data["threads"][0]["isOutdated"] = True + self.assertFalse(passed(result(data))) + + def test_accepted_requires_full_sha_still_in_pr(self): + for fix in ("", FIX[:7], "c" * 40, "https://github.com/org/repo/commit/" + FIX): + with self.subTest(fix=fix): + self.assertFalse( + passed(result(fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {fix}"))) + ) + + def test_force_push_removing_fix_invalidates_acceptance(self): + data = fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {FIX}") + data["commits"] = [HEAD] + self.assertFalse(passed(result(data))) + + def test_every_disposition_requires_reason(self): + for status in ("Accepted", "Rejected", "Deferred", "Invalid"): + with self.subTest(status=status): + self.assertFalse(passed(result(fixture(f"Disposition: {status}")))) + + def test_deferred_requires_valid_tracking(self): + for tracking in ("", "ISSUE-42", "https://evil.test/browse/PROJ-42"): + data = fixture("Disposition: Deferred\nReason: Later\n" + f"Tracking: {tracking}") + self.assertFalse(passed(result(data))) + + def test_unauthorized_replies_cannot_dispose(self): + data = fixture("Disposition: Invalid\nReason: False positive") + data["threads"][0]["comments"][-1]["author"]["login"] = "stranger" + self.assertFalse(passed(result(data))) + + def test_bot_cannot_dispose_even_as_pr_author(self): + data = fixture("Disposition: Invalid\nReason: False positive") + data["author"] = "other[bot]" + data["threads"][0]["comments"][-1]["author"] = { + "login": "other[bot]", + "__typename": "Bot", + } + self.assertFalse(passed(result(data))) + + def test_maintainer_can_dispose(self): + data = fixture("Disposition: Rejected\nReason: Covered upstream") + data["threads"][0]["comments"][-1]["author"]["login"] = "maintainer" + self.assertTrue(passed(result(data))) + + def test_latest_explicit_reply_supersedes_old_valid_reply(self): + data = fixture("Disposition: Rejected\nReason: Covered upstream") + data["threads"][0]["comments"].append( + comment("Disposition: Accepted", timestamp="2026-10-09T03:00:00Z") + ) + self.assertFalse(passed(result(data))) + + def test_edit_timestamp_selects_latest_disposition(self): + data = fixture("Disposition: Accepted") + data["threads"][0]["comments"][-1]["updatedAt"] = "2026-10-09T04:00:00Z" + data["threads"][0]["comments"].append( + comment( + "Disposition: Invalid\nReason: False positive", timestamp="2026-10-09T03:00:00Z" + ) + ) + self.assertFalse(passed(result(data))) + + def test_ai_edit_invalidates_older_reply(self): + data = fixture("Disposition: Invalid\nReason: False positive") + data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T03:00:00Z" + self.assertIn("changed", result(data)["findings"][0]["error"]) + + def test_missing_old_dismissed_or_incomplete_review_blocks(self): + for mode in ("missing", "old", "dismissed", "incomplete", "pending"): + with self.subTest(mode=mode): + data = fixture("Disposition: Invalid\nReason: False positive") + if mode == "missing": + data["reviews"] = [] + elif mode == "old": + data["reviews"][0]["commit"]["oid"] = FIX + elif mode == "dismissed": + data["reviews"][0]["state"] = "DISMISSED" + elif mode == "pending": + data["reviews"][0]["state"] = "PENDING" + else: + data["reviews"][0]["body"] = "No problems" + self.assertFalse(passed(result(data))) + + def test_later_unfinished_review_supersedes_completion(self): + data = fixture("Disposition: Invalid\nReason: False positive") + review = copy.deepcopy(data["reviews"][0]) + review.update(id="review-2", body="Working", submittedAt="2026-10-09T03:00:00Z") + data["reviews"].append(review) + self.assertFalse(passed(result(data))) + + def test_zero_findings_pass_only_after_review_completion(self): + data = fixture() + data["threads"] = [] + self.assertTrue(passed(result(data))) + data["reviews"] = [] + self.assertFalse(passed(result(data))) + + def test_every_configured_bot_must_complete_review(self): + data = fixture("Disposition: Invalid\nReason: False positive") + self.assertFalse(passed(result(data, bots={BOT, "another[bot]"}))) + + def test_graphql_bot_login_without_suffix_is_canonicalized(self): + data = fixture("Disposition: Invalid\nReason: False positive") + for author in ( + data["reviews"][0]["author"], + data["threads"][0]["comments"][0]["author"], + ): + author.update(login="reviewer", __typename="Bot") + self.assertTrue(passed(result(data))) + + def test_ordinary_user_cannot_impersonate_bot_login(self): + data = fixture("Disposition: Invalid\nReason: False positive") + data["reviews"][0]["author"] = {"login": "reviewer", "__typename": "User"} + self.assertFalse(passed(result(data))) + + def test_new_finding_after_completion_requires_new_marker(self): + data = fixture("Disposition: Invalid\nReason: False positive") + data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T01:45:00Z" + self.assertFalse(passed(result(data))) + data["reviews"][0]["submittedAt"] = "2026-10-09T01:50:00Z" + self.assertTrue(passed(result(data))) + + def test_human_root_thread_is_not_an_ai_finding(self): + data = fixture() + data["threads"][0]["comments"][0]["author"] = { + "login": "maintainer", + "__typename": "User", + } + self.assertTrue(passed(result(data))) + + def test_pending_review_comments_are_not_published_findings(self): + data = fixture() + data["threads"][0]["comments"][0]["pullRequestReview"]["state"] = "PENDING" + self.assertTrue(passed(result(data))) + + def test_quoted_and_fenced_dispositions_are_not_replies(self): + for text in ( + "> Disposition: Accepted", + "```\nDisposition: Accepted\n```", + "Accepted", + ): + self.assertIsNone(parse_disposition(text)) + + def test_duplicate_and_unknown_fields_are_invalid(self): + for text in ( + "Disposition: Invalid\nReason: First\nReason: Second", + "Disposition: Invalid\nReason: False positive\nStatus: Done", + "Disposition: Whatever\nReason: Test", + ): + self.assertIn("error", parse_disposition(text)) + + def test_summary_separates_status_counts_and_remaining_requirements(self): + data = fixture("Disposition: Accepted\nReason: Fixed", resolved=False) + report = summary(128, HEAD, result(data)) + self.assertIn("unresolved requirements: 1", report) + self.assertIn("| 1 | 0 | 0 | 0 | 0 |", report) + + def test_tracking_urls_are_bound_to_trusted_hosts(self): + self.assertEqual( + tracking_target( + "https://github.com/org/repo/issues/42", "https://github.com", "" + ), + ("github", "org", "repo", "42"), + ) + self.assertIsNotNone( + tracking_target( + "https://jira.test/browse/PROJ-42", "https://github.com", "https://jira.test" + ) + ) + for url in ( + "http://jira.test/browse/PROJ-42", + "https://jira.test.evil/browse/PROJ-42", + "https://github.com/org/repo/pull/42", + "https://github.com/org/repo/issues/42?redirect=1", + "https://user@github.com/org/repo/issues/42", + ): + self.assertIsNone(tracking_target(url, "https://github.com", "https://jira.test")) + + +class ApiTests(unittest.TestCase): + def test_connections_read_more_than_100_nodes(self): + api = GitHub("test-token", "https://api.github.com") + pages = [ + { + "nodes": list(range(100)), + "pageInfo": {"hasNextPage": True, "endCursor": "next"}, + }, + {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}}, + ] + responses = [{"repository": {"pullRequest": {"reviews": p}}} for p in pages] + with patch.object(api, "graphql", side_effect=responses) as graphql: + self.assertEqual(len(api.connection("org/repo", 128, "reviews", "id")), 101) + self.assertEqual(graphql.call_args.args[1]["cursor"], "next") + + def test_long_thread_comments_are_paginated(self): + api = GitHub("test-token", "https://api.github.com") + thread = { + "id": "thread-1", + "comments": { + "nodes": list(range(100)), + "pageInfo": {"hasNextPage": True, "endCursor": "next"}, + }, + } + page = {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}} + with patch.object(api, "graphql", return_value={"node": {"comments": page}}): + self.assertEqual(api.comments(thread)[-1], 100) + + def test_graphql_errors_reject_partial_data(self): + api = GitHub("test-token", "https://api.github.com") + with patch.object(api, "request", return_value={"data": {}, "errors": [{}]}): + with self.assertRaises(RuntimeError): + api.graphql("query", {}) + + def test_snapshot_rejects_head_change_during_read(self): + api = GitHub("test-token", "https://api.github.com") + before = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} + after = {**before, "head": {"sha": FIX}} + with ( + patch.object(api, "request", side_effect=[before, after]), + patch.object(api, "connection", return_value=[]), + self.assertRaises(RuntimeError), + ): + snapshot(api, "org/repo", 128) + + def test_check_is_written_to_pr_head_not_event_sha(self): + data = fixture("Disposition: Invalid\nReason: False positive") + calls, ok = self.run_check([data, copy.deepcopy(data)]) + self.assertTrue(ok) + self.assertEqual(calls[1].args[2]["head_sha"], HEAD) + self.assertEqual(calls[1].args[2]["name"], CHECK_NAME) + self.assertEqual(calls[-1].args[2]["conclusion"], "success") + + def test_new_finding_during_read_prevents_success(self): + data = fixture("Disposition: Invalid\nReason: False positive") + changed = copy.deepcopy(data) + changed["threads"].append(fixture()["threads"][0]) + calls, ok = self.run_check([data, changed]) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def test_api_failure_finishes_check_as_failure(self): + calls, ok = self.run_check(RuntimeError("failed")) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def test_closed_tracking_issue_or_pr_cannot_defer(self): + data = fixture( + "Disposition: Deferred\nReason: Later\nTracking: https://github.com/org/repo/issues/42" + ) + for item in ({"state": "closed"}, {"state": "open", "pull_request": {}}): + with self.subTest(item=item): + calls, ok = self.run_check([data], item) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def run_check(self, snapshots, issue=None): + api = GitHub("test-token", "https://api.github.com") + pr = {"head": {"sha": HEAD}, "state": "open"} + responses = [pr, {"id": 99}] + if issue is not None: + responses.append(issue) + responses.append({}) + with ( + patch.object(api, "request", side_effect=responses) as request, + patch("scripts.check_ai_review_disposition.snapshot", side_effect=snapshots), + patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), + patch("builtins.print"), + ): + ok = check_pr(api, "org/repo", 128, {BOT}, "https://github.com", "") + return request.call_args_list, ok + + +if __name__ == "__main__": + unittest.main() From 4979df468b5b02b98c25a7f1034430db9cb45155 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:41:15 +0800 Subject: [PATCH 02/21] docs[ci]: add unified AI review reply template --- .github/PULL_REQUEST_TEMPLATE/ai-review-reply.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE/ai-review-reply.md diff --git a/.github/PULL_REQUEST_TEMPLATE/ai-review-reply.md b/.github/PULL_REQUEST_TEMPLATE/ai-review-reply.md new file mode 100644 index 0000000..cc9b700 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/ai-review-reply.md @@ -0,0 +1,4 @@ +Disposition: +Reason: <填写处理原因,保持一行> +Fix: N/A +Tracking: N/A From 707fe2f841a41ddd2832326df193ac50e14b99f5 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:29:45 +0800 Subject: [PATCH 03/21] refactor[ci]: evaluate AI review dispositions per PR Problem: - Every event scanned all open PRs and shared a repository-wide queue. Solution: - Require a positive PR number and evaluate only that PR. - Pass review-event PR numbers via collector run names. - Serialize check updates per PR and simplify the GitHub.com client. Test: - Python 3.11: 40 unit tests passed. - 12 workflow routing and concurrency cases passed with @actions/expressions. - Workflow YAML contracts and git diff --check passed. - Live Bot review and target-repository deployment were not run. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 12 +- docs/AI_REVIEW_DISPOSITION.md | 154 +++++++++--------- docs/examples/ai-review-disposition.yml | 12 ++ docs/examples/ai-review-events.yml | 2 + scripts/check_ai_review_disposition.py | 64 +++----- scripts/tests/test_ai_review_disposition.py | 120 +++++++++++++- 6 files changed, 232 insertions(+), 132 deletions(-) diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index ec4a970..2fc1af6 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -8,10 +8,9 @@ on: required: true type: string pr-number: - description: 'PR to check; 0 checks all open PRs in the caller repository' - required: false + description: 'Positive PR number to check in the caller repository' + required: true type: number - default: 0 jira-url: description: 'Optional trusted Jira base URL, e.g. https://example.atlassian.net' required: false @@ -38,10 +37,9 @@ jobs: name: Evaluate AI Review Dispositions runs-on: ubuntu-latest timeout-minutes: 15 - # All scans for a repository must serialize. Pending scans may be coalesced; - # each scan reads live state for every open PR, not an event snapshot. + # Serialize updates for this PR only; every run reads its live API state. concurrency: - group: ai-review-disposition-${{ github.repository }} + group: ai-review-disposition-${{ github.repository }}-${{ inputs.pr-number }} cancel-in-progress: false steps: - name: Checkout trusted shared scripts @@ -59,7 +57,7 @@ jobs: with: python-version: '3.11' - - name: Publish check on each PR head commit + - name: Publish check on the target PR head commit env: GH_TOKEN: ${{ github.token }} AI_REVIEW_BOTS: ${{ inputs.bot-logins }} diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 3dba504..4e70f73 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,114 +1,120 @@ # AI Review / Disposition Check -目标:所有需要响应的 AI inline findings 都有可审计的处理记录,并且对话已 Resolve。检查不要求采纳 AI 建议,也不代替 Human Review。 +Ŀ�꣺������Ҫ��Ӧ�� AI inline findings ���п���ƵĴ�����¼�����ҶԻ��� Resolve����鲻Ҫ����� AI ���飬Ҳ������ Human Review�� -本仓库提供 [Python 检查器](../scripts/check_ai_review_disposition.py)、[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) 和两个项目接入示例。规则单独运行,不并入现有 `CI Result`:代码 CI 与 review 的完成时间不同,回复评论也不应该重新运行测试。 +���ֿ��ṩ [Python �����](../scripts/check_ai_review_disposition.py)��[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) ��������Ŀ����ʾ�������򵥶����У����������� `CI Result`������ CI �� review �����ʱ�䲻ͬ���ظ�����Ҳ��Ӧ���������в��ԡ� -## 合并条件 +ÿ��ֻ�����ȷָ����һ�� PR��ֻ���¸� PR �����ύ�ϵ� Check������ open PR �����뱾���ж���closed/merged PR ֱ����������ǰ API �ͻ��˽�֧�� GitHub.com�� + +## �ϲ����� ```text -每个指定 AI Bot 已完成当前 head SHA 的 review -AND 每个 AI finding 有授权人员的有效 disposition -AND 每个 finding 的 conversation 已 Resolve +ÿ��ָ�� AI Bot ����ɵ�ǰ head SHA �� review +AND ÿ�� AI finding ����Ȩ��Ա����Ч disposition +AND ÿ�� finding �� conversation �� Resolve ``` -检查范围为配置的 Bot 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding;Bot 应把不同问题分成不同 threads。以人类评论开头的 thread 不计入,PR 顶层评论/总结也不计为 finding。尚未提交的 pending review 不计入已发布 findings。 +��鷶ΧΪ���õ� Bot �����������ѷ��� inline review threads��������ʷ�ύ�ϵ� outdated threads ���� Resolve �� threads��ÿ�� thread ��һ�� finding��Bot Ӧ�Ѳ�ͬ����ֳɲ�ͬ threads�����������ۿ�ͷ�� thread �����룬PR ��������/�ܽ�Ҳ����Ϊ finding����δ�ύ�� pending review �������ѷ��� findings�� -Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。`AI_REVIEW_BOTS` 中的每个 Bot 都必须完成 review。空配置是错误,不会当作“无 AI 问题”通过。 +Bot �ɾ�ȷ GitHub login ƥ�䣬���� `reviewer[bot]`����������ʾ�������Ļ�ģ���Ӵ�ʶ��GraphQL �� `Bot` ���������ز�����׺�� login����ת���ɱ�׼ `[bot]` ��ʽ����ͨ `User` ������ת����`AI_REVIEW_BOTS` �е�ÿ�� Bot ��������� review���������Ǵ��󣬲��ᵱ������ AI ���⡱ͨ���� -回复者必须是 PR 作者或当前拥有仓库 `write` / `maintain` / `admin` 权限的人员。其他人员的回复不生效;GitHub Bot 和已配置的 AI 服务账号不能自行 disposition。仅有组织成员身份不足以授权回复。 +�ظ��߱����� PR ���߻�ǰӵ�вֿ� `write` / `maintain` / `admin` Ȩ�޵���Ա��������Ա�Ļظ�����Ч��GitHub Bot �������õ� AI �����˺Ų������� disposition��������֯��Ա���ݲ�������Ȩ�ظ��� -| Disposition | 必须提供的字段 | 检查的证据 | +| Disposition | �����ṩ���ֶ� | ����֤�� | | --- | --- | --- | -| Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,必须仍在当前 PR 的 commits 中 | -| Rejected | `Reason` | 非空拒绝理由 | -| Invalid | `Reason` | 非空误报理由 | -| Deferred | `Reason`、`Tracking` | 存在且开放的 GitHub Issue,或指定 Jira 域名下的 ticket URL | +| Accepted | `Reason`��`Fix` | ������ 40 λ commit SHA���������ڵ�ǰ PR �� commits �� | +| Rejected | `Reason` | �ǿվܾ����� | +| Invalid | `Reason` | �ǿ������� | +| Deferred | `Reason`��`Tracking` | �����ҿ��ŵ� GitHub Issue����ָ�� Jira �����µ� ticket URL | -`Fix` 证明提交引用有效;工具不判断该提交是否真正修复问题。理由的充分性、Jira ticket 的存在与状态,以及 deferral 的业务可接受性由 Human Review 审查。当前版本不支持无 tracking 的口头豁免;若未来接入审批,应验证审批人的身份及审批记录,而不是接受 Contributor 自填 `Approved: yes`。 +`Fix` ֤���ύ������Ч�����߲��жϸ��ύ�Ƿ������޸����⡣���ɵij���ԡ�Jira ticket �Ĵ�����״̬���Լ� deferral ��ҵ��ɽ������� Human Review ��顣��ǰ�汾��֧���� tracking �Ŀ�ͷ���⣻��δ������������Ӧ��֤�����˵����ݼ�������¼�������ǽ��� Contributor ���� `Approved: yes`�� -## Contributor 回复格式 +## Contributor �ظ���ʽ -直接在对应 inline thread 中回复。第一行必须是 `Disposition: ...`,每个字段单独一行;允许空行和字段名/状态大小写变化。不要加引号、Markdown 引用、代码块或额外字段。`Reason` 保持一行,可以用中文。 +ֱ���ڶ�Ӧ inline thread �лظ�����һ�б����� `Disposition: ...`��ÿ���ֶε���һ�У��������к��ֶ���/״̬��Сд�仯����Ҫ�����š�Markdown ���á�����������ֶΡ�`Reason` ����һ�У����������ġ� -Accepted: +Accepted�� ```text Disposition: Accepted -Reason: 已补充空数组边界判断,并增加回归测试。 +Reason: �Ѳ��������߽��жϣ������ӻع���ԡ� Fix: 0123456789abcdef0123456789abcdef01234567 ``` -Rejected: +Rejected�� ```text Disposition: Rejected -Reason: 调用入口已验证该条件,此处不会收到负数输入。 +Reason: �����������֤���������˴������յ��������롣 ``` -Invalid: +Invalid�� ```text Disposition: Invalid -Reason: 此实现使用异步执行,评论所述的同步调用路径不存在。 +Reason: ��ʵ��ʹ���첽ִ�У�����������ͬ������·�������ڡ� ``` -Deferred: +Deferred�� ```text Disposition: Deferred -Reason: 本次先完成兼容修复,性能优化在后续版本处理。 +Reason: ��������ɼ����޸��������Ż��ں����汾������ Tracking: https://github.com/IS-Model-Framework/example/issues/42 ``` -配置 `AI_REVIEW_JIRA_URL=https://example.atlassian.net` 后,也接受 `Tracking: https://example.atlassian.net/browse/PROJ-123`。不接受任意 HTTPS 链接、裸 ticket 编号或 PR 链接。GitHub Issue 需要当前 token 可读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 +���� `AI_REVIEW_JIRA_URL=https://example.atlassian.net` ��Ҳ���� `Tracking: https://example.atlassian.net/browse/PROJ-123`������������ HTTPS ���ӡ��� ticket ��Ż� PR ���ӡ�GitHub Issue ��Ҫ��ǰ token �ɶ�ȡ�������ֿ��˽�� Issue ������Ҫ GitHub App installation token�� -采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。AI 编辑 finding 或追加 inline 回复后,需要重新确认 disposition,并重新提交完成 review 的标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 +�������±༭ʱ�����ȷ disposition �ظ���ͬһʱ��ȡ thread �и���Ļظ����µIJ����� disposition ������ɵ���Ч�ظ����������ù��ھ�������ͨ�����ظ�������� disposition��AI �༭ finding ��׷�� inline �ظ�����Ҫ����ȷ�� disposition���������ύ��� review �ı�ǡ��޸��ύ�� force-push �Ƴ� PR ��Accepted ʧЧ�� -有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 +��Ч�ظ�֮���� Contributor / Maintainer Resolve Conversation�����߲����Զ� Resolve��ֻ Resolve��ֻд ��done / ���޸������� PR �ܽ���ͳһ�ش𣬶�����ͨ���� -## AI Bot 完成协议 +## AI Bot ���Э�� -Bot 的 review 流程必须遵守: +Bot �� review ���̱������أ� -1. 对固定的 PR head SHA 生成 findings,用 inline threads 发布。 -2. 全部 findings 发布完毕后,提交一个非 pending 的 review,其正文包含独立一行: +1. �Թ̶��� PR head SHA ���� findings���� inline threads ������ +2. ȫ�� findings ������Ϻ��ύһ���� pending �� review�������İ�������һ�У� ```text - AI-Review-Complete: <当前 PR 的完整 head SHA> + AI-Review-Complete: <��ǰ PR ������ head SHA> ``` -3. review 本身的 `commit.oid` 也必须等于该 SHA。没有 findings 时仍需要这个 review;这样“零问题”和“尚未开始 review”不会混淆。 -4. 当前 head 改变后,重新 review 并提交新完成标记。后续提交的新 review 未含标记、review 被 dismissed,或者 Bot 在完成标记之后继续增加/编辑 finding,均阻断通过。 +3. review ������ `commit.oid` Ҳ������ڸ� SHA��û�� findings ʱ����Ҫ��� review�������������⡱�͡���δ��ʼ review����������� +4. ��ǰ head �ı������ review ���ύ����ɱ�ǡ������ύ���� review δ����ǡ�review �� dismissed������ Bot ����ɱ��֮���������/�༭ finding�������ͨ���� -这是本工具的集成协议,不是 GitHub 自带的字段。现有 Bot 若不能提供该标记,需要修改其发布流程;不能仅凭 “没有 unresolved threads” 推断 review 已完成。不要在 findings 尚未全部发布时写入完成标记。 +���DZ����ߵļ���Э�飬���� GitHub �Դ����ֶΡ����� Bot �������ṩ�ñ�ǣ���Ҫ�޸��䷢�����̣����ܽ�ƾ ��û�� unresolved threads�� �ƶ� review ����ɡ���Ҫ�� findings ��δȫ������ʱд����ɱ�ǡ� -## Actions 接入 +## Actions ���� -`.github` 仓库的 workflow 不会自动在所有组织项目执行。每个目标项目需要 caller workflow,并由组织 ruleset 覆盖目标仓库。 +`.github` �ֿ�� workflow �����Զ���������֯��Ŀִ�С�ÿ��Ŀ����Ŀ��Ҫ caller workflow��������֯ ruleset ����Ŀ��ֿ⡣ -1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 与 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 复制到目标项目 `.github/workflows/`,合入默认分支。 -2. 在组织/仓库 Variables 设置 `AI_REVIEW_BOTS` 为准确的 login 列表,逗号分隔。需要 Jira 时设置 `AI_REVIEW_JIRA_URL`。示例中的 Bot 名称不是实际默认配置。 -3. 生产环境将 caller 的 `uses: ...@main` 与 `shared-ref: main` 同时固定到本仓库同一个已审核 commit SHA。共享脚本从可信 CI 仓库加载,完全不 checkout PR 代码。 -4. 为 `GITHUB_TOKEN` 提供 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。如果组织 CI 仓库是 private,还需要开启 reusable workflow 的组织访问,并通过可选 secret `shared-read-token` 提供 CI 仓库的只读 checkout token;caller 的 `GITHUB_TOKEN` 不会自动获得其他 private 仓库的读取权限。 -5. 完成一次运行后,将 **`AI Review / Disposition Check`** 加入 ruleset 的 Required Status Checks,检查来源选择 GitHub Actions。保持现有 Human Review / approval 规则。 +1. �� [ai-review-events.yml](examples/ai-review-events.yml) �� [ai-review-disposition.yml](examples/ai-review-disposition.yml) ���׸��Ƶ�Ŀ����Ŀ `.github/workflows/`������Ĭ�Ϸ�֧��collector �� `run-name` ���뱣��Ϊ PR ��ţ������� `workflow_run` ��λĿ�ꣻ��Ҫ�ij� PR ���⡣Ǩ���ڼ�� collector ����ʷ���в������¸�ʽ����ͨ���ֶ�ָ�� PR ���顣 +2. ����֯/�ֿ� Variables ���� `AI_REVIEW_BOTS` Ϊ׼ȷ�� login �б������ŷָ�����Ҫ Jira ʱ���� `AI_REVIEW_JIRA_URL`��ʾ���е� Bot ���Ʋ���ʵ��Ĭ�����á� +3. ���������� caller �� `uses: ...@main` �� `shared-ref: main` ͬʱ�̶������ֿ�ͬһ������� commit SHA�������ű��ӿ��� CI �ֿ���أ���ȫ�� checkout PR ���롣 +4. Ϊ `GITHUB_TOKEN` �ṩ `contents: read`��`pull-requests: read`��`issues: read`��`checks: write`�������֯ CI �ֿ��� private������Ҫ���� reusable workflow ����֯���ʣ���ͨ����ѡ secret `shared-read-token` �ṩ CI �ֿ��ֻ�� checkout token��caller �� `GITHUB_TOKEN` �����Զ�������� private �ֿ�Ķ�ȡȨ�ޡ� +5. ���һ�����к󣬽� **`AI Review / Disposition Check`** ���� ruleset �� Required Status Checks�������Դѡ�� GitHub Actions���������� Human Review / approval ���� -选择的是脚本通过 Checks API 发布到 PR **head commit** 上的 Check,不是 `Evaluate AI Review Dispositions` 这个 Actions job。`pull_request_target`、`issue_comment`、`workflow_run` 的 `GITHUB_SHA` 不一定是 PR head;直接使用 job success 作合并门禁会关联到错误提交。 +ѡ����ǽű�ͨ�� Checks API ������ PR **head commit** �ϵ� Check������ `Evaluate AI Review Dispositions` ��� Actions job��`pull_request_target`��`issue_comment`��`workflow_run` �� `GITHUB_SHA` ��һ���� PR head��ֱ��ʹ�� job success ���ϲ��Ž�������������ύ�� -| 事件 | 示例中的路径 | +| �¼� | ʾ���е�·�� | | --- | --- | -| PR opened / reopened / synchronize / ready_for_review | `pull_request_target` 调用可信检查器 | -| Review submitted / edited / dismissed | 无权限的 event collector → 默认分支 `workflow_run` → 检查器 | -| Inline comment created / edited / deleted | 同上 | -| PR 顶层评论 created / edited / deleted | `issue_comment` 触发复查,可用一条 “AI review recheck” 评论重新计算 | -| Resolve / Unresolve | Actions 不直接支持此事件;手动复查、顶层评论,或 App webhook → `repository_dispatch` | -| Bot 用 `GITHUB_TOKEN` 发布 review/comments | 通常不会触发后续 Actions;review workflow 结束后显式复查,或改用 App token 发布 | +| PR opened / reopened / synchronize / ready_for_review | �� `pull_request.number` ȡ�ñ�ţ�ֻ���� PR | +| Review submitted / edited / dismissed | ��Ȩ�޵� collector �� PR ���д�� `run-name` �� Ĭ�Ϸ�֧ `workflow_run.display_title` �� ���� PR | +| Inline comment created / edited / deleted | ͬ�� | +| PR �������� created / edited / deleted | `issue_comment` �������飬����һ�� ��AI review recheck�� �������¼��� | +| Resolve / Unresolve | Actions ��ֱ��֧�ִ��¼����ֶ����顢�������ۣ��� App webhook �� `repository_dispatch` | +| Bot �� `GITHUB_TOKEN` ���� review/comments | ͨ�����ᴥ������ Actions��review workflow ��������ʽ���飬����� App token ���� | +| Actions �ֶ����� | ���� `pr-number`��ֻ���ָ�� PR | +| `repository_dispatch: ai-review-state-changed` | �� `client_payload.pr_number` �д���Ŀ�� PR ����������� | + +collector �������ִ�� PR ���ݡ����ϴ� artifact��caller �� `workflow_run.display_title` ʹ�� `fromJSON` ȡ�����ֱ�ţ���� fork �� `workflow_run.pull_requests` Ϊ��Ҳ�ܶ�λ��������ֻ����·����ʾ�������� collector �ṩ�������ۻ�ű�����дȨ�޵ļ����ʼ�մӿ��Ź����ֿ���أ����¶�ȡĿ��ֿ��и� PR ��ʵʱ API ���ݡ� -collector 不运行 PR 内容、不上传 artifact。后续有写权限的 `workflow_run` 不信任 collector 输出,而是读取 GitHub API 的实时状态,支持 fork PR 的评论事件。每次默认检查所有 open PR,绕开 fork 的 `workflow_run.pull_requests` 可能为空,以及同一 PR 密集事件被 concurrency 合并的问题。 +���÷��� CLI ��Ҫ����ʽ���������� PR ��ţ�ȱʧ��0��������Ƿ�ֵ�����������˵�ȫ�ֿ�ɨ�衣Ȩ�޼���� disposition ���򱣳ֲ��䡣 -所有扫描使用仓库级 concurrency,`cancel-in-progress: false`。发布 Check 后发生 API 错误会标记 failure;超时/取消可能留下 in-progress Check,仍然阻止合并。通过之前再完整读取一次 review 数据,发现提交或评论变化就失败。扫描规模大时应改用 App,按 PR 串行处理。 +����������ֿ����� PR ��ţ�`cancel-in-progress: false`��ͬһ PR �ļ�鴮�����У���ִ���¼���ʹ���������¼��滻��Ҳ�����¶�ȡͬһ PR ��ʵʱ״̬����ͬ PR �����ö��С�ͨ��֮ǰ��������ȡһ�� review ���ݣ������ύ�����۱仯��ʧ�ܡ��������ڵ� API ����᳢��д failure������/���� Check ������ʧ�ܡ���ʱ��ȡ���������� in-progress Check����Ȼ��ֹ�ϲ��� -手动复查可在 Actions 页面运行 `AI Review Disposition`。单独调试某个 PR: +�ֶ�������� Actions ҳ������ `AI Review Disposition` ����д `pr-number`��CLI ʾ���� ```bash GH_TOKEN="" python scripts/check_ai_review_disposition.py \ @@ -117,40 +123,40 @@ GH_TOKEN="" python scripts/check_ai_review_disposition.py \ --bots 'reviewer[bot]' ``` -这条命令会通过 Checks API 写入 PR Check,不是 dry-run。Token 通过环境变量提供;不应提交到仓库。未指定 PR(`--pr-number 0`)时检查全部 open PR。退出码:0 全部通过,1 存在未处理项,2 参数/API 等执行错误。 +���������ͨ�� Checks API д��ָ�� PR �� Check������ dry-run��Token ͨ�����������ṩ����Ӧ�ύ���ֿ⡣`--pr-number` �����ұ������ 0���˳��룺0 Ŀ�� PR ͨ�����ѹرն�������1 Ŀ�� PR ��ͨ���������������в���� API ���󣩣�2 ���������δ�����ִ�д��� -## 严格组织门禁:GitHub App +## �ϸ���֯�Ž���GitHub App -Actions 方案适合初期接入,但不保证评论变化后瞬间撤销 success:事件排队、运行延迟、Resolve/Unresolve 缺少原生 trigger,都会留下状态更新窗口。需要严格覆盖 thread 状态变化时,建议组织安装专用 GitHub App,用同一个检查器作为执行核心: +Actions �����ʺϳ��ڽ��룬������֤���۱仯��˲�䳷�� success���¼��Ŷӡ������ӳ١�Resolve/Unresolve ȱ��ԭ�� trigger����������״̬���´��ڡ���Ҫ�ϸ񸲸� thread ״̬�仯ʱ��������֯��װר�� GitHub App����ͬһ���������Ϊִ�к��ģ� ```mermaid flowchart LR - A[PR / Review / Comment / Thread webhook] --> B[验证签名并按 PR 串行排队] - B --> C[将当前 head 的固定 Check 标记 in_progress] - C --> D[分页读取实时 reviews / threads / comments / commits] - D --> E{完成协议 + disposition + resolved} - E -->|满足| F[success] - E -->|未满足或 API 失败| G[failure] - F --> H[Human Review 与 Required Approval] + A[PR / Review / Comment / Thread webhook] --> B[��֤ǩ������ PR �����Ŷ�] + B --> C[����ǰ head �Ĺ̶� Check ��� in_progress] + C --> D[��ҳ��ȡʵʱ reviews / threads / comments / commits] + D --> E{���Э�� + disposition + resolved} + E -->|����| F[success] + E -->|δ����� API ʧ��| G[failure] + F --> H[Human Review �� Required Approval] ``` -App 应订阅 `pull_request`、`pull_request_review`、`pull_request_review_comment`、`pull_request_review_thread` 的相关 actions,并支持 Check rerequest;用 webhook signature 与 delivery ID 校验/去重,每个 PR 串行更新同一个 head 的 Check,变化时立即撤销旧 success。重试失败保持阻断,并以定期 reconciliation 恢复漏发/丢失事件。 +App Ӧ���� `pull_request`��`pull_request_review`��`pull_request_review_comment`��`pull_request_review_thread` ����� actions����֧�� Check rerequest���� webhook signature �� delivery ID У��/ȥ�أ�ÿ�� PR ���и���ͬһ�� head �� Check���仯ʱ���������� success������ʧ�ܱ�����ϣ����Զ��� reconciliation �ָ�©��/��ʧ�¼��� -权限为 Pull requests read、Contents read、Issues read、Checks write;安装 token 只覆盖获授权仓库。若调用跨仓库 Issue,需要相应仓库访问权限。当前提交未包含 App 的 webhook 服务、部署或持久化账本。 +Ȩ��Ϊ Pull requests read��Contents read��Issues read��Checks write����װ token ֻ���ǻ���Ȩ�ֿ⡣�����ÿ�ֿ� Issue����Ҫ��Ӧ�ֿ����Ȩ�ޡ���ǰ�ύδ���� App �� webhook ���񡢲����־û��˱��� -GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和“执行 merge”做成一个原子事务。高要求场景还应启用分支保护的 conversation resolution,并通过受控 merge 入口在合并前再次核验。AI findings 被删除后,实时 API 不再保留它们;若要求删除也必须留痕,App 需要持久化 finding ID 与 disposition 历史。此版本不会把 API 数据当作不可删改的审计账本。 +GitHub �� Status Check �����첽״̬���޷��ѡ����������ۡ��͡�ִ�� merge������һ��ԭ�����񡣸�Ҫ�󳡾���Ӧ���÷�֧������ conversation resolution����ͨ���ܿ� merge ����ںϲ�ǰ�ٴκ��顣AI findings ��ɾ����ʵʱ API ���ٱ������ǣ���Ҫ��ɾ��Ҳ�������ۣ�App ��Ҫ�־û� finding ID �� disposition ��ʷ���˰汾����� API ���ݵ�������ɾ�ĵ�����˱��� -该 Check 以 PR head 为对象;当前不支持 merge queue 生成的合成 SHA。使用 merge queue 的项目需要另外设计 `merge_group` 的成员 PR 核验,不能直接沿用此 caller 作为队列 required check。 +�� Check �� PR head Ϊ���󣻵�ǰ��֧�� merge queue ���ɵĺϳ� SHA��ʹ�� merge queue ����Ŀ��Ҫ������� `merge_group` �ij�Ա PR ���飬����ֱ�����ô� caller ��Ϊ���� required check�� -## 验证与参考 +## ��֤��ο� ```bash python -m unittest discover -s scripts/tests -v ``` -测试覆盖处理状态、回复权限、完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot Review → 回复 → Resolve → 复查 → Required Check 试运行。 +���Ը��Ǵ���״̬���ظ�Ȩ�ޡ����Э�顢outdated/resolved threads��force-push����ҳ��API �������ȡ�ڼ����� findings���Լ��� PR CLI���ܾ�ȱʧ/�Ƿ���š�closed PR ������ HTTP JSON ��д��API ͨ�� mock ��֤��������Ŀ��ֿ���һ����ʵ�� Bot Review �� �ظ� �� Resolve �� ���� �� Required Check �����С� -- [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) -- [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) -- [Checks API:发布并更新 Check Runs](https://docs.github.com/en/rest/checks/runs) -- [Reusable workflows 的组织接入与权限](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) +- [GitHub Actions �¼��� fork / workflow_run ��Ϊ](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) +- [Webhook �¼���pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) +- [Checks API������������ Check Runs](https://docs.github.com/en/rest/checks/runs) +- [Reusable workflows ����֯������Ȩ��](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index 3cb4732..747014a 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -13,6 +13,11 @@ on: repository_dispatch: types: [ai-review-state-changed] workflow_dispatch: + inputs: + pr-number: + description: 'Positive PR number to recheck' + required: true + type: number permissions: contents: read @@ -25,6 +30,13 @@ jobs: if: ${{ github.event_name != 'issue_comment' || github.event.issue.pull_request }} uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main with: + # Collector run-name is the PR number, even when workflow_run.pull_requests is empty. + pr-number: >- + ${{ github.event.pull_request.number + || github.event.issue.number + || inputs.pr-number + || github.event.client_payload.pr_number + || fromJSON(github.event.workflow_run.display_title || '0') }} # Set this repository/organization variable to exact bot logins. bot-logins: ${{ vars.AI_REVIEW_BOTS }} jira-url: ${{ vars.AI_REVIEW_JIRA_URL }} diff --git a/docs/examples/ai-review-events.yml b/docs/examples/ai-review-events.yml index f97de8b..373361d 100644 --- a/docs/examples/ai-review-events.yml +++ b/docs/examples/ai-review-events.yml @@ -1,6 +1,8 @@ # Copy to each project's .github/workflows/ai-review-events.yml. # This unprivileged collector never checks out or executes PR code. name: AI Review Events +# Pass the PR number through workflow_run.display_title; do not use the PR title. +run-name: ${{ github.event.pull_request.number }} on: pull_request_review: diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index a4b7cea..4388837 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Check AI review completion and explicit dispositions without running PR code.""" +"""Check one PR's AI review completion and dispositions without running PR code.""" import argparse import json @@ -30,20 +30,17 @@ def actor_login(author): class GitHub: - def __init__(self, token, api_url): + def __init__(self, token): self.token = token - self.api_url = api_url.rstrip("/") - self.graphql_url = ( - "https://api.github.com/graphql" - if self.api_url == "https://api.github.com" - else self.api_url.removesuffix("/v3") + "/graphql" - ) def request(self, method, path, body=None): - url = self.graphql_url if path == "graphql" else self.api_url + path + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + request = Request( - url, - data=json.dumps(body).encode() if body is not None else None, + "https://api.github.com" + path, + data=data, method=method, headers={ "Authorization": f"Bearer {self.token}", @@ -55,7 +52,7 @@ def request(self, method, path, body=None): return json.load(response) def graphql(self, query, variables): - result = self.request("POST", "graphql", {"query": query, "variables": variables}) + result = self.request("POST", "/graphql", {"query": query, "variables": variables}) if result.get("errors"): raise RuntimeError("GitHub GraphQL returned errors; refusing partial data") return result["data"] @@ -86,7 +83,7 @@ def connection(self, repository, number, field, selection): cursor = page["pageInfo"]["endCursor"] def comments(self, thread): - page = thread.pop("comments") + page = thread["comments"] comments = list(page["nodes"]) while page["pageInfo"]["hasNextPage"]: query = f""" @@ -105,17 +102,6 @@ def comments(self, thread): comments.extend(page["nodes"]) return comments - def open_prs(self, repository): - page = 1 - while True: - pulls = self.request( - "GET", f"/repos/{repository}/pulls?state=open&per_page=100&page={page}" - ) - yield from (pr["number"] for pr in pulls) - if len(pulls) < 100: - return - page += 1 - def snapshot(api, repository, number): pr = api.request("GET", f"/repos/{repository}/pulls/{number}") @@ -290,7 +276,7 @@ def summary(number, head, result): counts = Counter(f["status"] for f in result["findings"]) remaining = sum(bool(f["error"]) for f in result["findings"]) lines = [ - f"## PR #{number} · AI Review Disposition", + f"## PR #{number} �� AI Review Disposition", "", f"Head: `{head}`", "", @@ -394,7 +380,7 @@ def tracking_valid(value): def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY")) - parser.add_argument("--pr-number", type=int, default=0, help="0: all open PRs") + parser.add_argument("--pr-number", type=int, required=True, help="PR to check") parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) parser.add_argument("--jira-url", default=os.environ.get("AI_REVIEW_JIRA_URL", "")) args = parser.parse_args() @@ -405,33 +391,21 @@ def main(): or any(not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots) or not args.repository or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository) - or args.pr_number < 0 + or args.pr_number <= 0 or not token ): parser.error( - "Valid repository, nonempty bot logins, PR number >= 0 and token required" + "Valid repository, nonempty bot logins, PR number > 0 and token required" ) if args.jira_url: jira = urlparse(args.jira_url) if jira.scheme != "https" or not jira.netloc or jira.query or jira.fragment: parser.error("Jira URL must be an HTTPS base URL") - api = GitHub(token, os.environ.get("GITHUB_API_URL", "https://api.github.com")) - numbers = [args.pr_number] if args.pr_number else api.open_prs(args.repository) - success = True - for number in numbers: - # Keep checking other PRs when one has unaddressed findings. - success = ( - check_pr( - api, - args.repository, - number, - bots, - os.environ.get("GITHUB_SERVER_URL", "https://github.com"), - args.jira_url, - ) - and success - ) - return 0 if success else 1 + api = GitHub(token) + ok = check_pr( + api, args.repository, args.pr_number, bots, "https://github.com", args.jira_url + ) + return 0 if ok else 1 if __name__ == "__main__": diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 0d7ea07..2d16d8e 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -1,4 +1,7 @@ import copy +import io +import json +import sys import unittest from unittest.mock import patch @@ -7,6 +10,7 @@ GitHub, check_pr, evaluate, + main, parse_disposition, passed, snapshot, @@ -275,8 +279,62 @@ def test_tracking_urls_are_bound_to_trusted_hosts(self): class ApiTests(unittest.TestCase): + def test_http_client_reads_and_writes_github_json(self): + api = GitHub("test-token") + calls = [] + responses = [ + {"number": 313}, + {"data": {"viewer": {"login": "reviewer"}}}, + {"id": 99}, + {"conclusion": "success"}, + ] + + def respond(request, timeout): + self.assertEqual(timeout, 30) + calls.append(request) + return io.BytesIO(json.dumps(responses[len(calls) - 1]).encode()) + + with patch("scripts.check_ai_review_disposition.urlopen", side_effect=respond): + self.assertEqual( + api.request("GET", "/repos/org/repo/pulls/313"), {"number": 313} + ) + self.assertEqual( + api.graphql("query { viewer { login } }", {}), + {"viewer": {"login": "reviewer"}}, + ) + self.assertEqual( + api.request("POST", "/repos/org/repo/check-runs", {"head_sha": HEAD}), + {"id": 99}, + ) + self.assertEqual( + api.request( + "PATCH", "/repos/org/repo/check-runs/99", {"output": {"summary": "���ͨ��"}} + ), + {"conclusion": "success"}, + ) + self.assertEqual([r.get_method() for r in calls], ["GET", "POST", "POST", "PATCH"]) + self.assertEqual( + [r.full_url for r in calls], + [ + "https://api.github.com/repos/org/repo/pulls/313", + "https://api.github.com/graphql", + "https://api.github.com/repos/org/repo/check-runs", + "https://api.github.com/repos/org/repo/check-runs/99", + ], + ) + self.assertIsNone(calls[0].data) + self.assertEqual( + json.loads(calls[1].data), + {"query": "query { viewer { login } }", "variables": {}}, + ) + self.assertEqual(json.loads(calls[2].data), {"head_sha": HEAD}) + self.assertEqual(json.loads(calls[3].data)["output"]["summary"], "���ͨ��") + self.assertTrue( + all(r.get_header("Authorization") == "Bearer test-token" for r in calls) + ) + def test_connections_read_more_than_100_nodes(self): - api = GitHub("test-token", "https://api.github.com") + api = GitHub("test-token") pages = [ { "nodes": list(range(100)), @@ -290,7 +348,7 @@ def test_connections_read_more_than_100_nodes(self): self.assertEqual(graphql.call_args.args[1]["cursor"], "next") def test_long_thread_comments_are_paginated(self): - api = GitHub("test-token", "https://api.github.com") + api = GitHub("test-token") thread = { "id": "thread-1", "comments": { @@ -300,16 +358,19 @@ def test_long_thread_comments_are_paginated(self): } page = {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}} with patch.object(api, "graphql", return_value={"node": {"comments": page}}): - self.assertEqual(api.comments(thread)[-1], 100) + comments = api.comments(thread) + self.assertEqual(len(comments), 101) + self.assertEqual(comments[-1], 100) + self.assertEqual(len(thread["comments"]["nodes"]), 100) def test_graphql_errors_reject_partial_data(self): - api = GitHub("test-token", "https://api.github.com") + api = GitHub("test-token") with patch.object(api, "request", return_value={"data": {}, "errors": [{}]}): with self.assertRaises(RuntimeError): api.graphql("query", {}) def test_snapshot_rejects_head_change_during_read(self): - api = GitHub("test-token", "https://api.github.com") + api = GitHub("test-token") before = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} after = {**before, "head": {"sha": FIX}} with ( @@ -351,7 +412,7 @@ def test_closed_tracking_issue_or_pr_cannot_defer(self): self.assertEqual(calls[-1].args[2]["conclusion"], "failure") def run_check(self, snapshots, issue=None): - api = GitHub("test-token", "https://api.github.com") + api = GitHub("test-token") pr = {"head": {"sha": HEAD}, "state": "open"} responses = [pr, {"id": 99}] if issue is not None: @@ -367,5 +428,52 @@ def run_check(self, snapshots, issue=None): return request.call_args_list, ok +class MainTests(unittest.TestCase): + def run_main(self, *arguments, passed=True): + with ( + patch.dict("os.environ", {"GH_TOKEN": "test-token"}, clear=True), + patch.object( + sys, "argv", ["checker", "--repository", "org/repo", "--bots", BOT, *arguments] + ), + patch("scripts.check_ai_review_disposition.GitHub") as client, + patch("scripts.check_ai_review_disposition.check_pr", return_value=passed) as check, + patch("sys.stderr", new_callable=io.StringIO), + ): + return main(), client, check + + def test_checks_only_the_requested_pr(self): + code, client, check = self.run_main("--pr-number", "313") + self.assertEqual(code, 0) + client.assert_called_once_with("test-token") + check.assert_called_once_with( + client.return_value, "org/repo", 313, {BOT}, "https://github.com", "" + ) + client.return_value.open_prs.assert_not_called() + + def test_target_pr_failure_sets_exit_code(self): + code, _, check = self.run_main("--pr-number", "313", passed=False) + self.assertEqual(code, 1) + self.assertEqual(check.call_count, 1) + + def test_missing_or_invalid_pr_never_defaults_to_a_repository_scan(self): + for arguments in ( + (), + ("--pr-number", "0"), + ("--pr-number", "-1"), + ("--pr-number", "1.5"), + ): + with self.subTest(arguments=arguments), self.assertRaises(SystemExit) as error: + self.run_main(*arguments) + self.assertEqual(error.exception.code, 2) + + def test_closed_pr_does_not_create_a_check(self): + api = GitHub("test-token") + with patch.object(api, "request", return_value={"state": "closed"}) as request: + self.assertTrue( + check_pr(api, "org/repo", 313, {BOT}, "https://github.com", "") + ) + request.assert_called_once_with("GET", "/repos/org/repo/pulls/313") + + if __name__ == "__main__": unittest.main() From a2d2c4ef7604fed66dc9f19dbf9b5b84ef98c9b8 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:32:44 +0800 Subject: [PATCH 04/21] fix[ci]: preserve UTF-8 text in single-PR checker Restore documentation, summary punctuation, and Unicode test fixtures to the exact UTF-8 contents validated locally. Test: - Python 3.11: 40 unit tests passed on these exact contents. - 12 workflow expression cases passed. JIRA: PDIST-770 --- docs/AI_REVIEW_DISPOSITION.md | 156 ++++++++++---------- scripts/check_ai_review_disposition.py | 2 +- scripts/tests/test_ai_review_disposition.py | 4 +- 3 files changed, 81 insertions(+), 81 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 4e70f73..67bbc6b 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,120 +1,120 @@ # AI Review / Disposition Check -Ŀ�꣺������Ҫ��Ӧ�� AI inline findings ���п���ƵĴ�����¼�����ҶԻ��� Resolve����鲻Ҫ����� AI ���飬Ҳ������ Human Review�� +目标:所有需要响应的 AI inline findings 都有可审计的处理记录,并且对话已 Resolve。检查不要求采纳 AI 建议,也不代替 Human Review。 -���ֿ��ṩ [Python �����](../scripts/check_ai_review_disposition.py)��[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) ��������Ŀ����ʾ�������򵥶����У����������� `CI Result`������ CI �� review �����ʱ�䲻ͬ���ظ�����Ҳ��Ӧ���������в��ԡ� +本仓库提供 [Python 检查器](../scripts/check_ai_review_disposition.py)、[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) 和两个项目接入示例。规则单独运行,不并入现有 `CI Result`:代码 CI 与 review 的完成时间不同,回复评论也不应该重新运行测试。 -ÿ��ֻ�����ȷָ����һ�� PR��ֻ���¸� PR �����ύ�ϵ� Check������ open PR �����뱾���ж���closed/merged PR ֱ����������ǰ API �ͻ��˽�֧�� GitHub.com�� +每次只检查明确指定的一个 PR,只更新该 PR 最新提交上的 Check。其他 open PR 不参与本次判定;closed/merged PR 直接跳过。当前 API 客户端仅支持 GitHub.com。 -## �ϲ����� +## 合并条件 ```text -ÿ��ָ�� AI Bot ����ɵ�ǰ head SHA �� review -AND ÿ�� AI finding ����Ȩ��Ա����Ч disposition -AND ÿ�� finding �� conversation �� Resolve +每个指定 AI Bot 已完成当前 head SHA 的 review +AND 每个 AI finding 有授权人员的有效 disposition +AND 每个 finding 的 conversation 已 Resolve ``` -��鷶ΧΪ���õ� Bot �����������ѷ��� inline review threads��������ʷ�ύ�ϵ� outdated threads ���� Resolve �� threads��ÿ�� thread ��һ�� finding��Bot Ӧ�Ѳ�ͬ����ֳɲ�ͬ threads�����������ۿ�ͷ�� thread �����룬PR ��������/�ܽ�Ҳ����Ϊ finding����δ�ύ�� pending review �������ѷ��� findings�� +检查范围为配置的 Bot 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding;Bot 应把不同问题分成不同 threads。以人类评论开头的 thread 不计入,PR 顶层评论/总结也不计为 finding。尚未提交的 pending review 不计入已发布 findings。 -Bot �ɾ�ȷ GitHub login ƥ�䣬���� `reviewer[bot]`����������ʾ�������Ļ�ģ���Ӵ�ʶ��GraphQL �� `Bot` ���������ز�����׺�� login����ת���ɱ�׼ `[bot]` ��ʽ����ͨ `User` ������ת����`AI_REVIEW_BOTS` �е�ÿ�� Bot ��������� review���������Ǵ��󣬲��ᵱ������ AI ���⡱ͨ���� +Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。`AI_REVIEW_BOTS` 中的每个 Bot 都必须完成 review。空配置是错误,不会当作“无 AI 问题”通过。 -�ظ��߱����� PR ���߻�ǰӵ�вֿ� `write` / `maintain` / `admin` Ȩ�޵���Ա��������Ա�Ļظ�����Ч��GitHub Bot �������õ� AI �����˺Ų������� disposition��������֯��Ա���ݲ�������Ȩ�ظ��� +回复者必须是 PR 作者或当前拥有仓库 `write` / `maintain` / `admin` 权限的人员。其他人员的回复不生效;GitHub Bot 和已配置的 AI 服务账号不能自行 disposition。仅有组织成员身份不足以授权回复。 -| Disposition | �����ṩ���ֶ� | ����֤�� | +| Disposition | 必须提供的字段 | 检查的证据 | | --- | --- | --- | -| Accepted | `Reason`��`Fix` | ������ 40 λ commit SHA���������ڵ�ǰ PR �� commits �� | -| Rejected | `Reason` | �ǿվܾ����� | -| Invalid | `Reason` | �ǿ������� | -| Deferred | `Reason`��`Tracking` | �����ҿ��ŵ� GitHub Issue����ָ�� Jira �����µ� ticket URL | +| Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,必须仍在当前 PR 的 commits 中 | +| Rejected | `Reason` | 非空拒绝理由 | +| Invalid | `Reason` | 非空误报理由 | +| Deferred | `Reason`、`Tracking` | 存在且开放的 GitHub Issue,或指定 Jira 域名下的 ticket URL | -`Fix` ֤���ύ������Ч�����߲��жϸ��ύ�Ƿ������޸����⡣���ɵij���ԡ�Jira ticket �Ĵ�����״̬���Լ� deferral ��ҵ��ɽ������� Human Review ��顣��ǰ�汾��֧���� tracking �Ŀ�ͷ���⣻��δ������������Ӧ��֤�����˵����ݼ�������¼�������ǽ��� Contributor ���� `Approved: yes`�� +`Fix` 证明提交引用有效;工具不判断该提交是否真正修复问题。理由的充分性、Jira ticket 的存在与状态,以及 deferral 的业务可接受性由 Human Review 审查。当前版本不支持无 tracking 的口头豁免;若未来接入审批,应验证审批人的身份及审批记录,而不是接受 Contributor 自填 `Approved: yes`。 -## Contributor �ظ���ʽ +## Contributor 回复格式 -ֱ���ڶ�Ӧ inline thread �лظ�����һ�б����� `Disposition: ...`��ÿ���ֶε���һ�У��������к��ֶ���/״̬��Сд�仯����Ҫ�����š�Markdown ���á�����������ֶΡ�`Reason` ����һ�У����������ġ� +直接在对应 inline thread 中回复。第一行必须是 `Disposition: ...`,每个字段单独一行;允许空行和字段名/状态大小写变化。不要加引号、Markdown 引用、代码块或额外字段。`Reason` 保持一行,可以用中文。 -Accepted�� +Accepted: ```text Disposition: Accepted -Reason: �Ѳ��������߽��жϣ������ӻع���ԡ� +Reason: 已补充空数组边界判断,并增加回归测试。 Fix: 0123456789abcdef0123456789abcdef01234567 ``` -Rejected�� +Rejected: ```text Disposition: Rejected -Reason: �����������֤���������˴������յ��������롣 +Reason: 调用入口已验证该条件,此处不会收到负数输入。 ``` -Invalid�� +Invalid: ```text Disposition: Invalid -Reason: ��ʵ��ʹ���첽ִ�У�����������ͬ������·�������ڡ� +Reason: 此实现使用异步执行,评论所述的同步调用路径不存在。 ``` -Deferred�� +Deferred: ```text Disposition: Deferred -Reason: ��������ɼ����޸��������Ż��ں����汾������ +Reason: 本次先完成兼容修复,性能优化在后续版本处理。 Tracking: https://github.com/IS-Model-Framework/example/issues/42 ``` -���� `AI_REVIEW_JIRA_URL=https://example.atlassian.net` ��Ҳ���� `Tracking: https://example.atlassian.net/browse/PROJ-123`������������ HTTPS ���ӡ��� ticket ��Ż� PR ���ӡ�GitHub Issue ��Ҫ��ǰ token �ɶ�ȡ�������ֿ��˽�� Issue ������Ҫ GitHub App installation token�� +配置 `AI_REVIEW_JIRA_URL=https://example.atlassian.net` 后,也接受 `Tracking: https://example.atlassian.net/browse/PROJ-123`。不接受任意 HTTPS 链接、裸 ticket 编号或 PR 链接。GitHub Issue 需要当前 token 可读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 -�������±༭ʱ�����ȷ disposition �ظ���ͬһʱ��ȡ thread �и���Ļظ����µIJ����� disposition ������ɵ���Ч�ظ����������ù��ھ�������ͨ�����ظ�������� disposition��AI �༭ finding ��׷�� inline �ظ�����Ҫ����ȷ�� disposition���������ύ��� review �ı�ǡ��޸��ύ�� force-push �Ƴ� PR ��Accepted ʧЧ�� +采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。AI 编辑 finding 或追加 inline 回复后,需要重新确认 disposition,并重新提交完成 review 的标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 -��Ч�ظ�֮���� Contributor / Maintainer Resolve Conversation�����߲����Զ� Resolve��ֻ Resolve��ֻд ��done / ���޸������� PR �ܽ���ͳһ�ش𣬶�����ͨ���� +有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 -## AI Bot ���Э�� +## AI Bot 完成协议 -Bot �� review ���̱������أ� +Bot 的 review 流程必须遵守: -1. �Թ̶��� PR head SHA ���� findings���� inline threads ������ -2. ȫ�� findings ������Ϻ��ύһ���� pending �� review�������İ�������һ�У� +1. 对固定的 PR head SHA 生成 findings,用 inline threads 发布。 +2. 全部 findings 发布完毕后,提交一个非 pending 的 review,其正文包含独立一行: ```text - AI-Review-Complete: <��ǰ PR ������ head SHA> + AI-Review-Complete: <当前 PR 的完整 head SHA> ``` -3. review ������ `commit.oid` Ҳ������ڸ� SHA��û�� findings ʱ����Ҫ��� review�������������⡱�͡���δ��ʼ review����������� -4. ��ǰ head �ı������ review ���ύ����ɱ�ǡ������ύ���� review δ����ǡ�review �� dismissed������ Bot ����ɱ��֮���������/�༭ finding�������ͨ���� +3. review 本身的 `commit.oid` 也必须等于该 SHA。没有 findings 时仍需要这个 review;这样“零问题”和“尚未开始 review”不会混淆。 +4. 当前 head 改变后,重新 review 并提交新完成标记。后续提交的新 review 未含标记、review 被 dismissed,或者 Bot 在完成标记之后继续增加/编辑 finding,均阻断通过。 -���DZ����ߵļ���Э�飬���� GitHub �Դ����ֶΡ����� Bot �������ṩ�ñ�ǣ���Ҫ�޸��䷢�����̣����ܽ�ƾ ��û�� unresolved threads�� �ƶ� review ����ɡ���Ҫ�� findings ��δȫ������ʱд����ɱ�ǡ� +这是本工具的集成协议,不是 GitHub 自带的字段。现有 Bot 若不能提供该标记,需要修改其发布流程;不能仅凭 “没有 unresolved threads” 推断 review 已完成。不要在 findings 尚未全部发布时写入完成标记。 -## Actions ���� +## Actions 接入 -`.github` �ֿ�� workflow �����Զ���������֯��Ŀִ�С�ÿ��Ŀ����Ŀ��Ҫ caller workflow��������֯ ruleset ����Ŀ��ֿ⡣ +`.github` 仓库的 workflow 不会自动在所有组织项目执行。每个目标项目需要 caller workflow,并由组织 ruleset 覆盖目标仓库。 -1. �� [ai-review-events.yml](examples/ai-review-events.yml) �� [ai-review-disposition.yml](examples/ai-review-disposition.yml) ���׸��Ƶ�Ŀ����Ŀ `.github/workflows/`������Ĭ�Ϸ�֧��collector �� `run-name` ���뱣��Ϊ PR ��ţ������� `workflow_run` ��λĿ�ꣻ��Ҫ�ij� PR ���⡣Ǩ���ڼ�� collector ����ʷ���в������¸�ʽ����ͨ���ֶ�ָ�� PR ���顣 -2. ����֯/�ֿ� Variables ���� `AI_REVIEW_BOTS` Ϊ׼ȷ�� login �б������ŷָ�����Ҫ Jira ʱ���� `AI_REVIEW_JIRA_URL`��ʾ���е� Bot ���Ʋ���ʵ��Ĭ�����á� -3. ���������� caller �� `uses: ...@main` �� `shared-ref: main` ͬʱ�̶������ֿ�ͬһ������� commit SHA�������ű��ӿ��� CI �ֿ���أ���ȫ�� checkout PR ���롣 -4. Ϊ `GITHUB_TOKEN` �ṩ `contents: read`��`pull-requests: read`��`issues: read`��`checks: write`�������֯ CI �ֿ��� private������Ҫ���� reusable workflow ����֯���ʣ���ͨ����ѡ secret `shared-read-token` �ṩ CI �ֿ��ֻ�� checkout token��caller �� `GITHUB_TOKEN` �����Զ�������� private �ֿ�Ķ�ȡȨ�ޡ� -5. ���һ�����к󣬽� **`AI Review / Disposition Check`** ���� ruleset �� Required Status Checks�������Դѡ�� GitHub Actions���������� Human Review / approval ���� +1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 与 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 配套复制到目标项目 `.github/workflows/`,合入默认分支。collector 的 `run-name` 必须保持为 PR 编号,供后续 `workflow_run` 定位目标;不要改成 PR 标题。迁移期间旧 collector 的历史运行不符合新格式,可通过手动指定 PR 复查。 +2. 在组织/仓库 Variables 设置 `AI_REVIEW_BOTS` 为准确的 login 列表,逗号分隔。需要 Jira 时设置 `AI_REVIEW_JIRA_URL`。示例中的 Bot 名称不是实际默认配置。 +3. 生产环境将 caller 的 `uses: ...@main` 与 `shared-ref: main` 同时固定到本仓库同一个已审核 commit SHA。共享脚本从可信 CI 仓库加载,完全不 checkout PR 代码。 +4. 为 `GITHUB_TOKEN` 提供 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。如果组织 CI 仓库是 private,还需要开启 reusable workflow 的组织访问,并通过可选 secret `shared-read-token` 提供 CI 仓库的只读 checkout token;caller 的 `GITHUB_TOKEN` 不会自动获得其他 private 仓库的读取权限。 +5. 完成一次运行后,将 **`AI Review / Disposition Check`** 加入 ruleset 的 Required Status Checks,检查来源选择 GitHub Actions。保持现有 Human Review / approval 规则。 -ѡ����ǽű�ͨ�� Checks API ������ PR **head commit** �ϵ� Check������ `Evaluate AI Review Dispositions` ��� Actions job��`pull_request_target`��`issue_comment`��`workflow_run` �� `GITHUB_SHA` ��һ���� PR head��ֱ��ʹ�� job success ���ϲ��Ž�������������ύ�� +选择的是脚本通过 Checks API 发布到 PR **head commit** 上的 Check,不是 `Evaluate AI Review Dispositions` 这个 Actions job。`pull_request_target`、`issue_comment`、`workflow_run` 的 `GITHUB_SHA` 不一定是 PR head;直接使用 job success 作合并门禁会关联到错误提交。 -| �¼� | ʾ���е�·�� | +| 事件 | 示例中的路径 | | --- | --- | -| PR opened / reopened / synchronize / ready_for_review | �� `pull_request.number` ȡ�ñ�ţ�ֻ���� PR | -| Review submitted / edited / dismissed | ��Ȩ�޵� collector �� PR ���д�� `run-name` �� Ĭ�Ϸ�֧ `workflow_run.display_title` �� ���� PR | -| Inline comment created / edited / deleted | ͬ�� | -| PR �������� created / edited / deleted | `issue_comment` �������飬����һ�� ��AI review recheck�� �������¼��� | -| Resolve / Unresolve | Actions ��ֱ��֧�ִ��¼����ֶ����顢�������ۣ��� App webhook �� `repository_dispatch` | -| Bot �� `GITHUB_TOKEN` ���� review/comments | ͨ�����ᴥ������ Actions��review workflow ��������ʽ���飬����� App token ���� | -| Actions �ֶ����� | ���� `pr-number`��ֻ���ָ�� PR | -| `repository_dispatch: ai-review-state-changed` | �� `client_payload.pr_number` �д���Ŀ�� PR ����������� | +| PR opened / reopened / synchronize / ready_for_review | 从 `pull_request.number` 取得编号,只检查该 PR | +| Review submitted / edited / dismissed | 无权限的 collector 把 PR 编号写入 `run-name` → 默认分支 `workflow_run.display_title` → 检查该 PR | +| Inline comment created / edited / deleted | 同上 | +| PR 顶层评论 created / edited / deleted | `issue_comment` 触发复查,可用一条 “AI review recheck” 评论重新计算 | +| Resolve / Unresolve | Actions 不直接支持此事件;手动复查、顶层评论,或 App webhook → `repository_dispatch` | +| Bot 用 `GITHUB_TOKEN` 发布 review/comments | 通常不会触发后续 Actions;review workflow 结束后显式复查,或改用 App token 发布 | +| Actions 手动运行 | 必填 `pr-number`,只检查指定 PR | +| `repository_dispatch: ai-review-state-changed` | 在 `client_payload.pr_number` 中传入目标 PR 的正整数编号 | -collector �������ִ�� PR ���ݡ����ϴ� artifact��caller �� `workflow_run.display_title` ʹ�� `fromJSON` ȡ�����ֱ�ţ���� fork �� `workflow_run.pull_requests` Ϊ��Ҳ�ܶ�λ��������ֻ����·����ʾ�������� collector �ṩ�������ۻ�ű�����дȨ�޵ļ����ʼ�մӿ��Ź����ֿ���أ����¶�ȡĿ��ֿ��и� PR ��ʵʱ API ���ݡ� +collector 不检出或执行 PR 内容、不上传 artifact。caller 对 `workflow_run.display_title` 使用 `fromJSON` 取得数字编号,因此 fork 的 `workflow_run.pull_requests` 为空也能定位。这个编号只用作路由提示,不接受 collector 提供的审查结论或脚本;有写权限的检查器始终从可信共享仓库加载,重新读取目标仓库中该 PR 的实时 API 数据。 -���÷��� CLI ��Ҫ����ʽ���������� PR ��ţ�ȱʧ��0��������Ƿ�ֵ�����������˵�ȫ�ֿ�ɨ�衣Ȩ�޼���� disposition ���򱣳ֲ��䡣 +调用方和 CLI 都要求显式传入正整数 PR 编号;缺失、0、负数或非法值报错,不回退到全仓库扫描。权限检查与 disposition 规则保持不变。 -����������ֿ����� PR ��ţ�`cancel-in-progress: false`��ͬһ PR �ļ�鴮�����У���ִ���¼���ʹ���������¼��滻��Ҳ�����¶�ȡͬһ PR ��ʵʱ״̬����ͬ PR �����ö��С�ͨ��֮ǰ��������ȡһ�� review ���ݣ������ύ�����۱仯��ʧ�ܡ��������ڵ� API ����᳢��д failure������/���� Check ������ʧ�ܡ���ʱ��ȡ���������� in-progress Check����Ȼ��ֹ�ϲ��� +并发组包含仓库名和 PR 编号,`cancel-in-progress: false`。同一 PR 的检查串行运行,待执行事件即使被后来的事件替换,也会重新读取同一 PR 的实时状态;不同 PR 不共用队列。通过之前再完整读取一次 review 数据,发现提交或评论变化就失败。检查过程内的 API 错误会尝试写 failure;创建/更新 Check 请求本身失败、超时或取消可能留下 in-progress Check,仍然阻止合并。 -�ֶ�������� Actions ҳ������ `AI Review Disposition` ����д `pr-number`��CLI ʾ���� +手动复查可在 Actions 页面运行 `AI Review Disposition` 并填写 `pr-number`。CLI 示例: ```bash GH_TOKEN="" python scripts/check_ai_review_disposition.py \ @@ -123,40 +123,40 @@ GH_TOKEN="" python scripts/check_ai_review_disposition.py \ --bots 'reviewer[bot]' ``` -���������ͨ�� Checks API д��ָ�� PR �� Check������ dry-run��Token ͨ�����������ṩ����Ӧ�ύ���ֿ⡣`--pr-number` �����ұ������ 0���˳��룺0 Ŀ�� PR ͨ�����ѹرն�������1 Ŀ�� PR ��ͨ���������������в���� API ���󣩣�2 ���������δ�����ִ�д��� +这条命令会通过 Checks API 写入指定 PR 的 Check,不是 dry-run。Token 通过环境变量提供;不应提交到仓库。`--pr-number` 必填且必须大于 0。退出码:0 目标 PR 通过或已关闭而跳过,1 目标 PR 不通过(包括检查过程中捕获的 API 错误),2 参数错误或未捕获的执行错误。 -## �ϸ���֯�Ž���GitHub App +## 严格组织门禁:GitHub App -Actions �����ʺϳ��ڽ��룬������֤���۱仯��˲�䳷�� success���¼��Ŷӡ������ӳ١�Resolve/Unresolve ȱ��ԭ�� trigger����������״̬���´��ڡ���Ҫ�ϸ񸲸� thread ״̬�仯ʱ��������֯��װר�� GitHub App����ͬһ���������Ϊִ�к��ģ� +Actions 方案适合初期接入,但不保证评论变化后瞬间撤销 success:事件排队、运行延迟、Resolve/Unresolve 缺少原生 trigger,都会留下状态更新窗口。需要严格覆盖 thread 状态变化时,建议组织安装专用 GitHub App,用同一个检查器作为执行核心: ```mermaid flowchart LR - A[PR / Review / Comment / Thread webhook] --> B[��֤ǩ������ PR �����Ŷ�] - B --> C[����ǰ head �Ĺ̶� Check ��� in_progress] - C --> D[��ҳ��ȡʵʱ reviews / threads / comments / commits] - D --> E{���Э�� + disposition + resolved} - E -->|����| F[success] - E -->|δ����� API ʧ��| G[failure] - F --> H[Human Review �� Required Approval] + A[PR / Review / Comment / Thread webhook] --> B[验证签名并按 PR 串行排队] + B --> C[将当前 head 的固定 Check 标记 in_progress] + C --> D[分页读取实时 reviews / threads / comments / commits] + D --> E{完成协议 + disposition + resolved} + E -->|满足| F[success] + E -->|未满足或 API 失败| G[failure] + F --> H[Human Review 与 Required Approval] ``` -App Ӧ���� `pull_request`��`pull_request_review`��`pull_request_review_comment`��`pull_request_review_thread` ����� actions����֧�� Check rerequest���� webhook signature �� delivery ID У��/ȥ�أ�ÿ�� PR ���и���ͬһ�� head �� Check���仯ʱ���������� success������ʧ�ܱ�����ϣ����Զ��� reconciliation �ָ�©��/��ʧ�¼��� +App 应订阅 `pull_request`、`pull_request_review`、`pull_request_review_comment`、`pull_request_review_thread` 的相关 actions,并支持 Check rerequest;用 webhook signature 与 delivery ID 校验/去重,每个 PR 串行更新同一个 head 的 Check,变化时立即撤销旧 success。重试失败保持阻断,并以定期 reconciliation 恢复漏发/丢失事件。 -Ȩ��Ϊ Pull requests read��Contents read��Issues read��Checks write����װ token ֻ���ǻ���Ȩ�ֿ⡣�����ÿ�ֿ� Issue����Ҫ��Ӧ�ֿ����Ȩ�ޡ���ǰ�ύδ���� App �� webhook ���񡢲����־û��˱��� +权限为 Pull requests read、Contents read、Issues read、Checks write;安装 token 只覆盖获授权仓库。若调用跨仓库 Issue,需要相应仓库访问权限。当前提交未包含 App 的 webhook 服务、部署或持久化账本。 -GitHub �� Status Check �����첽״̬���޷��ѡ����������ۡ��͡�ִ�� merge������һ��ԭ�����񡣸�Ҫ�󳡾���Ӧ���÷�֧������ conversation resolution����ͨ���ܿ� merge ����ںϲ�ǰ�ٴκ��顣AI findings ��ɾ����ʵʱ API ���ٱ������ǣ���Ҫ��ɾ��Ҳ�������ۣ�App ��Ҫ�־û� finding ID �� disposition ��ʷ���˰汾����� API ���ݵ�������ɾ�ĵ�����˱��� +GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和“执行 merge”做成一个原子事务。高要求场景还应启用分支保护的 conversation resolution,并通过受控 merge 入口在合并前再次核验。AI findings 被删除后,实时 API 不再保留它们;若要求删除也必须留痕,App 需要持久化 finding ID 与 disposition 历史。此版本不会把 API 数据当作不可删改的审计账本。 -�� Check �� PR head Ϊ���󣻵�ǰ��֧�� merge queue ���ɵĺϳ� SHA��ʹ�� merge queue ����Ŀ��Ҫ������� `merge_group` �ij�Ա PR ���飬����ֱ�����ô� caller ��Ϊ���� required check�� +该 Check 以 PR head 为对象;当前不支持 merge queue 生成的合成 SHA。使用 merge queue 的项目需要另外设计 `merge_group` 的成员 PR 核验,不能直接沿用此 caller 作为队列 required check。 -## ��֤��ο� +## 验证与参考 ```bash python -m unittest discover -s scripts/tests -v ``` -���Ը��Ǵ���״̬���ظ�Ȩ�ޡ����Э�顢outdated/resolved threads��force-push����ҳ��API �������ȡ�ڼ����� findings���Լ��� PR CLI���ܾ�ȱʧ/�Ƿ���š�closed PR ������ HTTP JSON ��д��API ͨ�� mock ��֤��������Ŀ��ֿ���һ����ʵ�� Bot Review �� �ظ� �� Resolve �� ���� �� Required Check �����С� +测试覆盖处理状态、回复权限、完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过和 HTTP JSON 读写。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot Review → 回复 → Resolve → 复查 → Required Check 试运行。 -- [GitHub Actions �¼��� fork / workflow_run ��Ϊ](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) -- [Webhook �¼���pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) -- [Checks API������������ Check Runs](https://docs.github.com/en/rest/checks/runs) -- [Reusable workflows ����֯������Ȩ��](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) +- [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) +- [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) +- [Checks API:发布并更新 Check Runs](https://docs.github.com/en/rest/checks/runs) +- [Reusable workflows 的组织接入与权限](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 4388837..bd4fecd 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -276,7 +276,7 @@ def summary(number, head, result): counts = Counter(f["status"] for f in result["findings"]) remaining = sum(bool(f["error"]) for f in result["findings"]) lines = [ - f"## PR #{number} �� AI Review Disposition", + f"## PR #{number} · AI Review Disposition", "", f"Head: `{head}`", "", diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 2d16d8e..ed83379 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -308,7 +308,7 @@ def respond(request, timeout): ) self.assertEqual( api.request( - "PATCH", "/repos/org/repo/check-runs/99", {"output": {"summary": "���ͨ��"}} + "PATCH", "/repos/org/repo/check-runs/99", {"output": {"summary": "检查通过"}} ), {"conclusion": "success"}, ) @@ -328,7 +328,7 @@ def respond(request, timeout): {"query": "query { viewer { login } }", "variables": {}}, ) self.assertEqual(json.loads(calls[2].data), {"head_sha": HEAD}) - self.assertEqual(json.loads(calls[3].data)["output"]["summary"], "���ͨ��") + self.assertEqual(json.loads(calls[3].data)["output"]["summary"], "检查通过") self.assertTrue( all(r.get_header("Authorization") == "Bearer test-token" for r in calls) ) From a50a5e9c6996d0c6d0b52aa89d28a8ea4fef1a57 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:41:03 +0800 Subject: [PATCH 05/21] fix[ci]: require real GitHub issues for deferred reviews Problem: - Jira URLs were accepted without checking that a follow-up item exists. Solution: - Remove Jira options and configuration from the checker and callers. - Accept only readable open GitHub issues verified through the Issues API. - Reject missing, closed, inaccessible issues and pull requests. Test: - Python 3.11: 44 unit tests passed. - 12 workflow expression cases passed. - Four read-only live Issue API probes passed; Check writes were mocked. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 6 -- docs/AI_REVIEW_DISPOSITION.md | 10 +- docs/examples/ai-review-disposition.yml | 1 - scripts/check_ai_review_disposition.py | 52 ++--------- scripts/tests/test_ai_review_disposition.py | 92 +++++++++++++------ 5 files changed, 80 insertions(+), 81 deletions(-) diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index 2fc1af6..a96cf5c 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -11,11 +11,6 @@ on: description: 'Positive PR number to check in the caller repository' required: true type: number - jira-url: - description: 'Optional trusted Jira base URL, e.g. https://example.atlassian.net' - required: false - type: string - default: '' shared-ref: description: 'Trusted revision of this repository; pin alongside workflow uses' required: false @@ -61,7 +56,6 @@ jobs: env: GH_TOKEN: ${{ github.token }} AI_REVIEW_BOTS: ${{ inputs.bot-logins }} - AI_REVIEW_JIRA_URL: ${{ inputs.jira-url }} PR_NUMBER: ${{ inputs.pr-number }} run: | python .ci-shared/scripts/check_ai_review_disposition.py \ diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 67bbc6b..c7c10ac 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -25,9 +25,9 @@ Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名 | Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,必须仍在当前 PR 的 commits 中 | | Rejected | `Reason` | 非空拒绝理由 | | Invalid | `Reason` | 非空误报理由 | -| Deferred | `Reason`、`Tracking` | 存在且开放的 GitHub Issue,或指定 Jira 域名下的 ticket URL | +| Deferred | `Reason`、`Tracking` | GitHub API 确认存在、当前 token 可读且仍开放的 Issue,不能是 PR | -`Fix` 证明提交引用有效;工具不判断该提交是否真正修复问题。理由的充分性、Jira ticket 的存在与状态,以及 deferral 的业务可接受性由 Human Review 审查。当前版本不支持无 tracking 的口头豁免;若未来接入审批,应验证审批人的身份及审批记录,而不是接受 Contributor 自填 `Approved: yes`。 +`Fix` 证明提交引用有效;工具不判断该提交是否真正修复问题。理由的充分性、跟踪 Issue 是否确实覆盖此条意见,以及 deferral 的业务可接受性由 Human Review 审查。当前版本不支持无 tracking 的口头豁免;若未来接入审批,应验证审批人的身份及审批记录,而不是接受 Contributor 自填 `Approved: yes`。 ## Contributor 回复格式 @@ -63,7 +63,7 @@ Reason: 本次先完成兼容修复,性能优化在后续版本处理。 Tracking: https://github.com/IS-Model-Framework/example/issues/42 ``` -配置 `AI_REVIEW_JIRA_URL=https://example.atlassian.net` 后,也接受 `Tracking: https://example.atlassian.net/browse/PROJ-123`。不接受任意 HTTPS 链接、裸 ticket 编号或 PR 链接。GitHub Issue 需要当前 token 可读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 +`Tracking` 只接受 `https://github.com/owner/repo/issues/number` 形式的完整 Issue 链接,不接受其他站点、裸编号、PR 链接、查询参数或锚点。检查器会实际调用 GitHub Issues API;不存在、已关闭、无法读取的 Issue,以及限流、鉴权或服务错误都不会通过。允许引用其他仓库的 Issue,但当前 token 必须能读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。AI 编辑 finding 或追加 inline 回复后,需要重新确认 disposition,并重新提交完成 review 的标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 @@ -90,7 +90,7 @@ Bot 的 review 流程必须遵守: `.github` 仓库的 workflow 不会自动在所有组织项目执行。每个目标项目需要 caller workflow,并由组织 ruleset 覆盖目标仓库。 1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 与 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 配套复制到目标项目 `.github/workflows/`,合入默认分支。collector 的 `run-name` 必须保持为 PR 编号,供后续 `workflow_run` 定位目标;不要改成 PR 标题。迁移期间旧 collector 的历史运行不符合新格式,可通过手动指定 PR 复查。 -2. 在组织/仓库 Variables 设置 `AI_REVIEW_BOTS` 为准确的 login 列表,逗号分隔。需要 Jira 时设置 `AI_REVIEW_JIRA_URL`。示例中的 Bot 名称不是实际默认配置。 +2. 在组织/仓库 Variables 设置 `AI_REVIEW_BOTS` 为准确的 login 列表,逗号分隔。示例中的 Bot 名称不是实际默认配置。 3. 生产环境将 caller 的 `uses: ...@main` 与 `shared-ref: main` 同时固定到本仓库同一个已审核 commit SHA。共享脚本从可信 CI 仓库加载,完全不 checkout PR 代码。 4. 为 `GITHUB_TOKEN` 提供 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。如果组织 CI 仓库是 private,还需要开启 reusable workflow 的组织访问,并通过可选 secret `shared-read-token` 提供 CI 仓库的只读 checkout token;caller 的 `GITHUB_TOKEN` 不会自动获得其他 private 仓库的读取权限。 5. 完成一次运行后,将 **`AI Review / Disposition Check`** 加入 ruleset 的 Required Status Checks,检查来源选择 GitHub Actions。保持现有 Human Review / approval 规则。 @@ -154,7 +154,7 @@ GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和 python -m unittest discover -s scripts/tests -v ``` -测试覆盖处理状态、回复权限、完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过和 HTTP JSON 读写。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot Review → 回复 → Resolve → 复查 → Required Check 试运行。 +测试覆盖处理状态、回复权限、完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过、HTTP JSON 读写和跟踪 Issue 的真实存在性校验路径。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot Review → 回复 → Resolve → 复查 → Required Check 试运行。 - [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) - [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index 747014a..c1ba6a9 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -39,7 +39,6 @@ jobs: || fromJSON(github.event.workflow_run.display_title || '0') }} # Set this repository/organization variable to exact bot logins. bot-logins: ${{ vars.AI_REVIEW_BOTS }} - jira-url: ${{ vars.AI_REVIEW_JIRA_URL }} shared-ref: main # If the shared CI repository is private: # secrets: diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index bd4fecd..bd4a427 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -8,7 +8,7 @@ import sys from collections import Counter from urllib.error import HTTPError -from urllib.parse import quote, urlparse +from urllib.parse import quote from urllib.request import Request, urlopen CHECK_NAME = "AI Review / Disposition Check" @@ -159,31 +159,6 @@ def parse_disposition(body): return fields -def tracking_target(value, server_url, jira_url): - server = urlparse(server_url) - target = urlparse(value) - if target.query or target.fragment or target.username or target.password: - return None - if target.scheme == server.scheme and target.netloc == server.netloc: - prefix = server.path.rstrip("/") - match = re.fullmatch( - re.escape(prefix) + r"/([\w.-]+)/([\w.-]+)/issues/([1-9]\d*)", target.path - ) - if match: - return ("github", *match.groups()) - if jira_url: - jira = urlparse(jira_url.rstrip("/")) - if ( - target.scheme == "https" - and target.netloc == jira.netloc - and re.fullmatch( - re.escape(jira.path) + r"/browse/[A-Z][A-Z0-9_]*-[1-9]\d*", target.path - ) - ): - return ("jira", value) - return None - - def evaluate(data, bots, authorized, tracking_valid): """Pure policy; API-dependent identity and tracking checks are supplied by caller.""" errors = [] @@ -256,7 +231,7 @@ def evaluate(data, bots, authorized, tracking_valid): reason = "Fix must be a full commit SHA in the current PR" elif not reason and status == "Deferred": if not tracking_valid(fields.get("tracking", "")): - reason = "Tracking must reference an open GitHub issue or configured Jira URL" + reason = "Tracking must reference an existing, readable, open GitHub issue" if not reason and not thread["isResolved"]: reason = "Disposition is valid; resolve the conversation" findings.append({ @@ -296,7 +271,7 @@ def summary(number, head, result): return "\n".join(lines) -def check_pr(api, repository, number, bots, server_url, jira_url): +def check_pr(api, repository, number, bots): pr = api.request("GET", f"/repos/{repository}/pulls/{number}") if pr["state"] != "open": return True @@ -326,14 +301,14 @@ def authorized(login, author): def tracking_valid(value): if value not in tracking: - target = tracking_target(value, server_url, jira_url) + match = re.fullmatch( + r"https://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9_.-]+/issues/[1-9][0-9]*)", + value, + ) valid = False - if target and target[0] == "jira": - valid = True - elif target: - _, owner, name, issue = target + if match: try: - item = api.request("GET", f"/repos/{owner}/{name}/issues/{issue}") + item = api.request("GET", f"/repos/{match[1]}") valid = item["state"] == "open" and "pull_request" not in item except HTTPError as error: if error.code != 404: @@ -382,7 +357,6 @@ def main(): parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY")) parser.add_argument("--pr-number", type=int, required=True, help="PR to check") parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) - parser.add_argument("--jira-url", default=os.environ.get("AI_REVIEW_JIRA_URL", "")) args = parser.parse_args() bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") @@ -397,14 +371,8 @@ def main(): parser.error( "Valid repository, nonempty bot logins, PR number > 0 and token required" ) - if args.jira_url: - jira = urlparse(args.jira_url) - if jira.scheme != "https" or not jira.netloc or jira.query or jira.fragment: - parser.error("Jira URL must be an HTTPS base URL") api = GitHub(token) - ok = check_pr( - api, args.repository, args.pr_number, bots, "https://github.com", args.jira_url - ) + ok = check_pr(api, args.repository, args.pr_number, bots) return 0 if ok else 1 diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index ed83379..18eed24 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -4,6 +4,7 @@ import sys import unittest from unittest.mock import patch +from urllib.error import HTTPError from scripts.check_ai_review_disposition import ( CHECK_NAME, @@ -15,7 +16,6 @@ passed, snapshot, summary, - tracking_target, ) HEAD = "a" * 40 @@ -256,27 +256,6 @@ def test_summary_separates_status_counts_and_remaining_requirements(self): self.assertIn("unresolved requirements: 1", report) self.assertIn("| 1 | 0 | 0 | 0 | 0 |", report) - def test_tracking_urls_are_bound_to_trusted_hosts(self): - self.assertEqual( - tracking_target( - "https://github.com/org/repo/issues/42", "https://github.com", "" - ), - ("github", "org", "repo", "42"), - ) - self.assertIsNotNone( - tracking_target( - "https://jira.test/browse/PROJ-42", "https://github.com", "https://jira.test" - ) - ) - for url in ( - "http://jira.test/browse/PROJ-42", - "https://jira.test.evil/browse/PROJ-42", - "https://github.com/org/repo/pull/42", - "https://github.com/org/repo/issues/42?redirect=1", - "https://user@github.com/org/repo/issues/42", - ): - self.assertIsNone(tracking_target(url, "https://github.com", "https://jira.test")) - class ApiTests(unittest.TestCase): def test_http_client_reads_and_writes_github_json(self): @@ -411,6 +390,62 @@ def test_closed_tracking_issue_or_pr_cannot_defer(self): self.assertFalse(ok) self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + def test_deferred_requires_a_successful_open_issue_lookup(self): + data = fixture( + "Disposition: Deferred\nReason: Follow up\n" + "Tracking: https://github.com/org/repo/issues/42" + ) + calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) + self.assertTrue(ok) + self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) + self.assertEqual(calls[-1].args[2]["conclusion"], "success") + + def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): + data = fixture( + "Disposition: Deferred\nReason: Follow up\n" + "Tracking: https://github.com/org/repo/issues/42" + ) + for status in (404, 401, 403, 429, 500): + with self.subTest(status=status): + error = HTTPError("https://api.github.com/issue", status, "error", {}, None) + calls, ok = self.run_check([data], error) + self.assertFalse(ok) + self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def test_only_canonical_github_issue_urls_are_queried(self): + for url in ( + "https://jira.test/browse/PROJ-42", + "https://github.com.evil/org/repo/issues/42", + "http://github.com/org/repo/issues/42", + "https://github.com/org/repo/pull/42", + "https://github.com/org/repo/issues/0", + "https://github.com/org/repo/issues/42?redirect=1", + "https://github.com/org/repo/issues/42#issuecomment-1", + "https://user@github.com/org/repo/issues/42", + "PROJ-42", + ): + with self.subTest(url=url): + data = fixture(f"Disposition: Deferred\nReason: Follow up\nTracking: {url}") + calls, ok = self.run_check([data]) + self.assertFalse(ok) + # Only PR metadata, Check creation, and Check completion; no issue request. + self.assertEqual(len(calls), 3) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def test_multiple_findings_share_one_issue_lookup(self): + data = fixture( + "Disposition: Deferred\nReason: Follow up\n" + "Tracking: https://github.com/org/repo/issues/42" + ) + other = copy.deepcopy(data["threads"][0]) + other["id"] = "thread-2" + data["threads"].append(other) + calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) + self.assertTrue(ok) + issue_reads = [c for c in calls if c.args[:2] == ("GET", "/repos/org/repo/issues/42")] + self.assertEqual(len(issue_reads), 1) + def run_check(self, snapshots, issue=None): api = GitHub("test-token") pr = {"head": {"sha": HEAD}, "state": "open"} @@ -424,7 +459,7 @@ def run_check(self, snapshots, issue=None): patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), patch("builtins.print"), ): - ok = check_pr(api, "org/repo", 128, {BOT}, "https://github.com", "") + ok = check_pr(api, "org/repo", 128, {BOT}) return request.call_args_list, ok @@ -446,7 +481,7 @@ def test_checks_only_the_requested_pr(self): self.assertEqual(code, 0) client.assert_called_once_with("test-token") check.assert_called_once_with( - client.return_value, "org/repo", 313, {BOT}, "https://github.com", "" + client.return_value, "org/repo", 313, {BOT} ) client.return_value.open_prs.assert_not_called() @@ -469,11 +504,14 @@ def test_missing_or_invalid_pr_never_defaults_to_a_repository_scan(self): def test_closed_pr_does_not_create_a_check(self): api = GitHub("test-token") with patch.object(api, "request", return_value={"state": "closed"}) as request: - self.assertTrue( - check_pr(api, "org/repo", 313, {BOT}, "https://github.com", "") - ) + self.assertTrue(check_pr(api, "org/repo", 313, {BOT})) request.assert_called_once_with("GET", "/repos/org/repo/pulls/313") + def test_removed_jira_option_is_not_accepted(self): + with self.assertRaises(SystemExit) as error: + self.run_main("--pr-number", "313", "--jira-url", "https://jira.test") + self.assertEqual(error.exception.code, 2) + if __name__ == "__main__": unittest.main() From e8f487c25e78dbb76db650efd118e4d283983e49 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:03:07 +0800 Subject: [PATCH 06/21] fix[ci]: check human inline review dispositions Problem: - Human reviewer threads were skipped by the disposition check. Solution: - Include published inline threads from humans other than the PR author. - Reuse the existing template, evidence, permission and resolution checks. - Require a fresh disposition after the originating reviewer updates a thread. - Preserve configured bot identity precedence and the bot completion protocol. Test: - Python 3.11: all 57 tests passed, including 50 disposition tests. - AST checks confirm both bot completion loops and other functions are unchanged. - git diff --check passed. JIRA: PDIST-770 --- docs/AI_REVIEW_DISPOSITION.md | 12 +- scripts/check_ai_review_disposition.py | 16 +- scripts/tests/test_ai_review_disposition.py | 166 +++++++++++++++----- 3 files changed, 147 insertions(+), 47 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index c7c10ac..480e2aa 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,6 +1,6 @@ # AI Review / Disposition Check -目标:所有需要响应的 AI inline findings 都有可审计的处理记录,并且对话已 Resolve。检查不要求采纳 AI 建议,也不代替 Human Review。 +目标:配置的 AI Bot 和 PR 作者之外的人工 reviewer 提出的行内意见都有可审计的处理记录,并且对话已 Resolve。检查不要求采纳审查建议,也不代替 Human Review。 本仓库提供 [Python 检查器](../scripts/check_ai_review_disposition.py)、[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) 和两个项目接入示例。规则单独运行,不并入现有 `CI Result`:代码 CI 与 review 的完成时间不同,回复评论也不应该重新运行测试。 @@ -10,13 +10,13 @@ ```text 每个指定 AI Bot 已完成当前 head SHA 的 review -AND 每个 AI finding 有授权人员的有效 disposition +AND 每个纳入范围的 AI / 人工行内意见有授权人员的有效 disposition AND 每个 finding 的 conversation 已 Resolve ``` -检查范围为配置的 Bot 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding;Bot 应把不同问题分成不同 threads。以人类评论开头的 thread 不计入,PR 顶层评论/总结也不计为 finding。尚未提交的 pending review 不计入已发布 findings。 +检查范围为配置的 Bot,以及 PR 作者之外的人工 reviewer 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding,不同问题应分成不同 threads;AI 和人工意见共用以下模板、证据、回复权限和 Resolve 要求。PR 作者自行创建的人工 thread、未配置的 GitHub Bot thread、PR 顶层普通评论和 Review 总评不计为 finding。尚未提交的 pending review 不计入已发布 findings。 -Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。`AI_REVIEW_BOTS` 中的每个 Bot 都必须完成 review。空配置是错误,不会当作“无 AI 问题”通过。 +Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。配置的 Bot 优先按 AI 处理,即使其账号类型是 `User`(如 `infiscale-bot`)或恰好是 PR 作者。其他 `User` 按人工账号处理。`AI_REVIEW_BOTS` 中的每个 Bot 都必须完成 review;人工 reviewer 不需要完成标记。空配置是错误,不会当作“无 AI 问题”通过。本次只扩展意见范围,未修改 AI Bot 完成协议。 回复者必须是 PR 作者或当前拥有仓库 `write` / `maintain` / `admin` 权限的人员。其他人员的回复不生效;GitHub Bot 和已配置的 AI 服务账号不能自行 disposition。仅有组织成员身份不足以授权回复。 @@ -65,7 +65,7 @@ Tracking: https://github.com/IS-Model-Framework/example/issues/42 `Tracking` 只接受 `https://github.com/owner/repo/issues/number` 形式的完整 Issue 链接,不接受其他站点、裸编号、PR 链接、查询参数或锚点。检查器会实际调用 GitHub Issues API;不存在、已关闭、无法读取的 Issue,以及限流、鉴权或服务错误都不会通过。允许引用其他仓库的 Issue,但当前 token 必须能读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 -采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。AI 编辑 finding 或追加 inline 回复后,需要重新确认 disposition,并重新提交完成 review 的标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 +采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。发起该 thread 的 reviewer 或配置的 AI Bot 编辑意见或追加 inline 回复后,需要重新确认 disposition。AI 的活动仍按下述完成协议检查;人工意见变化不要求人工提供完成标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 @@ -154,7 +154,7 @@ GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和 python -m unittest discover -s scripts/tests -v ``` -测试覆盖处理状态、回复权限、完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过、HTTP JSON 读写和跟踪 Issue 的真实存在性校验路径。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot Review → 回复 → Resolve → 复查 → Required Check 试运行。 +测试覆盖 AI / 人工行内意见的处理状态、回复权限、范围排除、意见变化后的重新确认、AI 完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过、HTTP JSON 读写和跟踪 Issue 的真实存在性校验路径。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot / Human Review → 回复 → Resolve → 复查 → Required Check 试运行。 - [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) - [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index bd4a427..fddf8c7 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -191,7 +191,11 @@ def evaluate(data, bots, authorized, tracking_valid): if not comments: continue root = comments[0] - if actor_login(root.get("author")) not in bots: + reviewer = actor_login(root.get("author")) + if reviewer not in bots and ( + (root.get("author") or {}).get("__typename") != "User" + or reviewer == data["author"] + ): continue for bot in bots: if bot in completed_at and any( @@ -201,8 +205,10 @@ def evaluate(data, bots, authorized, tracking_valid): error = f"{bot}: findings changed after review completion" if error not in errors: errors.append(error) - bot_activity = max( - c["updatedAt"] for c in comments if actor_login(c.get("author")) in bots + reviewer_activity = max( + c["updatedAt"] + for c in comments + if actor_login(c.get("author")) in (bots | {reviewer}) ) candidates = [] for comment in comments[1:]: @@ -223,8 +229,8 @@ def evaluate(data, bots, authorized, tracking_valid): comment, fields = latest status = fields.get("disposition", "Unaddressed") reason = fields.get("error", "") - if comment["updatedAt"] < bot_activity: - reason = "AI comment changed after disposition; reply again" + if comment["updatedAt"] < reviewer_activity: + reason = "Review comment changed after disposition; reply again" elif not reason and status == "Accepted": fix = fields.get("fix", "").lower() if not re.fullmatch(r"[0-9a-f]{40}", fix) or fix not in data["commits"]: diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 18eed24..2b85a87 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -35,8 +35,8 @@ def comment(body, login="contributor", timestamp="2026-10-09T02:00:00Z"): } -def fixture(body=None, resolved=True): - comments = [comment("Please fix this", BOT, "2026-10-09T01:00:00Z")] +def fixture(body=None, resolved=True, reviewer=BOT): + comments = [comment("Please fix this", reviewer, "2026-10-09T01:00:00Z")] if body: comments.append(comment(body)) return { @@ -85,9 +85,10 @@ def test_all_dispositions_pass_with_required_evidence(self): "Tracking: https://github.com/org/repo/issues/42" ), ] - for body in replies: - with self.subTest(body=body): - self.assertTrue(passed(result(fixture(body)))) + for reviewer in (BOT, "human-reviewer"): + for body in replies: + with self.subTest(reviewer=reviewer, body=body): + self.assertTrue(passed(result(fixture(body, reviewer=reviewer)))) def test_resolve_alone_does_not_pass(self): evaluation = result(fixture()) @@ -221,18 +222,103 @@ def test_new_finding_after_completion_requires_new_marker(self): data["reviews"][0]["submittedAt"] = "2026-10-09T01:50:00Z" self.assertTrue(passed(result(data))) - def test_human_root_thread_is_not_an_ai_finding(self): - data = fixture() - data["threads"][0]["comments"][0]["author"] = { - "login": "maintainer", - "__typename": "User", - } + def test_human_findings_require_complete_dispositions(self): + for body in ( + None, + "done", + "Disposition: Rejected", + "Disposition: Unknown\nReason: Test", + "Disposition: Accepted\nReason: Fixed", + f"Disposition: Accepted\nReason: Fixed\nFix: {'c' * 40}", + "Disposition: Deferred\nReason: Later", + "Disposition: Deferred\nReason: Later\nTracking: ISSUE-42", + ): + with self.subTest(body=body): + evaluation = result(fixture(body, reviewer="human-reviewer")) + self.assertFalse(passed(evaluation)) + self.assertEqual(len(evaluation["findings"]), 1) + + def test_human_findings_keep_resolve_and_reply_permissions(self): + for resolved, login in ((False, "contributor"), (True, "stranger"), (True, BOT)): + with self.subTest(resolved=resolved, login=login): + data = fixture( + "Disposition: Invalid\nReason: Test", resolved, "human-reviewer" + ) + data["threads"][0]["comments"][-1]["author"]["login"] = login + data["threads"][0]["isOutdated"] = True + evaluation = result(data) + self.assertFalse(passed(evaluation)) + self.assertEqual(len(evaluation["findings"]), 1) + data["threads"][0]["comments"][-1]["author"]["login"] = "maintainer" self.assertTrue(passed(result(data))) - def test_pending_review_comments_are_not_published_findings(self): - data = fixture() - data["threads"][0]["comments"][0]["pullRequestReview"]["state"] = "PENDING" + def test_pr_author_deleted_author_and_unconfigured_bots_are_excluded(self): + for author in ( + {"login": "contributor", "__typename": "User"}, + None, + {"login": "other", "__typename": "Bot"}, + ): + with self.subTest(author=author): + data = fixture() + data["threads"][0]["comments"][0]["author"] = author + self.assertEqual(result(data)["findings"], []) + self.assertTrue(passed(result(data))) + + def test_configured_user_bot_takes_priority_over_pr_author_exclusion(self): + for owner in ("contributor", "infiscale-bot"): + with self.subTest(owner=owner): + data = fixture("Disposition: Invalid\nReason: Test", reviewer="infiscale-bot") + data["author"] = owner + data["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} + data["threads"][0]["comments"][-1]["author"]["login"] = "maintainer" + self.assertTrue(passed(result(data, bots={"infiscale-bot"}))) + data["threads"][0]["comments"][-1]["author"]["login"] = "infiscale-bot" + self.assertFalse(passed(result(data, bots={"infiscale-bot"}))) + + def test_human_review_changes_require_a_fresh_disposition(self): + for follow_up in (False, True): + with self.subTest(follow_up=follow_up): + data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") + comments = data["threads"][0]["comments"] + if follow_up: + comments.append( + comment("Follow up", "human-reviewer", "2026-10-09T03:00:00Z") + ) + else: + comments[0]["updatedAt"] = "2026-10-09T03:00:00Z" + evaluation = result(data) + self.assertEqual(evaluation["errors"], []) + self.assertIn("changed", evaluation["findings"][0]["error"]) + comments[1]["updatedAt"] = "2026-10-09T04:00:00Z" + self.assertTrue(passed(result(data))) + + def test_human_reviews_do_not_require_completion_markers(self): + data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") + data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T01:45:00Z" + human_review = copy.deepcopy(data["reviews"][0]) + human_review.update(author={"login": "human-reviewer"}, body="General feedback") + data["reviews"].append(human_review) self.assertTrue(passed(result(data))) + data["reviews"][0]["body"] = "" + self.assertFalse(passed(result(data))) + + def test_unaddressed_human_finding_blocks_an_addressed_ai_finding(self): + data = fixture("Disposition: Invalid\nReason: Test") + other = fixture(reviewer="human-reviewer")["threads"][0] + other["id"] = "human-thread" + data["threads"].append(other) + evaluation = result(data) + self.assertFalse(passed(evaluation)) + self.assertEqual(len(evaluation["findings"]), 2) + self.assertEqual(evaluation["findings"][0]["error"], "") + self.assertEqual(evaluation["findings"][1]["status"], "Unaddressed") + + def test_pending_review_comments_are_not_published_findings(self): + for reviewer in (BOT, "human-reviewer"): + with self.subTest(reviewer=reviewer): + data = fixture(reviewer=reviewer) + data["threads"][0]["comments"][0]["pullRequestReview"]["state"] = "PENDING" + self.assertTrue(passed(result(data))) def test_quoted_and_fenced_dispositions_are_not_replies(self): for text in ( @@ -368,12 +454,14 @@ def test_check_is_written_to_pr_head_not_event_sha(self): self.assertEqual(calls[-1].args[2]["conclusion"], "success") def test_new_finding_during_read_prevents_success(self): - data = fixture("Disposition: Invalid\nReason: False positive") - changed = copy.deepcopy(data) - changed["threads"].append(fixture()["threads"][0]) - calls, ok = self.run_check([data, changed]) - self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + for reviewer in (BOT, "human-reviewer"): + with self.subTest(reviewer=reviewer): + data = fixture("Disposition: Invalid\nReason: False positive") + changed = copy.deepcopy(data) + changed["threads"].append(fixture(reviewer=reviewer)["threads"][0]) + calls, ok = self.run_check([data, changed]) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") def test_api_failure_finishes_check_as_failure(self): calls, ok = self.run_check(RuntimeError("failed")) @@ -381,24 +469,30 @@ def test_api_failure_finishes_check_as_failure(self): self.assertEqual(calls[-1].args[2]["conclusion"], "failure") def test_closed_tracking_issue_or_pr_cannot_defer(self): - data = fixture( - "Disposition: Deferred\nReason: Later\nTracking: https://github.com/org/repo/issues/42" - ) - for item in ({"state": "closed"}, {"state": "open", "pull_request": {}}): - with self.subTest(item=item): - calls, ok = self.run_check([data], item) - self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + for reviewer in (BOT, "human-reviewer"): + data = fixture( + "Disposition: Deferred\nReason: Later\n" + "Tracking: https://github.com/org/repo/issues/42", + reviewer=reviewer, + ) + for item in ({"state": "closed"}, {"state": "open", "pull_request": {}}): + with self.subTest(reviewer=reviewer, item=item): + calls, ok = self.run_check([data], item) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") def test_deferred_requires_a_successful_open_issue_lookup(self): - data = fixture( - "Disposition: Deferred\nReason: Follow up\n" - "Tracking: https://github.com/org/repo/issues/42" - ) - calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) - self.assertTrue(ok) - self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) - self.assertEqual(calls[-1].args[2]["conclusion"], "success") + for reviewer in (BOT, "human-reviewer"): + with self.subTest(reviewer=reviewer): + data = fixture( + "Disposition: Deferred\nReason: Follow up\n" + "Tracking: https://github.com/org/repo/issues/42", + reviewer=reviewer, + ) + calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) + self.assertTrue(ok) + self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) + self.assertEqual(calls[-1].args[2]["conclusion"], "success") def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): data = fixture( From 14e30cb4d63ec1da0305913d8eb19f51967ee687 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:07:29 +0800 Subject: [PATCH 07/21] fix[ci]: preserve human replies and accept commit links Problem: - Human follow-up discussion invalidated an existing disposition. - Fix required manually copying a full commit SHA. Solution: - Invalidate human dispositions only when the root review comment changes. - Accept current-repository commit URLs alongside full SHAs. - Reuse PR commit membership checks without extra API requests. - Keep AI comment freshness and bot completion rules unchanged. Test: - Python 3.11: all 63 tests passed. - Regression cases cover human follow-ups, root edits and Unresolve. - Commit URL cases cover repository, host, SHA, force-push and API request counts. - AST checks confirm unchanged bot completion loops and existing API reads. - git diff --check passed. JIRA: PDIST-770 --- docs/AI_REVIEW_DISPOSITION.md | 8 +- scripts/check_ai_review_disposition.py | 19 ++-- scripts/tests/test_ai_review_disposition.py | 119 ++++++++++++++++---- 3 files changed, 113 insertions(+), 33 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 480e2aa..82db612 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -22,7 +22,7 @@ Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名 | Disposition | 必须提供的字段 | 检查的证据 | | --- | --- | --- | -| Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,必须仍在当前 PR 的 commits 中 | +| Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,或当前仓库的标准 commit 链接;提交必须仍在当前 PR 的 commits 中 | | Rejected | `Reason` | 非空拒绝理由 | | Invalid | `Reason` | 非空误报理由 | | Deferred | `Reason`、`Tracking` | GitHub API 确认存在、当前 token 可读且仍开放的 Issue,不能是 PR | @@ -38,9 +38,11 @@ Accepted: ```text Disposition: Accepted Reason: 已补充空数组边界判断,并增加回归测试。 -Fix: 0123456789abcdef0123456789abcdef01234567 +Fix: https://github.com/IS-Model-Framework/example/commit/0123456789abcdef0123456789abcdef01234567 ``` +`Fix` 兼容直接填写完整 40 位 SHA。链接仅支持 `https://github.com/owner/repo/commit/<完整40位SHA>`,仓库必须与当前 PR 所在仓库一致;不接受短 SHA、其他站点或仓库、PR 链接、查询参数和锚点。链接提取 SHA 后复用现有 PR 提交列表校验,不增加 API 请求。实际回复作为普通文本发送,不要包在代码块里,commit 链接即可点击跳转;延期 Issue 链接仍填写在 `Tracking` 字段中。 + Rejected: ```text @@ -65,7 +67,7 @@ Tracking: https://github.com/IS-Model-Framework/example/issues/42 `Tracking` 只接受 `https://github.com/owner/repo/issues/number` 形式的完整 Issue 链接,不接受其他站点、裸编号、PR 链接、查询参数或锚点。检查器会实际调用 GitHub Issues API;不存在、已关闭、无法读取的 Issue,以及限流、鉴权或服务错误都不会通过。允许引用其他仓库的 Issue,但当前 token 必须能读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 -采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。发起该 thread 的 reviewer 或配置的 AI Bot 编辑意见或追加 inline 回复后,需要重新确认 disposition。AI 的活动仍按下述完成协议检查;人工意见变化不要求人工提供完成标记。修复提交被 force-push 移出 PR 后,Accepted 失效。 +采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。人工线程只在原始审查意见的编辑时间晚于模板回复时要求重新确认;reviewer 后续追加“好的”“谢谢”或普通讨论不会使已有模板失效。新问题应新开线程或编辑原始意见。AI 线程仍按原有规则处理 AI 的编辑和追加回复,AI 完成协议不变;人工 reviewer 不需要完成标记。修复提交被 force-push 移出 PR 后,Accepted 的 SHA 和链接两种格式都失效。 有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index fddf8c7..d0e5bb2 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -125,6 +125,7 @@ def snapshot(api, repository, number): if current["head"]["sha"] != pr["head"]["sha"]: raise RuntimeError("PR head changed while reading review data; rerun required") return { + "repository": repository, "head": pr["head"]["sha"], "author": pr["user"]["login"].lower(), "state": current["state"], @@ -205,11 +206,11 @@ def evaluate(data, bots, authorized, tracking_valid): error = f"{bot}: findings changed after review completion" if error not in errors: errors.append(error) - reviewer_activity = max( - c["updatedAt"] - for c in comments - if actor_login(c.get("author")) in (bots | {reviewer}) - ) + reviewer_activity = root["updatedAt"] + if reviewer in bots: + reviewer_activity = max( + c["updatedAt"] for c in comments if actor_login(c.get("author")) in bots + ) candidates = [] for comment in comments[1:]: author = comment.get("author") or {} @@ -232,9 +233,13 @@ def evaluate(data, bots, authorized, tracking_valid): if comment["updatedAt"] < reviewer_activity: reason = "Review comment changed after disposition; reply again" elif not reason and status == "Accepted": - fix = fields.get("fix", "").lower() + fix = fields.get("fix", "") + link = re.fullmatch(r"https://github\.com/([^/]+/[^/]+)/commit/([^/]+)", fix) + if link and link[1].lower() == data["repository"].lower(): + fix = link[2] + fix = fix.lower() if not re.fullmatch(r"[0-9a-f]{40}", fix) or fix not in data["commits"]: - reason = "Fix must be a full commit SHA in the current PR" + reason = "Fix must be a current PR commit SHA or its repository commit URL" elif not reason and status == "Deferred": if not tracking_valid(fields.get("tracking", "")): reason = "Tracking must reference an existing, readable, open GitHub issue" diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 2b85a87..95588c8 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -40,6 +40,7 @@ def fixture(body=None, resolved=True, reviewer=BOT): if body: comments.append(comment(body)) return { + "repository": "org/repo", "head": HEAD, "author": "contributor", "state": "open", @@ -105,16 +106,51 @@ def test_outdated_findings_still_block(self): self.assertFalse(passed(result(data))) def test_accepted_requires_full_sha_still_in_pr(self): - for fix in ("", FIX[:7], "c" * 40, "https://github.com/org/repo/commit/" + FIX): + for fix in ("", FIX[:7], "c" * 40): with self.subTest(fix=fix): self.assertFalse( passed(result(fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {fix}"))) ) def test_force_push_removing_fix_invalidates_acceptance(self): - data = fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {FIX}") - data["commits"] = [HEAD] - self.assertFalse(passed(result(data))) + for fix in (FIX, f"https://github.com/org/repo/commit/{FIX}"): + with self.subTest(fix=fix): + data = fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {fix}") + data["commits"] = [HEAD] + self.assertFalse(passed(result(data))) + + def test_commit_links_and_sha_share_pr_membership_validation(self): + for reviewer in (BOT, "human-reviewer"): + for fix in ( + FIX, + f"https://github.com/org/repo/commit/{FIX}", + f"https://github.com/ORG/REPO/commit/{FIX.upper()}", + ): + with self.subTest(reviewer=reviewer, fix=fix): + data = fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {fix}", reviewer=reviewer) + self.assertTrue(passed(result(data))) + self.assertEqual(len(result(data)["findings"]), 1) + + def test_commit_links_require_the_current_repository_and_a_full_sha(self): + for fix in ( + f"http://github.com/org/repo/commit/{FIX}", + f"https://github.com.evil/org/repo/commit/{FIX}", + f"https://user@github.com/org/repo/commit/{FIX}", + f"https://github.com/other/repo/commit/{FIX}", + f"https://github.com/org/other/commit/{FIX}", + f"https://github.com/org/repo/COMMIT/{FIX}", + f"https://github.com/org/repo/pull/128/commits/{FIX}", + "https://github.com/org/repo/issues/42", + f"https://github.com/org/repo/commit/{FIX[:7]}", + f"https://github.com/org/repo/commit/{'g' * 40}", + f"https://github.com/org/repo/commit/{'c' * 40}", + f"https://github.com/org/repo/commit/{FIX}?query=1", + f"https://github.com/org/repo/commit/{FIX}#diff-1", + f"https://github.com/org/repo/commit/{FIX}/extra", + ): + with self.subTest(fix=fix): + data = fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {fix}") + self.assertFalse(passed(result(data))) def test_every_disposition_requires_reason(self): for status in ("Accepted", "Rejected", "Deferred", "Invalid"): @@ -146,11 +182,13 @@ def test_maintainer_can_dispose(self): self.assertTrue(passed(result(data))) def test_latest_explicit_reply_supersedes_old_valid_reply(self): - data = fixture("Disposition: Rejected\nReason: Covered upstream") - data["threads"][0]["comments"].append( - comment("Disposition: Accepted", timestamp="2026-10-09T03:00:00Z") - ) - self.assertFalse(passed(result(data))) + for reviewer in (BOT, "human-reviewer"): + with self.subTest(reviewer=reviewer): + data = fixture("Disposition: Rejected\nReason: Covered upstream", reviewer=reviewer) + data["threads"][0]["comments"].append( + comment("Disposition: Accepted", timestamp="2026-10-09T03:00:00Z") + ) + self.assertFalse(passed(result(data))) def test_edit_timestamp_selects_latest_disposition(self): data = fixture("Disposition: Accepted") @@ -275,22 +313,36 @@ def test_configured_user_bot_takes_priority_over_pr_author_exclusion(self): data["threads"][0]["comments"][-1]["author"]["login"] = "infiscale-bot" self.assertFalse(passed(result(data, bots={"infiscale-bot"}))) - def test_human_review_changes_require_a_fresh_disposition(self): - for follow_up in (False, True): - with self.subTest(follow_up=follow_up): + def test_editing_the_human_root_requires_a_fresh_disposition(self): + data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") + comments = data["threads"][0]["comments"] + comments[0]["updatedAt"] = "2026-10-09T03:00:00Z" + evaluation = result(data) + self.assertEqual(evaluation["errors"], []) + self.assertIn("changed", evaluation["findings"][0]["error"]) + comments[1]["updatedAt"] = "2026-10-09T04:00:00Z" + self.assertTrue(passed(result(data))) + + def test_human_follow_up_keeps_the_existing_disposition(self): + for text in ("OK", "Thanks", "Follow-up discussion"): + with self.subTest(text=text): data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") - comments = data["threads"][0]["comments"] - if follow_up: - comments.append( - comment("Follow up", "human-reviewer", "2026-10-09T03:00:00Z") - ) - else: - comments[0]["updatedAt"] = "2026-10-09T03:00:00Z" - evaluation = result(data) - self.assertEqual(evaluation["errors"], []) - self.assertIn("changed", evaluation["findings"][0]["error"]) - comments[1]["updatedAt"] = "2026-10-09T04:00:00Z" + data["threads"][0]["comments"].append( + comment(text, "human-reviewer", "2026-10-09T03:00:00Z") + ) self.assertTrue(passed(result(data))) + data["threads"][0]["isResolved"] = False + self.assertIn("resolve", result(data)["findings"][0]["error"]) + + def test_ai_follow_up_still_requires_a_fresh_disposition(self): + data = fixture("Disposition: Invalid\nReason: Test") + data["threads"][0]["comments"].append( + comment("Follow up", BOT, "2026-10-09T03:00:00Z") + ) + data["reviews"][0]["submittedAt"] = "2026-10-09T03:30:00Z" + evaluation = result(data) + self.assertEqual(evaluation["errors"], []) + self.assertIn("changed", evaluation["findings"][0]["error"]) def test_human_reviews_do_not_require_completion_markers(self): data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") @@ -445,6 +497,27 @@ def test_snapshot_rejects_head_change_during_read(self): ): snapshot(api, "org/repo", 128) + def test_snapshot_retains_repository_for_commit_link_validation(self): + pr = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} + api = GitHub("test-token") + with ( + patch.object(api, "request", return_value=pr), + patch.object(api, "connection", return_value=[]), + ): + self.assertEqual(snapshot(api, "org/repo", 128)["repository"], "org/repo") + + def test_commit_link_does_not_add_api_requests(self): + for reviewer in (BOT, "human-reviewer"): + with self.subTest(reviewer=reviewer): + data = fixture( + f"Disposition: Accepted\nReason: Fixed\nFix: https://github.com/org/repo/commit/{FIX}", + reviewer=reviewer, + ) + calls, ok = self.run_check([data, copy.deepcopy(data)]) + self.assertTrue(ok) + self.assertEqual(len(calls), 3) + self.assertEqual(calls[-1].args[2]["conclusion"], "success") + def test_check_is_written_to_pr_head_not_event_sha(self): data = fixture("Disposition: Invalid\nReason: False positive") calls, ok = self.run_check([data, copy.deepcopy(data)]) From 1ba64be167b70f3b7ad2383a3b5c0cddf647b316 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:23:05 +0800 Subject: [PATCH 08/21] fix[ci]: accept PR-level bot reviews and completion comments Problem: - Requiring a current-head review marker blocks bots that review once per PR. Solution: - Accept submitted reviews or exact successful Codex/infiscale completion comments. - Keep disposition evidence, reply permissions and conversation resolution checks. Test: - 71 unit tests, Ruff checks and 48 real Codex comment replays pass. JIRA: PDIST-770 --- docs/AI_REVIEW_DISPOSITION.md | 34 ++-- scripts/check_ai_review_disposition.py | 53 +++--- scripts/tests/test_ai_review_disposition.py | 175 ++++++++++++++++---- 3 files changed, 185 insertions(+), 77 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 82db612..eafb2ac 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -9,14 +9,14 @@ ## 合并条件 ```text -每个指定 AI Bot 已完成当前 head SHA 的 review +每个指定 AI Bot 已在该 PR 发布有效 Review 或明确的成功结束评论 AND 每个纳入范围的 AI / 人工行内意见有授权人员的有效 disposition AND 每个 finding 的 conversation 已 Resolve ``` 检查范围为配置的 Bot,以及 PR 作者之外的人工 reviewer 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding,不同问题应分成不同 threads;AI 和人工意见共用以下模板、证据、回复权限和 Resolve 要求。PR 作者自行创建的人工 thread、未配置的 GitHub Bot thread、PR 顶层普通评论和 Review 总评不计为 finding。尚未提交的 pending review 不计入已发布 findings。 -Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。配置的 Bot 优先按 AI 处理,即使其账号类型是 `User`(如 `infiscale-bot`)或恰好是 PR 作者。其他 `User` 按人工账号处理。`AI_REVIEW_BOTS` 中的每个 Bot 都必须完成 review;人工 reviewer 不需要完成标记。空配置是错误,不会当作“无 AI 问题”通过。本次只扩展意见范围,未修改 AI Bot 完成协议。 +Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。配置的 Bot 优先按 AI 处理,即使其账号类型是 `User`(如 `infiscale-bot`)或恰好是 PR 作者。其他 `User` 按人工账号处理。`AI_REVIEW_BOTS` 中的每个 Bot 都必须有审查结果;人工 reviewer 不需要完成标记。空配置是错误,不会当作“无 AI 问题”通过。 回复者必须是 PR 作者或当前拥有仓库 `write` / `maintain` / `admin` 权限的人员。其他人员的回复不生效;GitHub Bot 和已配置的 AI 服务账号不能自行 disposition。仅有组织成员身份不足以授权回复。 @@ -67,25 +67,27 @@ Tracking: https://github.com/IS-Model-Framework/example/issues/42 `Tracking` 只接受 `https://github.com/owner/repo/issues/number` 形式的完整 Issue 链接,不接受其他站点、裸编号、PR 链接、查询参数或锚点。检查器会实际调用 GitHub Issues API;不存在、已关闭、无法读取的 Issue,以及限流、鉴权或服务错误都不会通过。允许引用其他仓库的 Issue,但当前 token 必须能读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 -采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。人工线程只在原始审查意见的编辑时间晚于模板回复时要求重新确认;reviewer 后续追加“好的”“谢谢”或普通讨论不会使已有模板失效。新问题应新开线程或编辑原始意见。AI 线程仍按原有规则处理 AI 的编辑和追加回复,AI 完成协议不变;人工 reviewer 不需要完成标记。修复提交被 force-push 移出 PR 后,Accepted 的 SHA 和链接两种格式都失效。 +采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。人工线程只在原始审查意见的编辑时间晚于模板回复时要求重新确认;reviewer 后续追加“好的”“谢谢”或普通讨论不会使已有模板失效。新问题应新开线程或编辑原始意见。AI 线程仍按 AI 的编辑和追加回复时间要求重新确认;人工 reviewer 不需要完成标记。修复提交被 force-push 移出 PR 后,Accepted 的 SHA 和链接两种格式都失效。 有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 -## AI Bot 完成协议 +## AI Bot 审查结果 -Bot 的 review 流程必须遵守: +每个配置的 Bot 都必须满足以下任一条件: -1. 对固定的 PR head SHA 生成 findings,用 inline threads 发布。 -2. 全部 findings 发布完毕后,提交一个非 pending 的 review,其正文包含独立一行: +1. 该账号发布了有效 Review:状态为 `COMMENTED`、`APPROVED` 或 `CHANGES_REQUESTED`。允许正文为空;`PENDING` 和 `DISMISSED` 不算有效结果。 +2. 该账号发布了可识别的成功结束评论。当前支持以下两种固定格式,普通评论和开始、失败、配额不足提示均不算完成: - ```text - AI-Review-Complete: <当前 PR 的完整 head SHA> - ``` + | Bot login | 成功结束评论 | + | --- | --- | + | `infiscale-bot` | 去除首尾空白后,全文为 `未发现本次 PR 引入的新问题。LGTM!` | + | `chatgpt-codex-connector[bot]` | Codex 自带摘要,以 `` 开头,且 `Code Review` 行状态为 `✅ **Completed**` | -3. review 本身的 `commit.oid` 也必须等于该 SHA。没有 findings 时仍需要这个 review;这样“零问题”和“尚未开始 review”不会混淆。 -4. 当前 head 改变后,重新 review 并提交新完成标记。后续提交的新 review 未含标记、review 被 dismissed,或者 Bot 在完成标记之后继续增加/编辑 finding,均阻断通过。 +`infiscale-bot` 的 `收到,开始 review` 不算完成。有意见时,以它发布的正式 Review 为结果;无意见时,以约定的 LGTM 评论为结果。此规则依赖 Bot 在全部意见发布完毕时才提交 Review 或成功结束评论,不能在开始阶段提前提交正式 Review。Codex 的 `Security Review` 完成不能代替 `Code Review` 完成。仅看评论正文不够,发布账号也必须匹配;人工引用、其他 Bot 和行内回复中的相同文字都不会被当作完成证据。 -这是本工具的集成协议,不是 GitHub 自带的字段。现有 Bot 若不能提供该标记,需要修改其发布流程;不能仅凭 “没有 unresolved threads” 推断 review 已完成。不要在 findings 尚未全部发布时写入完成标记。 +以 PallasKernels 为例,将 `AI_REVIEW_BOTS` 设置为 `chatgpt-codex-connector[bot],infiscale-bot`,两者都必须有结果。其他配置的 Bot 可以使用正式 Review 路径;新增成功评论格式需要明确约定。 + +审查结果按 PR 判断,不绑定当前 head SHA,也不要求自定义 `AI-Review-Complete` 标记。后续 push 不要求 Bot 重审;后续开始评论或 pending review 不会抹去已发布的有效结果。已有的有效 Review 全部被 dismissed,且没有成功结束评论时,会重新阻断。新增行内意见仍须回复和 Resolve,AI 意见变更仍须更新 disposition,但不要求再补交一次完成标记。检查器仍将 Check 写到当前 head,并在通过前重读数据,防止读取期间的提交、意见或完成评论变化。 ## Actions 接入 @@ -136,13 +138,13 @@ flowchart LR A[PR / Review / Comment / Thread webhook] --> B[验证签名并按 PR 串行排队] B --> C[将当前 head 的固定 Check 标记 in_progress] C --> D[分页读取实时 reviews / threads / comments / commits] - D --> E{完成协议 + disposition + resolved} + D --> E{AI 审查结果 + disposition + resolved} E -->|满足| F[success] E -->|未满足或 API 失败| G[failure] F --> H[Human Review 与 Required Approval] ``` -App 应订阅 `pull_request`、`pull_request_review`、`pull_request_review_comment`、`pull_request_review_thread` 的相关 actions,并支持 Check rerequest;用 webhook signature 与 delivery ID 校验/去重,每个 PR 串行更新同一个 head 的 Check,变化时立即撤销旧 success。重试失败保持阻断,并以定期 reconciliation 恢复漏发/丢失事件。 +App 应订阅 `pull_request`、`pull_request_review`、`pull_request_review_comment`、`pull_request_review_thread`、`issue_comment` 的相关 actions,并支持 Check rerequest;用 webhook signature 与 delivery ID 校验/去重,每个 PR 串行更新同一个 head 的 Check,变化时立即撤销旧 success。重试失败保持阻断,并以定期 reconciliation 恢复漏发/丢失事件。 权限为 Pull requests read、Contents read、Issues read、Checks write;安装 token 只覆盖获授权仓库。若调用跨仓库 Issue,需要相应仓库访问权限。当前提交未包含 App 的 webhook 服务、部署或持久化账本。 @@ -156,7 +158,7 @@ GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和 python -m unittest discover -s scripts/tests -v ``` -测试覆盖 AI / 人工行内意见的处理状态、回复权限、范围排除、意见变化后的重新确认、AI 完成协议、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过、HTTP JSON 读写和跟踪 Issue 的真实存在性校验路径。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot / Human Review → 回复 → Resolve → 复查 → Required Check 试运行。 +测试覆盖 AI / 人工行内意见的处理状态、回复权限、范围排除、意见变化后的重新确认、AI Review / 成功结束评论识别、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings 或完成评论变化,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过、HTTP JSON 读写和跟踪 Issue 的真实存在性校验路径。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot / Human Review → 回复 → Resolve → 复查 → Required Check 试运行。 - [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) - [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index d0e5bb2..869c99b 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -109,8 +109,9 @@ def snapshot(api, repository, number): repository, number, "reviews", - f"id body state submittedAt {AUTHOR_FIELDS} commit {{ oid }}", + f"id state {AUTHOR_FIELDS}", ) + comments = api.connection(repository, number, "comments", f"id body {AUTHOR_FIELDS}") threads = api.connection( repository, number, @@ -130,6 +131,7 @@ def snapshot(api, repository, number): "author": pr["user"]["login"].lower(), "state": current["state"], "reviews": reviews, + "comments": comments, "threads": threads, "commits": [node["commit"]["oid"] for node in commits], } @@ -164,24 +166,33 @@ def evaluate(data, bots, authorized, tracking_valid): """Pure policy; API-dependent identity and tracking checks are supplied by caller.""" errors = [] findings = [] - completed_at = {} for bot in sorted(bots): - reviews = [ - review + reviewed = any( + actor_login(review.get("author")) == bot + and review["state"] in {"COMMENTED", "APPROVED", "CHANGES_REQUESTED"} for review in data["reviews"] - if actor_login(review.get("author")) == bot and review["state"] != "PENDING" - ] - latest = max(reversed(reviews), key=lambda r: r["submittedAt"] or "", default=None) - marker = f"AI-Review-Complete: {data['head']}" - if ( - not latest - or latest["state"] == "DISMISSED" - or (latest.get("commit") or {}).get("oid") != data["head"] - or marker not in [line.strip() for line in latest["body"].splitlines()] - ): - errors.append(f"{bot}: missing completed review for current head") - else: - completed_at[bot] = latest["submittedAt"] + ) + completed = any( + actor_login(comment.get("author")) == bot + and ( + ( + bot == "infiscale-bot" + and comment["body"].strip() == "未发现本次 PR 引入的新问题。LGTM!" # noqa: RUF001 + ) + or ( + bot == "chatgpt-codex-connector[bot]" + and comment["body"].startswith("\n") + and re.search( + r"(?m)^\| 📝 \*\*Code Review\*\* \| ✅ \*\*Completed\*\*" + r"(?: )? \|", + comment["body"], + ) + ) + ) + for comment in data["comments"] + ) + if not reviewed and not completed: + errors.append(f"{bot}: missing published review or successful completion comment") for thread in data["threads"]: comments = [ @@ -198,14 +209,6 @@ def evaluate(data, bots, authorized, tracking_valid): or reviewer == data["author"] ): continue - for bot in bots: - if bot in completed_at and any( - actor_login(c.get("author")) == bot and c["updatedAt"] > completed_at[bot] - for c in comments - ): - error = f"{bot}: findings changed after review completion" - if error not in errors: - errors.append(error) reviewer_activity = root["updatedAt"] if reviewer in bots: reviewer_activity = max( diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 95588c8..19373d4 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -21,6 +21,17 @@ HEAD = "a" * 40 FIX = "b" * 40 BOT = "reviewer[bot]" +CODEX = "chatgpt-codex-connector[bot]" +CODEX_SUMMARY = ( + "\n\n## Codex Review Summary\n\n" + "| Review | Status | Commit | Review trigger |\n" + "| --- | --- | --- | --- |\n" + "| 📝 **Code Review** | ✅ **Completed** " + '' + "2026-10-14T09:05:35Z | `7a7a473` | PR opened |" +) +INFISCALE_COMPLETE = "未发现本次 PR 引入的新问题。LGTM!" # noqa: RUF001 +INFISCALE_START = "收到,开始 review" # noqa: RUF001 def comment(body, login="contributor", timestamp="2026-10-09T02:00:00Z"): @@ -48,13 +59,14 @@ def fixture(body=None, resolved=True, reviewer=BOT): "reviews": [ { "id": "review-1", - "body": f"AI-Review-Complete: {HEAD}", + "body": "", "state": "COMMENTED", "submittedAt": "2026-10-09T01:30:00Z", "author": {"login": BOT}, "commit": {"oid": HEAD}, } ], + "comments": [], "threads": [ { "id": "thread-1", @@ -127,7 +139,9 @@ def test_commit_links_and_sha_share_pr_membership_validation(self): f"https://github.com/ORG/REPO/commit/{FIX.upper()}", ): with self.subTest(reviewer=reviewer, fix=fix): - data = fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {fix}", reviewer=reviewer) + data = fixture( + f"Disposition: Accepted\nReason: Fixed\nFix: {fix}", reviewer=reviewer + ) self.assertTrue(passed(result(data))) self.assertEqual(len(result(data)["findings"]), 1) @@ -184,7 +198,9 @@ def test_maintainer_can_dispose(self): def test_latest_explicit_reply_supersedes_old_valid_reply(self): for reviewer in (BOT, "human-reviewer"): with self.subTest(reviewer=reviewer): - data = fixture("Disposition: Rejected\nReason: Covered upstream", reviewer=reviewer) + data = fixture( + "Disposition: Rejected\nReason: Covered upstream", reviewer=reviewer + ) data["threads"][0]["comments"].append( comment("Disposition: Accepted", timestamp="2026-10-09T03:00:00Z") ) @@ -205,28 +221,29 @@ def test_ai_edit_invalidates_older_reply(self): data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T03:00:00Z" self.assertIn("changed", result(data)["findings"][0]["error"]) - def test_missing_old_dismissed_or_incomplete_review_blocks(self): - for mode in ("missing", "old", "dismissed", "incomplete", "pending"): - with self.subTest(mode=mode): + def test_missing_pending_or_dismissed_review_blocks(self): + for state in (None, "DISMISSED", "PENDING"): + with self.subTest(state=state): data = fixture("Disposition: Invalid\nReason: False positive") - if mode == "missing": + if state is None: data["reviews"] = [] - elif mode == "old": - data["reviews"][0]["commit"]["oid"] = FIX - elif mode == "dismissed": - data["reviews"][0]["state"] = "DISMISSED" - elif mode == "pending": - data["reviews"][0]["state"] = "PENDING" else: - data["reviews"][0]["body"] = "No problems" + data["reviews"][0]["state"] = state self.assertFalse(passed(result(data))) - def test_later_unfinished_review_supersedes_completion(self): + def test_published_review_needs_neither_current_head_nor_custom_marker(self): + for state in ("COMMENTED", "APPROVED", "CHANGES_REQUESTED"): + with self.subTest(state=state): + data = fixture("Disposition: Invalid\nReason: False positive") + data["reviews"][0].update(state=state, body="", commit={"oid": FIX}) + self.assertTrue(passed(result(data))) + + def test_later_pending_review_does_not_erase_a_published_review(self): data = fixture("Disposition: Invalid\nReason: False positive") review = copy.deepcopy(data["reviews"][0]) - review.update(id="review-2", body="Working", submittedAt="2026-10-09T03:00:00Z") + review.update(id="review-2", state="PENDING", submittedAt=None) data["reviews"].append(review) - self.assertFalse(passed(result(data))) + self.assertTrue(passed(result(data))) def test_zero_findings_pass_only_after_review_completion(self): data = fixture() @@ -239,6 +256,68 @@ def test_every_configured_bot_must_complete_review(self): data = fixture("Disposition: Invalid\nReason: False positive") self.assertFalse(passed(result(data, bots={BOT, "another[bot]"}))) + def test_both_bots_can_complete_without_findings(self): + data = fixture() + data.update(reviews=[], threads=[]) + bots = {CODEX, "infiscale-bot"} + data["comments"] = [comment(CODEX_SUMMARY, CODEX)] + self.assertFalse(passed(result(data, bots=bots))) + data["comments"].append(comment(INFISCALE_COMPLETE, "infiscale-bot")) + evaluation = result(data, bots=bots) + self.assertTrue(passed(evaluation)) + self.assertEqual(evaluation["findings"], []) + data["threads"] = fixture(reviewer="human-reviewer")["threads"] + self.assertFalse(passed(result(data, bots=bots))) + + def test_completion_comments_require_the_exact_bot_and_success_format(self): + cases = ( + (CODEX, CODEX_SUMMARY, True), + (CODEX, CODEX_SUMMARY.replace("✅ **Completed**", "⚠️ **Failed**"), False), + (CODEX, CODEX_SUMMARY.replace("✅ **Completed**", "⏳ **In progress**"), False), + (CODEX, CODEX_SUMMARY.replace("**Code Review**", "**Security Review**"), False), + ( + CODEX, + CODEX_SUMMARY.replace("", ""), + False, + ), + (CODEX, "Codex usage limits have been reached for code reviews.", False), + (CODEX, "Completed", False), + (CODEX, INFISCALE_COMPLETE, False), + ("infiscale-bot", INFISCALE_COMPLETE, True), + ("infiscale-bot", "\n" + INFISCALE_COMPLETE + "\n", True), + ("infiscale-bot", INFISCALE_START, False), + ("infiscale-bot", "review failed", False), + ("infiscale-bot", "LGTM!", False), + ("infiscale-bot", CODEX_SUMMARY, False), + ) + for bot, body, expected in cases: + for author in (bot, "contributor", "other-bot"): + with self.subTest(bot=bot, body=body, author=author): + data = fixture() + data.update(reviews=[], threads=[], comments=[comment(body, author)]) + self.assertEqual(passed(result(data, bots={bot})), expected and author == bot) + + def test_quoted_completion_text_does_not_count(self): + for bot, body in ((CODEX, CODEX_SUMMARY), ("infiscale-bot", INFISCALE_COMPLETE)): + for quoted in ("> " + body, "```\n" + body + "\n```", "Example:\n" + body): + with self.subTest(bot=bot, body=quoted): + data = fixture() + data.update(reviews=[], threads=[], comments=[comment(quoted, bot)]) + self.assertFalse(passed(result(data, bots={bot}))) + + def test_infiscale_start_comment_does_not_replace_a_published_review(self): + data = fixture("Disposition: Invalid\nReason: Test", reviewer="infiscale-bot") + data["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} + data["comments"] = [comment(INFISCALE_START, "infiscale-bot")] + self.assertTrue(passed(result(data, bots={"infiscale-bot"}))) + + def test_codex_completion_accepts_graphql_bot_login_without_suffix(self): + data = fixture() + completed = comment(CODEX_SUMMARY, CODEX) + completed["author"] = {"login": "chatgpt-codex-connector", "__typename": "Bot"} + data.update(reviews=[], threads=[], comments=[completed]) + self.assertTrue(passed(result(data, bots={CODEX}))) + def test_graphql_bot_login_without_suffix_is_canonicalized(self): data = fixture("Disposition: Invalid\nReason: False positive") for author in ( @@ -253,12 +332,12 @@ def test_ordinary_user_cannot_impersonate_bot_login(self): data["reviews"][0]["author"] = {"login": "reviewer", "__typename": "User"} self.assertFalse(passed(result(data))) - def test_new_finding_after_completion_requires_new_marker(self): + def test_new_finding_requires_disposition_without_requiring_a_new_review(self): data = fixture("Disposition: Invalid\nReason: False positive") data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T01:45:00Z" - self.assertFalse(passed(result(data))) - data["reviews"][0]["submittedAt"] = "2026-10-09T01:50:00Z" self.assertTrue(passed(result(data))) + data["threads"].append(fixture()["threads"][0]) + self.assertFalse(passed(result(data))) def test_human_findings_require_complete_dispositions(self): for body in ( @@ -279,9 +358,7 @@ def test_human_findings_require_complete_dispositions(self): def test_human_findings_keep_resolve_and_reply_permissions(self): for resolved, login in ((False, "contributor"), (True, "stranger"), (True, BOT)): with self.subTest(resolved=resolved, login=login): - data = fixture( - "Disposition: Invalid\nReason: Test", resolved, "human-reviewer" - ) + data = fixture("Disposition: Invalid\nReason: Test", resolved, "human-reviewer") data["threads"][0]["comments"][-1]["author"]["login"] = login data["threads"][0]["isOutdated"] = True evaluation = result(data) @@ -351,7 +428,7 @@ def test_human_reviews_do_not_require_completion_markers(self): human_review.update(author={"login": "human-reviewer"}, body="General feedback") data["reviews"].append(human_review) self.assertTrue(passed(result(data))) - data["reviews"][0]["body"] = "" + data["reviews"].pop(0) self.assertFalse(passed(result(data))) def test_unaddressed_human_finding_blocks_an_addressed_ai_finding(self): @@ -412,9 +489,7 @@ def respond(request, timeout): return io.BytesIO(json.dumps(responses[len(calls) - 1]).encode()) with patch("scripts.check_ai_review_disposition.urlopen", side_effect=respond): - self.assertEqual( - api.request("GET", "/repos/org/repo/pulls/313"), {"number": 313} - ) + self.assertEqual(api.request("GET", "/repos/org/repo/pulls/313"), {"number": 313}) self.assertEqual( api.graphql("query { viewer { login } }", {}), {"viewer": {"login": "reviewer"}}, @@ -459,10 +534,12 @@ def test_connections_read_more_than_100_nodes(self): }, {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}}, ] - responses = [{"repository": {"pullRequest": {"reviews": p}}} for p in pages] - with patch.object(api, "graphql", side_effect=responses) as graphql: - self.assertEqual(len(api.connection("org/repo", 128, "reviews", "id")), 101) - self.assertEqual(graphql.call_args.args[1]["cursor"], "next") + for field in ("reviews", "comments"): + with self.subTest(field=field): + responses = [{"repository": {"pullRequest": {field: p}}} for p in pages] + with patch.object(api, "graphql", side_effect=responses) as graphql: + self.assertEqual(len(api.connection("org/repo", 128, field, "id")), 101) + self.assertEqual(graphql.call_args.args[1]["cursor"], "next") def test_long_thread_comments_are_paginated(self): api = GitHub("test-token") @@ -506,6 +583,21 @@ def test_snapshot_retains_repository_for_commit_link_validation(self): ): self.assertEqual(snapshot(api, "org/repo", 128)["repository"], "org/repo") + def test_snapshot_reads_top_level_comments_for_completion(self): + pr = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} + api = GitHub("test-token") + completed = comment(INFISCALE_COMPLETE, "infiscale-bot") + with ( + patch.object(api, "request", return_value=pr), + patch.object( + api, "connection", side_effect=[[], [completed], [], []] + ) as connection, + ): + data = snapshot(api, "org/repo", 128) + self.assertEqual(data["comments"], [completed]) + self.assertEqual(connection.call_args_list[1].args[2], "comments") + self.assertNotIn("pullRequestReview", connection.call_args_list[1].args[3]) + def test_commit_link_does_not_add_api_requests(self): for reviewer in (BOT, "human-reviewer"): with self.subTest(reviewer=reviewer): @@ -536,6 +628,15 @@ def test_new_finding_during_read_prevents_success(self): self.assertFalse(ok) self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + def test_completion_comment_changed_during_read_prevents_success(self): + data = fixture("Disposition: Invalid\nReason: Test") + data["comments"] = [comment(INFISCALE_COMPLETE, "infiscale-bot")] + changed = copy.deepcopy(data) + changed["comments"][0]["body"] = INFISCALE_START + calls, ok = self.run_check([data, changed]) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + def test_api_failure_finishes_check_as_failure(self): calls, ok = self.run_check(RuntimeError("failed")) self.assertFalse(ok) @@ -610,7 +711,9 @@ def test_multiple_findings_share_one_issue_lookup(self): data["threads"].append(other) calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) self.assertTrue(ok) - issue_reads = [c for c in calls if c.args[:2] == ("GET", "/repos/org/repo/issues/42")] + issue_reads = [ + c for c in calls if c.args[:2] == ("GET", "/repos/org/repo/issues/42") + ] self.assertEqual(len(issue_reads), 1) def run_check(self, snapshots, issue=None): @@ -638,7 +741,9 @@ def run_main(self, *arguments, passed=True): sys, "argv", ["checker", "--repository", "org/repo", "--bots", BOT, *arguments] ), patch("scripts.check_ai_review_disposition.GitHub") as client, - patch("scripts.check_ai_review_disposition.check_pr", return_value=passed) as check, + patch( + "scripts.check_ai_review_disposition.check_pr", return_value=passed + ) as check, patch("sys.stderr", new_callable=io.StringIO), ): return main(), client, check @@ -647,9 +752,7 @@ def test_checks_only_the_requested_pr(self): code, client, check = self.run_main("--pr-number", "313") self.assertEqual(code, 0) client.assert_called_once_with("test-token") - check.assert_called_once_with( - client.return_value, "org/repo", 313, {BOT} - ) + check.assert_called_once_with(client.return_value, "org/repo", 313, {BOT}) client.return_value.open_prs.assert_not_called() def test_target_pr_failure_sets_exit_code(self): From faa4db5ed975b5d77893154c9e1a2a1983aaa547 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:45:23 +0800 Subject: [PATCH 09/21] refactor: simplify AI review disposition gate --- .../PULL_REQUEST_TEMPLATE/ai-review-reply.md | 4 - .../reusable-ai-review-disposition.yml | 5 - .gitignore | 3 - docs/AI_REVIEW_DISPOSITION.md | 179 ++++----------- docs/examples/ai-review-disposition.yml | 6 - scripts/check_ai_review_disposition.py | 211 +++++++----------- scripts/tests/test_ai_review_disposition.py | 186 +++++++++------ 7 files changed, 248 insertions(+), 346 deletions(-) delete mode 100644 .github/PULL_REQUEST_TEMPLATE/ai-review-reply.md diff --git a/.github/PULL_REQUEST_TEMPLATE/ai-review-reply.md b/.github/PULL_REQUEST_TEMPLATE/ai-review-reply.md deleted file mode 100644 index cc9b700..0000000 --- a/.github/PULL_REQUEST_TEMPLATE/ai-review-reply.md +++ /dev/null @@ -1,4 +0,0 @@ -Disposition: -Reason: <填写处理原因,保持一行> -Fix: N/A -Tracking: N/A diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index a96cf5c..0631389 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -16,10 +16,6 @@ on: required: false type: string default: main - secrets: - shared-read-token: - description: 'Optional read-only token for checkout when shared CI repo is private' - required: false permissions: contents: read @@ -41,7 +37,6 @@ jobs: uses: actions/checkout@v4 with: repository: IS-Model-Framework/.github - token: ${{ secrets.shared-read-token || github.token }} ref: ${{ inputs.shared-ref }} path: .ci-shared persist-credentials: false diff --git a/.gitignore b/.gitignore index d21fd39..b7faf40 100644 --- a/.gitignore +++ b/.gitignore @@ -205,6 +205,3 @@ cython_debug/ marimo/_static/ marimo/_lsp/ __marimo__/ - -*.DS_Store -*.serena diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index eafb2ac..4480bf2 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,166 +1,71 @@ # AI Review / Disposition Check -目标:配置的 AI Bot 和 PR 作者之外的人工 reviewer 提出的行内意见都有可审计的处理记录,并且对话已 Resolve。检查不要求采纳审查建议,也不代替 Human Review。 +合并前检查三件事:每个指定 AI 完成过审查;AI 和人工 reviewer 的每条行内线程都有有效模板回复;这些线程全部 resolved。无需采纳所有意见,检查也不代替人工 approval。 -本仓库提供 [Python 检查器](../scripts/check_ai_review_disposition.py)、[reusable workflow](../.github/workflows/reusable-ai-review-disposition.yml) 和两个项目接入示例。规则单独运行,不并入现有 `CI Result`:代码 CI 与 review 的完成时间不同,回复评论也不应该重新运行测试。 +## 检查规则 -每次只检查明确指定的一个 PR,只更新该 PR 最新提交上的 Check。其他 open PR 不参与本次判定;closed/merged PR 直接跳过。当前 API 客户端仅支持 GitHub.com。 +- 每次明确指定一个 PR;closed/merged PR 跳过。Check 写入该 PR 的最新 head commit。 +- `AI_REVIEW_BOTS` 是必填的逗号分隔 login 列表,每个账号都必须完成审查。按 login 精确匹配,忽略大小写;GraphQL `Bot` login 缺少 `[bot]` 后缀时补齐,普通 `User` 不补。 +- 完成依据是该 Bot 发布的 `COMMENTED`、`APPROVED` 或 `CHANGES_REQUESTED` Review,或下表中的成功结束评论。`PENDING`、`DISMISSED`、开始/失败/配额不足提示不算完成。 +- 完成按整个 PR 判断,不绑定当前 head;后续 push 无需重审。新的 pending review 或开始评论不撤销已有完成结果;所有有效 Review 被 dismissed 且无成功评论时重新阻断。 +- 检查指定 AI 和 PR 作者之外的人工账号创建的全部已发布 inline threads,包括 outdated 和 resolved threads。PR 作者自己的人工线程、未配置 Bot 的线程、PR 顶层评论和 Review 总评不计为待处理线程;pending review 不计入。配置的 AI 即使是 `User` 或 PR 作者,仍按 AI 处理。 +- 模板回复者须为 PR 作者或当前具有仓库写权限的人工账号;Bot 和配置的 AI 服务账号不能自行处理意见。组织成员身份本身不代表写权限。 +- 采用编辑时间最新的明确模板回复,同一时间取 thread 中更后的回复;新的无效模板会替代旧模板,普通讨论不会。AI/人工使用相同规则,后续讨论或原始意见编辑不额外要求重复确认;新问题应新开线程。 +- 每个线程必须同时满足有效回复和 resolved。仅 resolved、仅回复 “done”,或在 PR 总结中统一回答均不能通过。工具不自动回复或 resolve。 -## 合并条件 - -```text -每个指定 AI Bot 已在该 PR 发布有效 Review 或明确的成功结束评论 -AND 每个纳入范围的 AI / 人工行内意见有授权人员的有效 disposition -AND 每个 finding 的 conversation 已 Resolve -``` - -检查范围为配置的 Bot,以及 PR 作者之外的人工 reviewer 创建的所有已发布 inline review threads,包括历史提交上的 outdated threads 和已 Resolve 的 threads。每个 thread 是一条 finding,不同问题应分成不同 threads;AI 和人工意见共用以下模板、证据、回复权限和 Resolve 要求。PR 作者自行创建的人工 thread、未配置的 GitHub Bot thread、PR 顶层普通评论和 Review 总评不计为 finding。尚未提交的 pending review 不计入已发布 findings。 - -Bot 由精确 GitHub login 匹配,例如 `reviewer[bot]`;不根据显示名、正文或模糊子串识别。GraphQL 的 `Bot` 类型若返回不带后缀的 login,会转换成标准 `[bot]` 格式;普通 `User` 不做此转换。配置的 Bot 优先按 AI 处理,即使其账号类型是 `User`(如 `infiscale-bot`)或恰好是 PR 作者。其他 `User` 按人工账号处理。`AI_REVIEW_BOTS` 中的每个 Bot 都必须有审查结果;人工 reviewer 不需要完成标记。空配置是错误,不会当作“无 AI 问题”通过。 - -回复者必须是 PR 作者或当前拥有仓库 `write` / `maintain` / `admin` 权限的人员。其他人员的回复不生效;GitHub Bot 和已配置的 AI 服务账号不能自行 disposition。仅有组织成员身份不足以授权回复。 - -| Disposition | 必须提供的字段 | 检查的证据 | -| --- | --- | --- | -| Accepted | `Reason`、`Fix` | 完整的 40 位 commit SHA,或当前仓库的标准 commit 链接;提交必须仍在当前 PR 的 commits 中 | -| Rejected | `Reason` | 非空拒绝理由 | -| Invalid | `Reason` | 非空误报理由 | -| Deferred | `Reason`、`Tracking` | GitHub API 确认存在、当前 token 可读且仍开放的 Issue,不能是 PR | - -`Fix` 证明提交引用有效;工具不判断该提交是否真正修复问题。理由的充分性、跟踪 Issue 是否确实覆盖此条意见,以及 deferral 的业务可接受性由 Human Review 审查。当前版本不支持无 tracking 的口头豁免;若未来接入审批,应验证审批人的身份及审批记录,而不是接受 Contributor 自填 `Approved: yes`。 +| Bot login | 可替代正式 Review 的成功结束评论 | +| --- | --- | +| `infiscale-bot` | 去除首尾空白后全文为 `未发现本次 PR 引入的新问题。LGTM!` | +| `chatgpt-codex-connector[bot]` | 自带摘要以 `` 开头,且 `Code Review` 行状态为 `✅ **Completed**` | -## Contributor 回复格式 +仅匹配相应 Bot 发布的 PR 顶层评论;人工引用、行内回复、Security Review 完成均不能作为完成依据。Bot 须在全部意见发布完毕后才提交正式 Review 或成功结束评论。 -直接在对应 inline thread 中回复。第一行必须是 `Disposition: ...`,每个字段单独一行;允许空行和字段名/状态大小写变化。不要加引号、Markdown 引用、代码块或额外字段。`Reason` 保持一行,可以用中文。 +## 回复模板 -Accepted: +直接在对应 inline thread 中发送普通文本。第一行必须为 `Disposition: ...`;每个字段一行,允许空行及字段名/状态大小写变化,不接受引用、代码块、重复字段或额外字段。 ```text Disposition: Accepted -Reason: 已补充空数组边界判断,并增加回归测试。 +Reason: 已修复边界判断。 Fix: https://github.com/IS-Model-Framework/example/commit/0123456789abcdef0123456789abcdef01234567 +Tracking: N/A ``` -`Fix` 兼容直接填写完整 40 位 SHA。链接仅支持 `https://github.com/owner/repo/commit/<完整40位SHA>`,仓库必须与当前 PR 所在仓库一致;不接受短 SHA、其他站点或仓库、PR 链接、查询参数和锚点。链接提取 SHA 后复用现有 PR 提交列表校验,不增加 API 请求。实际回复作为普通文本发送,不要包在代码块里,commit 链接即可点击跳转;延期 Issue 链接仍填写在 `Tracking` 字段中。 - -Rejected: - -```text -Disposition: Rejected -Reason: 调用入口已验证该条件,此处不会收到负数输入。 -``` - -Invalid: - -```text -Disposition: Invalid -Reason: 此实现使用异步执行,评论所述的同步调用路径不存在。 -``` - -Deferred: - -```text -Disposition: Deferred -Reason: 本次先完成兼容修复,性能优化在后续版本处理。 -Tracking: https://github.com/IS-Model-Framework/example/issues/42 -``` - -`Tracking` 只接受 `https://github.com/owner/repo/issues/number` 形式的完整 Issue 链接,不接受其他站点、裸编号、PR 链接、查询参数或锚点。检查器会实际调用 GitHub Issues API;不存在、已关闭、无法读取的 Issue,以及限流、鉴权或服务错误都不会通过。允许引用其他仓库的 Issue,但当前 token 必须能读取;其他仓库的私有 Issue 可能需要 GitHub App installation token。 - -采用最新编辑时间的明确 disposition 回复;同一时间取 thread 中更后的回复。新的不完整 disposition 会替代旧的有效回复,避免沿用过期决定。普通交流回复不会替代 disposition。人工线程只在原始审查意见的编辑时间晚于模板回复时要求重新确认;reviewer 后续追加“好的”“谢谢”或普通讨论不会使已有模板失效。新问题应新开线程或编辑原始意见。AI 线程仍按 AI 的编辑和追加回复时间要求重新确认;人工 reviewer 不需要完成标记。修复提交被 force-push 移出 PR 后,Accepted 的 SHA 和链接两种格式都失效。 - -有效回复之后,由 Contributor / Maintainer Resolve Conversation;工具不会自动 Resolve。只 Resolve、只写 “done / 已修复”、在 PR 总结里统一回答,都不能通过。 - -## AI Bot 审查结果 - -每个配置的 Bot 都必须满足以下任一条件: - -1. 该账号发布了有效 Review:状态为 `COMMENTED`、`APPROVED` 或 `CHANGES_REQUESTED`。允许正文为空;`PENDING` 和 `DISMISSED` 不算有效结果。 -2. 该账号发布了可识别的成功结束评论。当前支持以下两种固定格式,普通评论和开始、失败、配额不足提示均不算完成: - - | Bot login | 成功结束评论 | - | --- | --- | - | `infiscale-bot` | 去除首尾空白后,全文为 `未发现本次 PR 引入的新问题。LGTM!` | - | `chatgpt-codex-connector[bot]` | Codex 自带摘要,以 `` 开头,且 `Code Review` 行状态为 `✅ **Completed**` | - -`infiscale-bot` 的 `收到,开始 review` 不算完成。有意见时,以它发布的正式 Review 为结果;无意见时,以约定的 LGTM 评论为结果。此规则依赖 Bot 在全部意见发布完毕时才提交 Review 或成功结束评论,不能在开始阶段提前提交正式 Review。Codex 的 `Security Review` 完成不能代替 `Code Review` 完成。仅看评论正文不够,发布账号也必须匹配;人工引用、其他 Bot 和行内回复中的相同文字都不会被当作完成证据。 - -以 PallasKernels 为例,将 `AI_REVIEW_BOTS` 设置为 `chatgpt-codex-connector[bot],infiscale-bot`,两者都必须有结果。其他配置的 Bot 可以使用正式 Review 路径;新增成功评论格式需要明确约定。 - -审查结果按 PR 判断,不绑定当前 head SHA,也不要求自定义 `AI-Review-Complete` 标记。后续 push 不要求 Bot 重审;后续开始评论或 pending review 不会抹去已发布的有效结果。已有的有效 Review 全部被 dismissed,且没有成功结束评论时,会重新阻断。新增行内意见仍须回复和 Resolve,AI 意见变更仍须更新 disposition,但不要求再补交一次完成标记。检查器仍将 Check 写到当前 head,并在通过前重读数据,防止读取期间的提交、意见或完成评论变化。 - -## Actions 接入 - -`.github` 仓库的 workflow 不会自动在所有组织项目执行。每个目标项目需要 caller workflow,并由组织 ruleset 覆盖目标仓库。 - -1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 与 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 配套复制到目标项目 `.github/workflows/`,合入默认分支。collector 的 `run-name` 必须保持为 PR 编号,供后续 `workflow_run` 定位目标;不要改成 PR 标题。迁移期间旧 collector 的历史运行不符合新格式,可通过手动指定 PR 复查。 -2. 在组织/仓库 Variables 设置 `AI_REVIEW_BOTS` 为准确的 login 列表,逗号分隔。示例中的 Bot 名称不是实际默认配置。 -3. 生产环境将 caller 的 `uses: ...@main` 与 `shared-ref: main` 同时固定到本仓库同一个已审核 commit SHA。共享脚本从可信 CI 仓库加载,完全不 checkout PR 代码。 -4. 为 `GITHUB_TOKEN` 提供 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。如果组织 CI 仓库是 private,还需要开启 reusable workflow 的组织访问,并通过可选 secret `shared-read-token` 提供 CI 仓库的只读 checkout token;caller 的 `GITHUB_TOKEN` 不会自动获得其他 private 仓库的读取权限。 -5. 完成一次运行后,将 **`AI Review / Disposition Check`** 加入 ruleset 的 Required Status Checks,检查来源选择 GitHub Actions。保持现有 Human Review / approval 规则。 - -选择的是脚本通过 Checks API 发布到 PR **head commit** 上的 Check,不是 `Evaluate AI Review Dispositions` 这个 Actions job。`pull_request_target`、`issue_comment`、`workflow_run` 的 `GITHUB_SHA` 不一定是 PR head;直接使用 job success 作合并门禁会关联到错误提交。 - -| 事件 | 示例中的路径 | +| Disposition | 必填证据(所有状态都须有一行非空 `Reason`) | | --- | --- | -| PR opened / reopened / synchronize / ready_for_review | 从 `pull_request.number` 取得编号,只检查该 PR | -| Review submitted / edited / dismissed | 无权限的 collector 把 PR 编号写入 `run-name` → 默认分支 `workflow_run.display_title` → 检查该 PR | -| Inline comment created / edited / deleted | 同上 | -| PR 顶层评论 created / edited / deleted | `issue_comment` 触发复查,可用一条 “AI review recheck” 评论重新计算 | -| Resolve / Unresolve | Actions 不直接支持此事件;手动复查、顶层评论,或 App webhook → `repository_dispatch` | -| Bot 用 `GITHUB_TOKEN` 发布 review/comments | 通常不会触发后续 Actions;review workflow 结束后显式复查,或改用 App token 发布 | -| Actions 手动运行 | 必填 `pr-number`,只检查指定 PR | -| `repository_dispatch: ai-review-state-changed` | 在 `client_payload.pr_number` 中传入目标 PR 的正整数编号 | - -collector 不检出或执行 PR 内容、不上传 artifact。caller 对 `workflow_run.display_title` 使用 `fromJSON` 取得数字编号,因此 fork 的 `workflow_run.pull_requests` 为空也能定位。这个编号只用作路由提示,不接受 collector 提供的审查结论或脚本;有写权限的检查器始终从可信共享仓库加载,重新读取目标仓库中该 PR 的实时 API 数据。 +| Accepted | `Fix` 为完整 40 位 SHA,或当前仓库的标准 commit 链接;提交必须仍在当前 PR 的 commits 中 | +| Rejected | 拒绝理由 | +| Invalid | 误报理由 | +| Deferred | `Tracking` 为 GitHub Issue 完整链接;API 确认该 Issue 存在、当前 token 可读、仍开放且不是 PR | -调用方和 CLI 都要求显式传入正整数 PR 编号;缺失、0、负数或非法值报错,不回退到全仓库扫描。权限检查与 disposition 规则保持不变。 +不适用的 `Fix` / `Tracking` 可省略或填 `N/A`。commit 链接仅接受 `https://github.com/owner/repo/commit/<40位SHA>`,Issue 链接仅接受 `https://github.com/owner/repo/issues/<正整数>`,均不接受查询参数或锚点。force-push 移除修复提交后,Accepted 失效。Issue 可跨仓库,但当前 token 必须能读取;目标仓库的 `GITHUB_TOKEN` 无法读取其他私有仓库时需改用具有对应访问权限的调用方式。 -并发组包含仓库名和 PR 编号,`cancel-in-progress: false`。同一 PR 的检查串行运行,待执行事件即使被后来的事件替换,也会重新读取同一 PR 的实时状态;不同 PR 不共用队列。通过之前再完整读取一次 review 数据,发现提交或评论变化就失败。检查过程内的 API 错误会尝试写 failure;创建/更新 Check 请求本身失败、超时或取消可能留下 in-progress Check,仍然阻止合并。 +工具验证引用有效,不判断理由是否充分、提交是否真正修复问题或延期是否合理;这些由人工审查确认。 -手动复查可在 Actions 页面运行 `AI Review Disposition` 并填写 `pr-number`。CLI 示例: +## CI 接入 -```bash -GH_TOKEN="" python scripts/check_ai_review_disposition.py \ - --repository IS-Model-Framework/example \ - --pr-number 128 \ - --bots 'reviewer[bot]' -``` +本组织有共享 Python CI 和独立 CI;本检查通过独立 caller 接入,保持现有测试及 `CI Result` 不变。组织 `.github` 仓库的 workflow 不会自动在其他仓库运行。 -这条命令会通过 Checks API 写入指定 PR 的 Check,不是 dry-run。Token 通过环境变量提供;不应提交到仓库。`--pr-number` 必填且必须大于 0。退出码:0 目标 PR 通过或已关闭而跳过,1 目标 PR 不通过(包括检查过程中捕获的 API 错误),2 参数错误或未捕获的执行错误。 +1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 和 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 复制到目标仓库 `.github/workflows/` 并合入默认分支。 +2. 设置组织/仓库 Variable `AI_REVIEW_BOTS`,如 `chatgpt-codex-connector[bot],infiscale-bot`。空值会报错,不提供隐式默认 Bot。 +3. 生产接入时,将 caller 中 `uses: ...@main` 和 `shared-ref: main` 同时固定到本公共 CI 仓库的同一个已审核 commit SHA。 +4. caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`;不执行或检出 PR 代码。 +5. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。保留人工 approval 与 conversation resolution 规则。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 -## 严格组织门禁:GitHub App +PR opened/reopened/synchronize/ready_for_review 和 PR 顶层评论变化直接触发检查。Review/行内评论变化先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器,因此 fork PR 也可复查。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。 -Actions 方案适合初期接入,但不保证评论变化后瞬间撤销 success:事件排队、运行延迟、Resolve/Unresolve 缺少原生 trigger,都会留下状态更新窗口。需要严格覆盖 thread 状态变化时,建议组织安装专用 GitHub App,用同一个检查器作为执行核心: +Resolve/Unresolve 没有原生 Actions trigger:resolve 后,在 PR 顶层发一条评论或通过 Actions 手动运行 `AI Review Disposition`,填写 `pr-number`。使用 `GITHUB_TOKEN` 发布的 Review/评论通常不会触发后续 Actions,应由审查流程显式触发复查,或用 App token 发布。 -```mermaid -flowchart LR - A[PR / Review / Comment / Thread webhook] --> B[验证签名并按 PR 串行排队] - B --> C[将当前 head 的固定 Check 标记 in_progress] - C --> D[分页读取实时 reviews / threads / comments / commits] - D --> E{AI 审查结果 + disposition + resolved} - E -->|满足| F[success] - E -->|未满足或 API 失败| G[failure] - F --> H[Human Review 与 Required Approval] -``` +同一 PR 串行检查,不取消正在执行的检查;不同 PR 独立。通过前再完整读取一次数据,提交或评论变化则阻断。API 错误不放行;取消、超时或 Check 写入失败可能留下 in-progress 状态,需重跑。该方案是异步门禁,不提供不可删改的历史审计或 merge queue 合成 SHA 支持。 -App 应订阅 `pull_request`、`pull_request_review`、`pull_request_review_comment`、`pull_request_review_thread`、`issue_comment` 的相关 actions,并支持 Check rerequest;用 webhook signature 与 delivery ID 校验/去重,每个 PR 串行更新同一个 head 的 Check,变化时立即撤销旧 success。重试失败保持阻断,并以定期 reconciliation 恢复漏发/丢失事件。 - -权限为 Pull requests read、Contents read、Issues read、Checks write;安装 token 只覆盖获授权仓库。若调用跨仓库 Issue,需要相应仓库访问权限。当前提交未包含 App 的 webhook 服务、部署或持久化账本。 - -GitHub 的 Status Check 仍是异步状态,无法把“读所有评论”和“执行 merge”做成一个原子事务。高要求场景还应启用分支保护的 conversation resolution,并通过受控 merge 入口在合并前再次核验。AI findings 被删除后,实时 API 不再保留它们;若要求删除也必须留痕,App 需要持久化 finding ID 与 disposition 历史。此版本不会把 API 数据当作不可删改的审计账本。 - -该 Check 以 PR head 为对象;当前不支持 merge queue 生成的合成 SHA。使用 merge queue 的项目需要另外设计 `merge_group` 的成员 PR 核验,不能直接沿用此 caller 作为队列 required check。 - -## 验证与参考 +CLI(会写入指定 PR 的 Check): ```bash -python -m unittest discover -s scripts/tests -v +GH_TOKEN="" python scripts/check_ai_review_disposition.py \ + --repository IS-Model-Framework/example --pr-number 128 \ + --bots 'chatgpt-codex-connector[bot],infiscale-bot' ``` -测试覆盖 AI / 人工行内意见的处理状态、回复权限、范围排除、意见变化后的重新确认、AI Review / 成功结束评论识别、outdated/resolved threads、force-push、分页、API 错误与读取期间新增 findings 或完成评论变化,以及单 PR CLI、拒绝缺失/非法编号、closed PR 跳过、HTTP JSON 读写和跟踪 Issue 的真实存在性校验路径。API 通过 mock 验证;仍需在目标仓库做一次真实的 Bot / Human Review → 回复 → Resolve → 复查 → Required Check 试运行。 +仅支持 GitHub.com。退出码:0 通过或 closed PR 跳过,1 未通过,2 参数错误或未捕获的执行错误。验证:`python -m unittest discover -s scripts/tests -v`;正式启用 required check 前,应在目标仓库试运行 Bot 完成 → 模板回复 → resolve → 复查流程。 -- [GitHub Actions 事件与 fork / workflow_run 行为](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) -- [Webhook 事件:pull_request_review_thread](https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review_thread) -- [Checks API:发布并更新 Check Runs](https://docs.github.com/en/rest/checks/runs) -- [Reusable workflows 的组织接入与权限](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) +参考:[Actions 事件](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)、[Checks API](https://docs.github.com/en/rest/checks/runs)、[复用 workflow](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows)。 diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index c1ba6a9..f53a3b5 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -10,8 +10,6 @@ on: types: [completed] issue_comment: types: [created, edited, deleted] - repository_dispatch: - types: [ai-review-state-changed] workflow_dispatch: inputs: pr-number: @@ -35,11 +33,7 @@ jobs: ${{ github.event.pull_request.number || github.event.issue.number || inputs.pr-number - || github.event.client_payload.pr_number || fromJSON(github.event.workflow_run.display_title || '0') }} # Set this repository/organization variable to exact bot logins. bot-logins: ${{ vars.AI_REVIEW_BOTS }} shared-ref: main - # If the shared CI repository is private: - # secrets: - # shared-read-token: ${{ secrets.CI_READ_TOKEN }} diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 869c99b..aa380fb 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -6,7 +6,7 @@ import os import re import sys -from collections import Counter +from functools import cache from urllib.error import HTTPError from urllib.parse import quote from urllib.request import Request, urlopen @@ -15,7 +15,7 @@ STATUSES = ("Accepted", "Rejected", "Deferred", "Invalid") AUTHOR_FIELDS = "author { login __typename }" COMMENT_FIELDS = f""" - id body url createdAt updatedAt {AUTHOR_FIELDS} + id body url updatedAt {AUTHOR_FIELDS} pullRequestReview {{ state }} """ PAGE_FIELDS = "pageInfo { hasNextPage endCursor }" @@ -34,13 +34,9 @@ def __init__(self, token): self.token = token def request(self, method, path, body=None): - data = None - if body is not None: - data = json.dumps(body).encode("utf-8") - request = Request( "https://api.github.com" + path, - data=data, + data=json.dumps(body).encode("utf-8") if body is not None else None, method=method, headers={ "Authorization": f"Bearer {self.token}", @@ -57,71 +53,48 @@ def graphql(self, query, variables): raise RuntimeError("GitHub GraphQL returned errors; refusing partial data") return result["data"] - def connection(self, repository, number, field, selection): - owner, name = repository.split("/") + def connection(self, node_id, field, selection, typename="PullRequest", page=None): cursor = None nodes = [] while True: - query = f""" - query($owner: String!, $name: String!, $number: Int!, $cursor: String) {{ - repository(owner: $owner, name: $name) {{ - pullRequest(number: $number) {{ + if page is None: + query = f""" + query($id: ID!, $cursor: String) {{ + node(id: $id) {{ ... on {typename} {{ {field}(first: 100, after: $cursor) {{ nodes {{ {selection} }} {PAGE_FIELDS} }} - }} + }} }} }} - }} - """ - data = self.graphql( - query, {"owner": owner, "name": name, "number": number, "cursor": cursor} - ) - page = data["repository"]["pullRequest"][field] + """ + data = self.graphql(query, {"id": node_id, "cursor": cursor}) + page = data["node"][field] nodes.extend(page["nodes"]) if not page["pageInfo"]["hasNextPage"]: return nodes cursor = page["pageInfo"]["endCursor"] - - def comments(self, thread): - page = thread["comments"] - comments = list(page["nodes"]) - while page["pageInfo"]["hasNextPage"]: - query = f""" - query($id: ID!, $cursor: String) {{ - node(id: $id) {{ ... on PullRequestReviewThread {{ - comments(first: 100, after: $cursor) {{ - nodes {{ {COMMENT_FIELDS} }} {PAGE_FIELDS} - }} - }} }} - }} - """ - data = self.graphql( - query, {"id": thread["id"], "cursor": page["pageInfo"]["endCursor"]} - ) - page = data["node"]["comments"] - comments.extend(page["nodes"]) - return comments + page = None def snapshot(api, repository, number): pr = api.request("GET", f"/repos/{repository}/pulls/{number}") - reviews = api.connection( - repository, - number, - "reviews", - f"id state {AUTHOR_FIELDS}", - ) - comments = api.connection(repository, number, "comments", f"id body {AUTHOR_FIELDS}") + reviews = api.connection(pr["node_id"], "reviews", f"id state {AUTHOR_FIELDS}") + comments = api.connection(pr["node_id"], "comments", f"id body {AUTHOR_FIELDS}") threads = api.connection( - repository, - number, + pr["node_id"], "reviewThreads", - f"""id isResolved isOutdated + f"""id isResolved comments(first: 100) {{ nodes {{ {COMMENT_FIELDS} }} {PAGE_FIELDS} }}""", ) for thread in threads: - thread["comments"] = api.comments(thread) - commits = api.connection(repository, number, "commits", "commit { oid }") + thread["comments"] = api.connection( + thread["id"], + "comments", + COMMENT_FIELDS, + "PullRequestReviewThread", + page=thread["comments"], + ) + commits = api.connection(pr["node_id"], "commits", "commit { oid }") current = api.request("GET", f"/repos/{repository}/pulls/{number}") if current["head"]["sha"] != pr["head"]["sha"]: raise RuntimeError("PR head changed while reading review data; rerun required") @@ -162,37 +135,40 @@ def parse_disposition(body): return fields -def evaluate(data, bots, authorized, tracking_valid): - """Pure policy; API-dependent identity and tracking checks are supplied by caller.""" - errors = [] - findings = [] - for bot in sorted(bots): - reviewed = any( - actor_login(review.get("author")) == bot - and review["state"] in {"COMMENTED", "APPROVED", "CHANGES_REQUESTED"} - for review in data["reviews"] - ) - completed = any( - actor_login(comment.get("author")) == bot - and ( - ( - bot == "infiscale-bot" - and comment["body"].strip() == "未发现本次 PR 引入的新问题。LGTM!" # noqa: RUF001 - ) - or ( - bot == "chatgpt-codex-connector[bot]" - and comment["body"].startswith("\n") - and re.search( - r"(?m)^\| 📝 \*\*Code Review\*\* \| ✅ \*\*Completed\*\*" - r"(?: )? \|", - comment["body"], - ) - ) +def completion_comment(comment): + bot = actor_login(comment.get("author")) + body = comment["body"].replace("\r\n", "\n").strip() + if bot == "infiscale-bot": + return body == "未发现本次 PR 引入的新问题。LGTM!" # noqa: RUF001 + return ( + bot == "chatgpt-codex-connector[bot]" + and body.startswith("\n") + and bool( + re.search( + r"(?m)^\| 📝 \*\*Code Review\*\* \| ✅ \*\*Completed\*\*" + r"(?: )? \|", + body, ) - for comment in data["comments"] ) - if not reviewed and not completed: - errors.append(f"{bot}: missing published review or successful completion comment") + ) + + +def evaluate(data, bots, authorized, tracking_valid): + """Check PR-wide completion, then apply the same reply policy to AI/human threads.""" + completed = { + actor_login(review.get("author")) + for review in data["reviews"] + if review["state"] in {"COMMENTED", "APPROVED", "CHANGES_REQUESTED"} + } | { + actor_login(comment.get("author")) + for comment in data["comments"] + if completion_comment(comment) + } + errors = [ + f"{bot}: missing published review or successful completion comment" + for bot in sorted(bots - completed) + ] + findings = [] for thread in data["threads"]: comments = [ @@ -209,11 +185,6 @@ def evaluate(data, bots, authorized, tracking_valid): or reviewer == data["author"] ): continue - reviewer_activity = root["updatedAt"] - if reviewer in bots: - reviewer_activity = max( - c["updatedAt"] for c in comments if actor_login(c.get("author")) in bots - ) candidates = [] for comment in comments[1:]: author = comment.get("author") or {} @@ -230,12 +201,10 @@ def evaluate(data, bots, authorized, tracking_valid): status = "Unaddressed" reason = "No authorized disposition reply" if latest: - comment, fields = latest + _, fields = latest status = fields.get("disposition", "Unaddressed") reason = fields.get("error", "") - if comment["updatedAt"] < reviewer_activity: - reason = "Review comment changed after disposition; reply again" - elif not reason and status == "Accepted": + if not reason and status == "Accepted": fix = fields.get("fix", "") link = re.fullmatch(r"https://github\.com/([^/]+/[^/]+)/commit/([^/]+)", fix) if link and link[1].lower() == data["repository"].lower(): @@ -262,22 +231,16 @@ def passed(result): def summary(number, head, result): - counts = Counter(f["status"] for f in result["findings"]) - remaining = sum(bool(f["error"]) for f in result["findings"]) + blocked = [f for f in result["findings"] if f["error"]] lines = [ f"## PR #{number} · AI Review Disposition", "", f"Head: `{head}`", "", - f"Findings: {len(result['findings'])}; unresolved requirements: {remaining}", - "", - "| Accepted | Rejected | Deferred | Invalid | Unaddressed |", - "| --- | --- | --- | --- | --- |", - "| " + " | ".join(str(counts[s]) for s in (*STATUSES, "Unaddressed")) + " |", + f"Findings: {len(result['findings'])}; unresolved requirements: {len(blocked)}", "", ] lines.extend(f"- {error}" for error in result["errors"]) - blocked = [f for f in result["findings"] if f["error"]] for finding in blocked[:100]: lines.append(f"- [{finding['status']}]({finding['url']}): {finding['error']}") if len(blocked) > 100: @@ -295,40 +258,36 @@ def check_pr(api, repository, number, bots): f"/repos/{repository}/check-runs", {"name": CHECK_NAME, "head_sha": head, "status": "in_progress"}, ) - permissions = {} - tracking = {} + @cache def authorized(login, author): if login == author: return True - if login not in permissions: - try: - response = api.request( - "GET", f"/repos/{repository}/collaborators/{quote(login, safe='')}/permission" - ) - permissions[login] = response["permission"] in {"admin", "maintain", "write"} - except HTTPError as error: - if error.code != 404: - raise - permissions[login] = False - return permissions[login] + try: + response = api.request( + "GET", f"/repos/{repository}/collaborators/{quote(login, safe='')}/permission" + ) + return response["permission"] in {"admin", "write"} + except HTTPError as error: + if error.code != 404: + raise + return False + @cache def tracking_valid(value): - if value not in tracking: - match = re.fullmatch( - r"https://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9_.-]+/issues/[1-9][0-9]*)", - value, - ) - valid = False - if match: - try: - item = api.request("GET", f"/repos/{match[1]}") - valid = item["state"] == "open" and "pull_request" not in item - except HTTPError as error: - if error.code != 404: - raise - tracking[value] = valid - return tracking[value] + match = re.fullmatch( + r"https://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9_.-]+/issues/[1-9][0-9]*)", + value, + ) + if not match: + return False + try: + item = api.request("GET", f"/repos/{match[1]}") + return item["state"] == "open" and "pull_request" not in item + except HTTPError as error: + if error.code != 404: + raise + return False try: data = snapshot(api, repository, number) diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 19373d4..6ab39b9 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -216,11 +216,6 @@ def test_edit_timestamp_selects_latest_disposition(self): ) self.assertFalse(passed(result(data))) - def test_ai_edit_invalidates_older_reply(self): - data = fixture("Disposition: Invalid\nReason: False positive") - data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T03:00:00Z" - self.assertIn("changed", result(data)["findings"][0]["error"]) - def test_missing_pending_or_dismissed_review_blocks(self): for state in (None, "DISMISSED", "PENDING"): with self.subTest(state=state): @@ -272,6 +267,7 @@ def test_both_bots_can_complete_without_findings(self): def test_completion_comments_require_the_exact_bot_and_success_format(self): cases = ( (CODEX, CODEX_SUMMARY, True), + (CODEX, CODEX_SUMMARY.replace("\n", "\r\n"), True), (CODEX, CODEX_SUMMARY.replace("✅ **Completed**", "⚠️ **Failed**"), False), (CODEX, CODEX_SUMMARY.replace("✅ **Completed**", "⏳ **In progress**"), False), (CODEX, CODEX_SUMMARY.replace("**Code Review**", "**Security Review**"), False), @@ -339,22 +335,6 @@ def test_new_finding_requires_disposition_without_requiring_a_new_review(self): data["threads"].append(fixture()["threads"][0]) self.assertFalse(passed(result(data))) - def test_human_findings_require_complete_dispositions(self): - for body in ( - None, - "done", - "Disposition: Rejected", - "Disposition: Unknown\nReason: Test", - "Disposition: Accepted\nReason: Fixed", - f"Disposition: Accepted\nReason: Fixed\nFix: {'c' * 40}", - "Disposition: Deferred\nReason: Later", - "Disposition: Deferred\nReason: Later\nTracking: ISSUE-42", - ): - with self.subTest(body=body): - evaluation = result(fixture(body, reviewer="human-reviewer")) - self.assertFalse(passed(evaluation)) - self.assertEqual(len(evaluation["findings"]), 1) - def test_human_findings_keep_resolve_and_reply_permissions(self): for resolved, login in ((False, "contributor"), (True, "stranger"), (True, BOT)): with self.subTest(resolved=resolved, login=login): @@ -390,37 +370,18 @@ def test_configured_user_bot_takes_priority_over_pr_author_exclusion(self): data["threads"][0]["comments"][-1]["author"]["login"] = "infiscale-bot" self.assertFalse(passed(result(data, bots={"infiscale-bot"}))) - def test_editing_the_human_root_requires_a_fresh_disposition(self): - data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") - comments = data["threads"][0]["comments"] - comments[0]["updatedAt"] = "2026-10-09T03:00:00Z" - evaluation = result(data) - self.assertEqual(evaluation["errors"], []) - self.assertIn("changed", evaluation["findings"][0]["error"]) - comments[1]["updatedAt"] = "2026-10-09T04:00:00Z" - self.assertTrue(passed(result(data))) - - def test_human_follow_up_keeps_the_existing_disposition(self): - for text in ("OK", "Thanks", "Follow-up discussion"): - with self.subTest(text=text): - data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") + def test_discussion_and_root_edits_do_not_require_another_disposition(self): + for reviewer in (BOT, "human-reviewer"): + with self.subTest(reviewer=reviewer): + data = fixture("Disposition: Invalid\nReason: Test", reviewer=reviewer) + data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T03:00:00Z" data["threads"][0]["comments"].append( - comment(text, "human-reviewer", "2026-10-09T03:00:00Z") + comment("Thanks", reviewer, "2026-10-09T03:00:00Z") ) self.assertTrue(passed(result(data))) data["threads"][0]["isResolved"] = False self.assertIn("resolve", result(data)["findings"][0]["error"]) - def test_ai_follow_up_still_requires_a_fresh_disposition(self): - data = fixture("Disposition: Invalid\nReason: Test") - data["threads"][0]["comments"].append( - comment("Follow up", BOT, "2026-10-09T03:00:00Z") - ) - data["reviews"][0]["submittedAt"] = "2026-10-09T03:30:00Z" - evaluation = result(data) - self.assertEqual(evaluation["errors"], []) - self.assertIn("changed", evaluation["findings"][0]["error"]) - def test_human_reviews_do_not_require_completion_markers(self): data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") data["threads"][0]["comments"][0]["updatedAt"] = "2026-10-09T01:45:00Z" @@ -465,11 +426,11 @@ def test_duplicate_and_unknown_fields_are_invalid(self): ): self.assertIn("error", parse_disposition(text)) - def test_summary_separates_status_counts_and_remaining_requirements(self): + def test_summary_links_to_blocked_threads(self): data = fixture("Disposition: Accepted\nReason: Fixed", resolved=False) report = summary(128, HEAD, result(data)) self.assertIn("unresolved requirements: 1", report) - self.assertIn("| 1 | 0 | 0 | 0 | 0 |", report) + self.assertIn(data["threads"][0]["comments"][0]["url"], report) class ApiTests(unittest.TestCase): @@ -536,9 +497,9 @@ def test_connections_read_more_than_100_nodes(self): ] for field in ("reviews", "comments"): with self.subTest(field=field): - responses = [{"repository": {"pullRequest": {field: p}}} for p in pages] + responses = [{"node": {field: p}} for p in pages] with patch.object(api, "graphql", side_effect=responses) as graphql: - self.assertEqual(len(api.connection("org/repo", 128, field, "id")), 101) + self.assertEqual(len(api.connection("pr-1", field, "id")), 101) self.assertEqual(graphql.call_args.args[1]["cursor"], "next") def test_long_thread_comments_are_paginated(self): @@ -552,11 +513,54 @@ def test_long_thread_comments_are_paginated(self): } page = {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}} with patch.object(api, "graphql", return_value={"node": {"comments": page}}): - comments = api.comments(thread) + comments = api.connection( + thread["id"], + "comments", + "id", + "PullRequestReviewThread", + page=thread["comments"], + ) self.assertEqual(len(comments), 101) self.assertEqual(comments[-1], 100) self.assertEqual(len(thread["comments"]["nodes"]), 100) + def test_snapshot_keeps_inline_replies_and_top_level_completion_separate(self): + api = GitHub("test-token") + data = fixture("Disposition: Invalid\nReason: Test") + pr = { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "user": {"login": data["author"]}, + "state": "open", + } + + def page(nodes): + return {"nodes": nodes, "pageInfo": {"hasNextPage": False, "endCursor": None}} + + thread = copy.deepcopy(data["threads"][0]) + thread["comments"] = page(thread["comments"]) + completed = comment(INFISCALE_COMPLETE, "infiscale-bot") + responses = [ + {"node": {field: page(nodes)}} + for field, nodes in ( + ("reviews", data["reviews"]), + ("comments", [completed]), + ("reviewThreads", [thread]), + ("commits", [{"commit": {"oid": FIX}}, {"commit": {"oid": HEAD}}]), + ) + ] + with ( + patch.object(api, "request", return_value=pr), + patch.object(api, "graphql", side_effect=responses) as graphql, + ): + loaded = snapshot(api, "org/repo", 128) + self.assertEqual(loaded["comments"], [completed]) + self.assertEqual(loaded["threads"], data["threads"]) + self.assertEqual(loaded["commits"], [FIX, HEAD]) + self.assertTrue(passed(result(loaded, bots={BOT, "infiscale-bot"}))) + self.assertEqual(graphql.call_count, 4) + self.assertTrue(all(c.args[1]["id"] == "pr-1" for c in graphql.call_args_list)) + def test_graphql_errors_reject_partial_data(self): api = GitHub("test-token") with patch.object(api, "request", return_value={"data": {}, "errors": [{}]}): @@ -565,7 +569,12 @@ def test_graphql_errors_reject_partial_data(self): def test_snapshot_rejects_head_change_during_read(self): api = GitHub("test-token") - before = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} + before = { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "user": {"login": "contributor"}, + "state": "open", + } after = {**before, "head": {"sha": FIX}} with ( patch.object(api, "request", side_effect=[before, after]), @@ -575,7 +584,12 @@ def test_snapshot_rejects_head_change_during_read(self): snapshot(api, "org/repo", 128) def test_snapshot_retains_repository_for_commit_link_validation(self): - pr = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} + pr = { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "user": {"login": "contributor"}, + "state": "open", + } api = GitHub("test-token") with ( patch.object(api, "request", return_value=pr), @@ -584,7 +598,12 @@ def test_snapshot_retains_repository_for_commit_link_validation(self): self.assertEqual(snapshot(api, "org/repo", 128)["repository"], "org/repo") def test_snapshot_reads_top_level_comments_for_completion(self): - pr = {"head": {"sha": HEAD}, "user": {"login": "contributor"}, "state": "open"} + pr = { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "user": {"login": "contributor"}, + "state": "open", + } api = GitHub("test-token") completed = comment(INFISCALE_COMPLETE, "infiscale-bot") with ( @@ -595,8 +614,8 @@ def test_snapshot_reads_top_level_comments_for_completion(self): ): data = snapshot(api, "org/repo", 128) self.assertEqual(data["comments"], [completed]) - self.assertEqual(connection.call_args_list[1].args[2], "comments") - self.assertNotIn("pullRequestReview", connection.call_args_list[1].args[3]) + self.assertEqual(connection.call_args_list[1].args[1], "comments") + self.assertNotIn("pullRequestReview", connection.call_args_list[1].args[2]) def test_commit_link_does_not_add_api_requests(self): for reviewer in (BOT, "human-reviewer"): @@ -716,12 +735,49 @@ def test_multiple_findings_share_one_issue_lookup(self): ] self.assertEqual(len(issue_reads), 1) - def run_check(self, snapshots, issue=None): + def test_reply_permissions_are_queried_and_cached(self): + for permission, expected in ( + ("write", True), + ("admin", True), + ("read", False), + ("none", False), + ): + with self.subTest(permission=permission): + data = fixture("Disposition: Invalid\nReason: Test") + data["threads"][0]["comments"][-1]["author"]["login"] = "maintainer" + data["threads"].append(copy.deepcopy(data["threads"][0])) + calls, ok = self.run_check( + [data, copy.deepcopy(data)], {"permission": permission} + ) + self.assertEqual(ok, expected) + permission_reads = [c for c in calls if "/collaborators/" in c.args[1]] + self.assertEqual(len(permission_reads), 1) + self.assertEqual( + permission_reads[0].args, + ("GET", "/repos/org/repo/collaborators/maintainer/permission"), + ) + + def test_permission_lookup_errors_block_and_encode_the_login(self): + for status in (404, 403, 429, 500): + with self.subTest(status=status): + data = fixture("Disposition: Invalid\nReason: Test") + data["threads"][0]["comments"][-1]["author"]["login"] = "user/name" + error = HTTPError( + "https://api.github.com/permission", status, "error", {}, None + ) + calls, ok = self.run_check([data], error) + self.assertFalse(ok) + self.assertEqual( + calls[2].args, ("GET", "/repos/org/repo/collaborators/user%2Fname/permission") + ) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def run_check(self, snapshots, lookup=None): api = GitHub("test-token") pr = {"head": {"sha": HEAD}, "state": "open"} responses = [pr, {"id": 99}] - if issue is not None: - responses.append(issue) + if lookup is not None: + responses.append(lookup) responses.append({}) with ( patch.object(api, "request", side_effect=responses) as request, @@ -753,7 +809,6 @@ def test_checks_only_the_requested_pr(self): self.assertEqual(code, 0) client.assert_called_once_with("test-token") check.assert_called_once_with(client.return_value, "org/repo", 313, {BOT}) - client.return_value.open_prs.assert_not_called() def test_target_pr_failure_sets_exit_code(self): code, _, check = self.run_main("--pr-number", "313", passed=False) @@ -771,17 +826,18 @@ def test_missing_or_invalid_pr_never_defaults_to_a_repository_scan(self): self.run_main(*arguments) self.assertEqual(error.exception.code, 2) + def test_empty_or_invalid_bot_configuration_is_an_error(self): + for bots in ("", ",", "reviewer+bot"): + with self.subTest(bots=bots), self.assertRaises(SystemExit) as error: + self.run_main("--pr-number", "313", "--bots", bots) + self.assertEqual(error.exception.code, 2) + def test_closed_pr_does_not_create_a_check(self): api = GitHub("test-token") with patch.object(api, "request", return_value={"state": "closed"}) as request: self.assertTrue(check_pr(api, "org/repo", 313, {BOT})) request.assert_called_once_with("GET", "/repos/org/repo/pulls/313") - def test_removed_jira_option_is_not_accepted(self): - with self.assertRaises(SystemExit) as error: - self.run_main("--pr-number", "313", "--jira-url", "https://jira.test") - self.assertEqual(error.exception.code, 2) - if __name__ == "__main__": unittest.main() From 3e0b6ea9b85c6c951be87379a360cabbf821fa41 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:25:36 +0800 Subject: [PATCH 10/21] fix[ci]: delegate conversation resolution to GitHub Problem: - Resolve and Unresolve do not trigger the disposition workflow, leaving stale Check results. Solution: - Validate AI review completion and disposition replies independently of resolution. - Exclude isResolved from snapshots so resolution changes cannot invalidate the second read. - Require GitHub native conversation resolution alongside the required Check in setup docs. Test: - Python 3.11: all 71 unit tests passed. - Ruff lint and format checks passed for both changed Python files. - Regression coverage includes all dispositions and Resolve/Unresolve during evaluation. - Patch whitespace check and AST checks for unchanged bot identity/completion logic passed. JIRA: PDIST-770 --- docs/AI_REVIEW_DISPOSITION.md | 12 ++-- scripts/check_ai_review_disposition.py | 9 +-- scripts/tests/test_ai_review_disposition.py | 76 +++++++++++++++++---- 3 files changed, 76 insertions(+), 21 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 4480bf2..e8f173a 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,6 +1,6 @@ # AI Review / Disposition Check -合并前检查三件事:每个指定 AI 完成过审查;AI 和人工 reviewer 的每条行内线程都有有效模板回复;这些线程全部 resolved。无需采纳所有意见,检查也不代替人工 approval。 +合并门禁分工:本 Check 验证每个指定 AI 完成过审查,以及 AI 和人工 reviewer 的每条行内线程都有有效模板回复;GitHub 原生的 **Require conversation resolution before merging** 规则负责要求讨论线程全部 resolved。两项都满足才能合并,无需采纳所有意见,也不代替人工 approval。 ## 检查规则 @@ -11,7 +11,8 @@ - 检查指定 AI 和 PR 作者之外的人工账号创建的全部已发布 inline threads,包括 outdated 和 resolved threads。PR 作者自己的人工线程、未配置 Bot 的线程、PR 顶层评论和 Review 总评不计为待处理线程;pending review 不计入。配置的 AI 即使是 `User` 或 PR 作者,仍按 AI 处理。 - 模板回复者须为 PR 作者或当前具有仓库写权限的人工账号;Bot 和配置的 AI 服务账号不能自行处理意见。组织成员身份本身不代表写权限。 - 采用编辑时间最新的明确模板回复,同一时间取 thread 中更后的回复;新的无效模板会替代旧模板,普通讨论不会。AI/人工使用相同规则,后续讨论或原始意见编辑不额外要求重复确认;新问题应新开线程。 -- 每个线程必须同时满足有效回复和 resolved。仅 resolved、仅回复 “done”,或在 PR 总结中统一回答均不能通过。工具不自动回复或 resolve。 +- 本 Check 只验证每个纳入检查的线程有有效回复,不读取或判断 resolved 状态。仅 resolved、仅回复 “done”,或在 PR 总结中统一回答均不能通过。工具不自动回复或 resolve。 +- 有效回复可以让本 Check 在未 resolved 时通过;GitHub 原生 conversation resolution 规则继续阻止合并。点击 Resolve/Unresolve 后,GitHub 更新原生合并条件,无需为了该状态重跑本 Check。原生规则覆盖所有代码讨论,范围可能比本 Check 筛选的线程更广。 | Bot login | 可替代正式 Review 的成功结束评论 | | --- | --- | @@ -50,11 +51,12 @@ Tracking: N/A 2. 设置组织/仓库 Variable `AI_REVIEW_BOTS`,如 `chatgpt-codex-connector[bot],infiscale-bot`。空值会报错,不提供隐式默认 Bot。 3. 生产接入时,将 caller 中 `uses: ...@main` 和 `shared-ref: main` 同时固定到本公共 CI 仓库的同一个已审核 commit SHA。 4. caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`;不执行或检出 PR 代码。 -5. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。保留人工 approval 与 conversation resolution 规则。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 +5. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 +6. 在目标分支的 ruleset / 分支保护中启用 [**Require conversation resolution before merging**](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-a-pull-request-before-merging),并保留人工 approval 要求。此项必须与 Required Status Check 同时配置;脚本不会修改仓库规则,也不会因未 resolved 而失败。 PR opened/reopened/synchronize/ready_for_review 和 PR 顶层评论变化直接触发检查。Review/行内评论变化先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器,因此 fork PR 也可复查。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。 -Resolve/Unresolve 没有原生 Actions trigger:resolve 后,在 PR 顶层发一条评论或通过 Actions 手动运行 `AI Review Disposition`,填写 `pr-number`。使用 `GITHUB_TOKEN` 发布的 Review/评论通常不会触发后续 Actions,应由审查流程显式触发复查,或用 App token 发布。 +Resolve/Unresolve 无需触发本 Check,也不需要额外发评论或手动复查;它们由 GitHub 原生 conversation resolution 规则处理。审查完成或模板回复变化仍需触发检查。使用 `GITHUB_TOKEN` 发布的 Review/评论通常不会触发后续 Actions,应由审查流程显式触发复查,或用 App token 发布。 同一 PR 串行检查,不取消正在执行的检查;不同 PR 独立。通过前再完整读取一次数据,提交或评论变化则阻断。API 错误不放行;取消、超时或 Check 写入失败可能留下 in-progress 状态,需重跑。该方案是异步门禁,不提供不可删改的历史审计或 merge queue 合成 SHA 支持。 @@ -66,6 +68,6 @@ GH_TOKEN="" python scripts/check_ai_review_disposition.py \ --bots 'chatgpt-codex-connector[bot],infiscale-bot' ``` -仅支持 GitHub.com。退出码:0 通过或 closed PR 跳过,1 未通过,2 参数错误或未捕获的执行错误。验证:`python -m unittest discover -s scripts/tests -v`;正式启用 required check 前,应在目标仓库试运行 Bot 完成 → 模板回复 → resolve → 复查流程。 +仅支持 GitHub.com。退出码:0 通过或 closed PR 跳过,1 未通过,2 参数错误或未捕获的执行错误。验证:`python -m unittest discover -s scripts/tests -v`;正式启用合并门禁前,应在目标仓库验证:Bot 完成且模板有效时,即使线程未 resolved,本 Check 也能通过,但 GitHub 原生规则阻止合并;Resolve 后原生条件满足;再次 Unresolve 后原生规则重新阻止合并,全程无需因解决状态变化重跑本 Check。另需确认没有模板或模板无效的线程仍让本 Check 失败。 参考:[Actions 事件](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)、[Checks API](https://docs.github.com/en/rest/checks/runs)、[复用 workflow](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows)。 diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index aa380fb..869cc44 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -83,7 +83,8 @@ def snapshot(api, repository, number): threads = api.connection( pr["node_id"], "reviewThreads", - f"""id isResolved + # Repository rules enforce resolution; it must not affect snapshot equality. + f"""id comments(first: 100) {{ nodes {{ {COMMENT_FIELDS} }} {PAGE_FIELDS} }}""", ) for thread in threads: @@ -215,8 +216,6 @@ def evaluate(data, bots, authorized, tracking_valid): elif not reason and status == "Deferred": if not tracking_valid(fields.get("tracking", "")): reason = "Tracking must reference an existing, readable, open GitHub issue" - if not reason and not thread["isResolved"]: - reason = "Disposition is valid; resolve the conversation" findings.append({ "id": thread["id"], "url": root["url"], @@ -237,7 +236,9 @@ def summary(number, head, result): "", f"Head: `{head}`", "", - f"Findings: {len(result['findings'])}; unresolved requirements: {len(blocked)}", + f"Findings: {len(result['findings'])}; blocked dispositions: {len(blocked)}", + "", + "Conversation resolution is enforced separately by GitHub repository rules.", "", ] lines.extend(f"- {error}" for error in result["errors"]) diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 6ab39b9..d632c54 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -88,7 +88,7 @@ def result(data, bots=None, authorized=None, tracking_valid=None): class PolicyTests(unittest.TestCase): - def test_all_dispositions_pass_with_required_evidence(self): + def test_all_dispositions_pass_independently_of_resolution(self): replies = [ f"Disposition: Accepted\nReason: Added bounds check\nFix: {FIX}", "Disposition: Rejected\nReason: This input is already validated upstream", @@ -100,17 +100,19 @@ def test_all_dispositions_pass_with_required_evidence(self): ] for reviewer in (BOT, "human-reviewer"): for body in replies: - with self.subTest(reviewer=reviewer, body=body): - self.assertTrue(passed(result(fixture(body, reviewer=reviewer)))) + for resolved in (False, True): + with self.subTest(reviewer=reviewer, body=body, resolved=resolved): + self.assertTrue(passed(result(fixture(body, resolved, reviewer)))) def test_resolve_alone_does_not_pass(self): evaluation = result(fixture()) self.assertFalse(passed(evaluation)) self.assertEqual(evaluation["findings"][0]["status"], "Unaddressed") - def test_valid_reply_still_needs_resolve(self): - data = fixture("Disposition: Rejected\nReason: Covered upstream", resolved=False) - self.assertIn("resolve", result(data)["findings"][0]["error"]) + def test_valid_reply_does_not_require_resolution_field(self): + data = fixture("Disposition: Rejected\nReason: Covered upstream") + del data["threads"][0]["isResolved"] + self.assertTrue(passed(result(data))) def test_outdated_findings_still_block(self): data = fixture() @@ -335,10 +337,10 @@ def test_new_finding_requires_disposition_without_requiring_a_new_review(self): data["threads"].append(fixture()["threads"][0]) self.assertFalse(passed(result(data))) - def test_human_findings_keep_resolve_and_reply_permissions(self): - for resolved, login in ((False, "contributor"), (True, "stranger"), (True, BOT)): - with self.subTest(resolved=resolved, login=login): - data = fixture("Disposition: Invalid\nReason: Test", resolved, "human-reviewer") + def test_human_findings_keep_reply_permissions(self): + for login in ("stranger", BOT): + with self.subTest(login=login): + data = fixture("Disposition: Invalid\nReason: Test", False, "human-reviewer") data["threads"][0]["comments"][-1]["author"]["login"] = login data["threads"][0]["isOutdated"] = True evaluation = result(data) @@ -380,7 +382,7 @@ def test_discussion_and_root_edits_do_not_require_another_disposition(self): ) self.assertTrue(passed(result(data))) data["threads"][0]["isResolved"] = False - self.assertIn("resolve", result(data)["findings"][0]["error"]) + self.assertTrue(passed(result(data))) def test_human_reviews_do_not_require_completion_markers(self): data = fixture("Disposition: Invalid\nReason: Test", reviewer="human-reviewer") @@ -429,7 +431,8 @@ def test_duplicate_and_unknown_fields_are_invalid(self): def test_summary_links_to_blocked_threads(self): data = fixture("Disposition: Accepted\nReason: Fixed", resolved=False) report = summary(128, HEAD, result(data)) - self.assertIn("unresolved requirements: 1", report) + self.assertIn("blocked dispositions: 1", report) + self.assertIn("Conversation resolution is enforced separately", report) self.assertIn(data["threads"][0]["comments"][0]["url"], report) @@ -567,6 +570,55 @@ def test_graphql_errors_reject_partial_data(self): with self.assertRaises(RuntimeError): api.graphql("query", {}) + def test_resolution_changes_during_check_do_not_block(self): + api = GitHub("test-token") + data = fixture("Disposition: Invalid\nReason: False positive") + pr = { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "user": {"login": data["author"]}, + "state": "open", + } + + def page(nodes): + return {"nodes": nodes, "pageInfo": {"hasNextPage": False, "endCursor": None}} + + for resolutions in ((False, True), (True, False)): + with self.subTest(resolutions=resolutions): + states = iter(resolutions) + + def graphql(query, variables, states=states): + if "reviewThreads(first:" in query: + thread = { + "id": "thread-1", + "comments": page(data["threads"][0]["comments"]), + } + resolved = next(states) + # Return resolution state only if the query requested it. + if "isResolved" in query: + thread["isResolved"] = resolved + return {"node": {"reviewThreads": page([thread])}} + for field, nodes in ( + ("reviews", data["reviews"]), + ("comments", []), + ("commits", [{"commit": {"oid": FIX}}, {"commit": {"oid": HEAD}}]), + ): + if f"{field}(first:" in query: + return {"node": {field: page(nodes)}} + self.fail("Unexpected GraphQL query") + + with ( + patch.object( + api, "request", side_effect=[pr, {"id": 99}, pr, pr, pr, pr, {}] + ) as request, + patch.object(api, "graphql", side_effect=graphql), + patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), + patch("builtins.print"), + ): + self.assertTrue(check_pr(api, "org/repo", 128, {BOT})) + self.assertEqual(list(states), []) + self.assertEqual(request.call_args.args[2]["conclusion"], "success") + def test_snapshot_rejects_head_change_during_read(self): api = GitHub("test-token") before = { From a53023d7db838f184668d081b2521eb2e423c15c Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:37:39 +0800 Subject: [PATCH 11/21] docs: remove SHA pinning requirement from AI review setup --- docs/AI_REVIEW_DISPOSITION.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index e8f173a..1fb3ae2 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -49,10 +49,9 @@ Tracking: N/A 1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 和 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 复制到目标仓库 `.github/workflows/` 并合入默认分支。 2. 设置组织/仓库 Variable `AI_REVIEW_BOTS`,如 `chatgpt-codex-connector[bot],infiscale-bot`。空值会报错,不提供隐式默认 Bot。 -3. 生产接入时,将 caller 中 `uses: ...@main` 和 `shared-ref: main` 同时固定到本公共 CI 仓库的同一个已审核 commit SHA。 -4. caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`;不执行或检出 PR 代码。 -5. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 -6. 在目标分支的 ruleset / 分支保护中启用 [**Require conversation resolution before merging**](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-a-pull-request-before-merging),并保留人工 approval 要求。此项必须与 Required Status Check 同时配置;脚本不会修改仓库规则,也不会因未 resolved 而失败。 +3. caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`;不执行或检出 PR 代码。 +4. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 +5. 在目标分支的 ruleset / 分支保护中启用 [**Require conversation resolution before merging**](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-a-pull-request-before-merging),并保留人工 approval 要求。此项必须与 Required Status Check 同时配置;脚本不会修改仓库规则,也不会因未 resolved 而失败。 PR opened/reopened/synchronize/ready_for_review 和 PR 顶层评论变化直接触发检查。Review/行内评论变化先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器,因此 fork PR 也可复查。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。 From be25a22a1c39b9c64fe8931e858e29829be1ada5 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:30:43 +0800 Subject: [PATCH 12/21] fix[ci]: evaluate current AI reviews and keep latest disposition results Track review rounds and dismissal fallback, restrict Deferred to open issues in the PR repository, and recheck open PRs when an issue changes. Prevent older evaluations from replacing newer check results and revalidate permissions and tracking issues before success. Validation: 94 unit tests, Ruff lint/format, actionlint, and a read-only snapshot of the live PR review data. --- .../reusable-ai-review-disposition.yml | 26 +- docs/AI_REVIEW_DISPOSITION.md | 38 +- docs/examples/ai-review-disposition.yml | 18 +- docs/examples/ai-review-events.yml | 2 +- scripts/check_ai_review_disposition.py | 235 ++++++++-- scripts/tests/test_ai_review_disposition.py | 423 +++++++++++++++++- 6 files changed, 668 insertions(+), 74 deletions(-) diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index 0631389..0d260d5 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -9,10 +9,16 @@ on: type: string pr-number: description: 'Positive PR number to check in the caller repository' - required: true + required: false type: number + default: 0 + all-open-prs: + description: 'Explicitly recheck every open PR after an issue changes' + required: false + type: boolean + default: false shared-ref: - description: 'Trusted revision of this repository; pin alongside workflow uses' + description: 'Revision of the shared CI scripts; defaults to main' required: false type: string default: main @@ -28,10 +34,10 @@ jobs: name: Evaluate AI Review Dispositions runs-on: ubuntu-latest timeout-minutes: 15 - # Serialize updates for this PR only; every run reads its live API state. + # Keep the newest evaluation for this PR; other PRs run independently. concurrency: - group: ai-review-disposition-${{ github.repository }}-${{ inputs.pr-number }} - cancel-in-progress: false + group: ai-review-disposition-${{ github.repository }}-${{ inputs.all-open-prs && 'all-open-prs' || inputs.pr-number }} + cancel-in-progress: true steps: - name: Checkout trusted shared scripts uses: actions/checkout@v4 @@ -43,7 +49,7 @@ jobs: sparse-checkout: scripts - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v7 with: python-version: '3.11' @@ -52,6 +58,10 @@ jobs: GH_TOKEN: ${{ github.token }} AI_REVIEW_BOTS: ${{ inputs.bot-logins }} PR_NUMBER: ${{ inputs.pr-number }} + ALL_OPEN_PRS: ${{ inputs.all-open-prs }} run: | - python .ci-shared/scripts/check_ai_review_disposition.py \ - --pr-number "$PR_NUMBER" + if [[ "$ALL_OPEN_PRS" == "true" ]]; then + python .ci-shared/scripts/check_ai_review_disposition.py --all-open-prs + else + python .ci-shared/scripts/check_ai_review_disposition.py --pr-number "$PR_NUMBER" + fi diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 1fb3ae2..62f3e63 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,25 +1,27 @@ # AI Review / Disposition Check -合并门禁分工:本 Check 验证每个指定 AI 完成过审查,以及 AI 和人工 reviewer 的每条行内线程都有有效模板回复;GitHub 原生的 **Require conversation resolution before merging** 规则负责要求讨论线程全部 resolved。两项都满足才能合并,无需采纳所有意见,也不代替人工 approval。 +合并门禁分工:本 Check 验证每个指定 AI 按下述轮次规则完成审查,以及 AI 和人工 reviewer 的每条行内线程都有有效模板回复;GitHub 原生的 **Require conversation resolution before merging** 规则负责要求讨论线程全部 resolved。两项都满足才能合并,无需采纳所有意见,也不代替人工 approval。 ## 检查规则 -- 每次明确指定一个 PR;closed/merged PR 跳过。Check 写入该 PR 的最新 head commit。 +- 默认明确指定一个 PR;closed/merged PR 跳过。只有显式的 `--all-open-prs` 才扫描本仓库全部开放 PR。Check 写入各 PR 的最新 head commit。 - `AI_REVIEW_BOTS` 是必填的逗号分隔 login 列表,每个账号都必须完成审查。按 login 精确匹配,忽略大小写;GraphQL `Bot` login 缺少 `[bot]` 后缀时补齐,普通 `User` 不补。 -- 完成依据是该 Bot 发布的 `COMMENTED`、`APPROVED` 或 `CHANGES_REQUESTED` Review,或下表中的成功结束评论。`PENDING`、`DISMISSED`、开始/失败/配额不足提示不算完成。 -- 完成按整个 PR 判断,不绑定当前 head;后续 push 无需重审。新的 pending review 或开始评论不撤销已有完成结果;所有有效 Review 被 dismissed 且无成功评论时重新阻断。 +- 完成依据是该 Bot 发布的 `COMMENTED`、`APPROVED` 或 `CHANGES_REQUESTED` Review,或下表中的成功结束评论。`PENDING`、`DISMISSED`、开始/失败/配额不足提示本身不算完成。 +- 每个 AI 单独按开始消息及时间划分轮次,同一 AI 在同一 PR 上的轮次不得重叠。新一轮开始或出现更新的 pending / 进行中状态后,旧结果不能提前放行。没有开始记录的历史数据,兼容已有的已发布 Review 或成功结束评论。 +- 本轮发布的 Review 全部被 dismissed 后,本轮作废,允许更早的有效 Review 或成功摘要兜底;没有有效依据则阻断。随后又开始新一轮时,仍须等待该轮完成。 +- 审查完成不绑定当前 head,修复后 push 无需强制重审;Accepted 的修复提交仍须属于当前 PR。 - 检查指定 AI 和 PR 作者之外的人工账号创建的全部已发布 inline threads,包括 outdated 和 resolved threads。PR 作者自己的人工线程、未配置 Bot 的线程、PR 顶层评论和 Review 总评不计为待处理线程;pending review 不计入。配置的 AI 即使是 `User` 或 PR 作者,仍按 AI 处理。 - 模板回复者须为 PR 作者或当前具有仓库写权限的人工账号;Bot 和配置的 AI 服务账号不能自行处理意见。组织成员身份本身不代表写权限。 - 采用编辑时间最新的明确模板回复,同一时间取 thread 中更后的回复;新的无效模板会替代旧模板,普通讨论不会。AI/人工使用相同规则,后续讨论或原始意见编辑不额外要求重复确认;新问题应新开线程。 - 本 Check 只验证每个纳入检查的线程有有效回复,不读取或判断 resolved 状态。仅 resolved、仅回复 “done”,或在 PR 总结中统一回答均不能通过。工具不自动回复或 resolve。 - 有效回复可以让本 Check 在未 resolved 时通过;GitHub 原生 conversation resolution 规则继续阻止合并。点击 Resolve/Unresolve 后,GitHub 更新原生合并条件,无需为了该状态重跑本 Check。原生规则覆盖所有代码讨论,范围可能比本 Check 筛选的线程更广。 -| Bot login | 可替代正式 Review 的成功结束评论 | +| Bot login | 开始与完成依据 | | --- | --- | -| `infiscale-bot` | 去除首尾空白后全文为 `未发现本次 PR 引入的新问题。LGTM!` | -| `chatgpt-codex-connector[bot]` | 自带摘要以 `` 开头,且 `Code Review` 行状态为 `✅ **Completed**` | +| `infiscale-bot` | 首行 `收到,开始 review`(允许前置 👀)为开始;之后有已发布 Review,或去除首尾空白后全文为 `未发现本次 PR 引入的新问题。LGTM!`,视为完成 | +| `chatgpt-codex-connector[bot]` | 自带摘要以 `` 开头,采用 `Code Review` 行自己的状态和时间;最新状态须为 `✅ **Completed**`,进行中或失败不能用旧 Review 提前放行 | -仅匹配相应 Bot 发布的 PR 顶层评论;人工引用、行内回复、Security Review 完成均不能作为完成依据。Bot 须在全部意见发布完毕后才提交正式 Review 或成功结束评论。 +仅匹配相应 Bot 发布的 PR 顶层评论;人工引用、行内回复、Security Review 完成均不能作为完成依据。整条摘要的编辑时间不能刷新旧的 Code Review 完成时间。infiscale 的判定以其一轮 Review 几乎同时发布的行为约定为前提;CI 不修改 Bot,也不额外要求人工确认审查结束。 ## 回复模板 @@ -37,9 +39,11 @@ Tracking: N/A | Accepted | `Fix` 为完整 40 位 SHA,或当前仓库的标准 commit 链接;提交必须仍在当前 PR 的 commits 中 | | Rejected | 拒绝理由 | | Invalid | 误报理由 | -| Deferred | `Tracking` 为 GitHub Issue 完整链接;API 确认该 Issue 存在、当前 token 可读、仍开放且不是 PR | +| Deferred | `Tracking` 为当前仓库的 GitHub Issue 完整链接;API 确认该 Issue 存在、可读、仍开放且不是 PR | -不适用的 `Fix` / `Tracking` 可省略或填 `N/A`。commit 链接仅接受 `https://github.com/owner/repo/commit/<40位SHA>`,Issue 链接仅接受 `https://github.com/owner/repo/issues/<正整数>`,均不接受查询参数或锚点。force-push 移除修复提交后,Accepted 失效。Issue 可跨仓库,但当前 token 必须能读取;目标仓库的 `GITHUB_TOKEN` 无法读取其他私有仓库时需改用具有对应访问权限的调用方式。 +不适用的 `Fix` / `Tracking` 可省略或填 `N/A`。commit 链接仅接受 `https://github.com/owner/repo/commit/<40位SHA>`,Issue 链接仅接受 `https://github.com/owner/repo/issues/<正整数>`,均不接受查询参数或锚点。两种链接均限定当前仓库;跨仓库 Issue 在请求前拒绝,转移后的重定向也不能绕过仓库校验。只使用目标仓库的 `GITHUB_TOKEN`,无需额外钥匙。 + +force-push 移除修复提交后,Accepted 失效。Issue 关闭后,Deferred 失效,需要作者新增或编辑有效处理回复,例如改为 Accepted 并提供当前 PR 的修复 commit,或改为 Rejected 并说明理由。工具不会自动替作者修改模板。 工具验证引用有效,不判断理由是否充分、提交是否真正修复问题或延期是否合理;这些由人工审查确认。 @@ -53,11 +57,15 @@ Tracking: N/A 4. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 5. 在目标分支的 ruleset / 分支保护中启用 [**Require conversation resolution before merging**](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-a-pull-request-before-merging),并保留人工 approval 要求。此项必须与 Required Status Check 同时配置;脚本不会修改仓库规则,也不会因未 resolved 而失败。 -PR opened/reopened/synchronize/ready_for_review 和 PR 顶层评论变化直接触发检查。Review/行内评论变化先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器,因此 fork PR 也可复查。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。 +PR opened/reopened/synchronize、目标分支变化和 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。普通聊天不会开启新审查轮次。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器,因此 fork PR 也可复查。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。 + +本仓库 Issue closed/reopened/deleted/transferred 时,caller 使用显式的 `all-open-prs: true` 检查所有开放 PR,不维护 Issue 到 PR 的反向关联,也不把 Issue 编号当作 PR 编号。仍引用无效 Issue 的 Deferred 会阻断;其他 PR 按各自实时状态判断。一个 PR 失败不会跳过后续 PR,新建普通 Issue 不触发。 -Resolve/Unresolve 无需触发本 Check,也不需要额外发评论或手动复查;它们由 GitHub 原生 conversation resolution 规则处理。审查完成或模板回复变化仍需触发检查。使用 `GITHUB_TOKEN` 发布的 Review/评论通常不会触发后续 Actions,应由审查流程显式触发复查,或用 App token 发布。 +Resolve/Unresolve 无需触发本 Check,也不需要额外发评论或手动复查;它们由 GitHub 原生 conversation resolution 规则处理。使用 `GITHUB_TOKEN` 发布的 Review、评论或 Issue 事件通常不会触发后续 Actions,应由对应流程显式 dispatch 复查,或用 App token 发布。 -同一 PR 串行检查,不取消正在执行的检查;不同 PR 独立。通过前再完整读取一次数据,提交或评论变化则阻断。API 错误不放行;取消、超时或 Check 写入失败可能留下 in-progress 状态,需重跑。该方案是异步门禁,不提供不可删改的历史审计或 merge queue 合成 SHA 支持。 +同一 PR 的新运行取消旧运行;Issue 全仓复查有独立并发组,仍按每个 PR 争取结果发布权。只部署一份 caller,按其运行编号及 attempt 判断新旧。B 接管后只认 B:B 运行中、失败或取消时均不回退到 A 的通过结果。旧 Check 改为带 superseded 后缀的历史名称,只有当前检查使用固定门禁名;最后写结果不设置名称,因此旧请求迟到也不能重新占用 B 的门禁名称。历史记录保留与否不影响 B 的判定。 + +通过前再次完整读取 PR 状态、目标分支、提交、Review 和评论,并清除缓存重新校验回复者权限及 Issue 有效性。数据变化或 API 错误不放行。补查使用 caller 的 Run workflow;重跑旧编号不能覆盖更新的运行编号。取消、超时或 Check 写入失败可能保留当前 in-progress 状态,需发起新检查。该方案是异步门禁,不提供不可删改的历史审计或 merge queue 合成 SHA 支持。 CLI(会写入指定 PR 的 Check): @@ -67,6 +75,8 @@ GH_TOKEN="" python scripts/check_ai_review_disposition.py \ --bots 'chatgpt-codex-connector[bot],infiscale-bot' ``` -仅支持 GitHub.com。退出码:0 通过或 closed PR 跳过,1 未通过,2 参数错误或未捕获的执行错误。验证:`python -m unittest discover -s scripts/tests -v`;正式启用合并门禁前,应在目标仓库验证:Bot 完成且模板有效时,即使线程未 resolved,本 Check 也能通过,但 GitHub 原生规则阻止合并;Resolve 后原生条件满足;再次 Unresolve 后原生规则重新阻止合并,全程无需因解决状态变化重跑本 Check。另需确认没有模板或模板无效的线程仍让本 Check 失败。 +仅支持 GitHub.com。退出码:0 通过、closed PR 跳过或已被更新检查取代,1 未通过,2 参数错误或未捕获的执行错误。全仓复查使用 `--all-open-prs` 替代 `--pr-number`,逐一处理全部开放 PR 并汇总退出码。验证:`python -m unittest discover -s scripts/tests -v`。 + +正式启用门禁前,在目标仓库验证:新轮开始阻断、完成后恢复;全部 dismissed 时允许有效旧依据兜底;Issue 关闭使 Deferred 失败、更新模板后恢复;B 失败不能被 A 的迟到成功覆盖,B 成功不被旧记录阻塞。还需验证本 Check 通过但线程未 resolved 时,GitHub 原生规则继续阻止合并;Resolve/Unresolve 只更新原生条件,无需重跑本 Check。 参考:[Actions 事件](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)、[Checks API](https://docs.github.com/en/rest/checks/runs)、[复用 workflow](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows)。 diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index f53a3b5..c0adc3c 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -4,12 +4,14 @@ name: AI Review Disposition on: pull_request_target: - types: [opened, reopened, synchronize, ready_for_review] + types: [opened, reopened, synchronize, edited] workflow_run: workflows: [AI Review Events] types: [completed] issue_comment: types: [created, edited, deleted] + issues: + types: [closed, reopened, deleted, transferred] workflow_dispatch: inputs: pr-number: @@ -25,7 +27,11 @@ permissions: jobs: disposition: - if: ${{ github.event_name != 'issue_comment' || github.event.issue.pull_request }} + if: >- + ${{ github.event_name != 'issues' + && (github.event_name != 'issue_comment' || github.event.issue.pull_request) + && (github.event_name != 'pull_request_target' + || github.event.action != 'edited' || github.event.changes.base) }} uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main with: # Collector run-name is the PR number, even when workflow_run.pull_requests is empty. @@ -37,3 +43,11 @@ jobs: # Set this repository/organization variable to exact bot logins. bot-logins: ${{ vars.AI_REVIEW_BOTS }} shared-ref: main + + issue-recheck: + if: ${{ github.event_name == 'issues' }} + uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main + with: + all-open-prs: true + bot-logins: ${{ vars.AI_REVIEW_BOTS }} + shared-ref: main diff --git a/docs/examples/ai-review-events.yml b/docs/examples/ai-review-events.yml index 373361d..55c74d1 100644 --- a/docs/examples/ai-review-events.yml +++ b/docs/examples/ai-review-events.yml @@ -6,7 +6,7 @@ run-name: ${{ github.event.pull_request.number }} on: pull_request_review: - types: [submitted, edited, dismissed] + types: [submitted, dismissed] pull_request_review_comment: types: [created, edited, deleted] diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 869cc44..6fe9e0d 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -1,11 +1,12 @@ #!/usr/bin/env python3 -"""Check one PR's AI review completion and dispositions without running PR code.""" +"""Check AI review rounds and dispositions without running PR code.""" import argparse import json import os import re import sys +from datetime import UTC, datetime from functools import cache from urllib.error import HTTPError from urllib.parse import quote @@ -19,6 +20,10 @@ pullRequestReview {{ state }} """ PAGE_FIELDS = "pageInfo { hasNextPage endCursor }" +CODEX = "chatgpt-codex-connector[bot]" +CODEX_SUMMARY = "" +PUBLISHED_REVIEWS = {"COMMENTED", "APPROVED", "CHANGES_REQUESTED"} +INFISCALE_COMPLETE = "未发现本次 PR 引入的新问题。LGTM!" # noqa: RUF001 def actor_login(author): @@ -75,11 +80,28 @@ def connection(self, node_id, field, selection, typename="PullRequest", page=Non cursor = page["pageInfo"]["endCursor"] page = None + def pages(self, path, field=None): + """Read a REST list completely, including object-wrapped lists such as checks.""" + nodes = [] + separator = "&" if "?" in path else "?" + page = 1 + while True: + response = self.request("GET", f"{path}{separator}per_page=100&page={page}") + items = response[field] if field else response + nodes.extend(items) + if len(items) < 100: + return nodes + page += 1 + def snapshot(api, repository, number): pr = api.request("GET", f"/repos/{repository}/pulls/{number}") - reviews = api.connection(pr["node_id"], "reviews", f"id state {AUTHOR_FIELDS}") - comments = api.connection(pr["node_id"], "comments", f"id body {AUTHOR_FIELDS}") + reviews = api.connection( + pr["node_id"], "reviews", f"id state createdAt submittedAt {AUTHOR_FIELDS}" + ) + comments = api.connection( + pr["node_id"], "comments", f"id body createdAt updatedAt {AUTHOR_FIELDS}" + ) threads = api.connection( pr["node_id"], "reviewThreads", @@ -97,11 +119,17 @@ def snapshot(api, repository, number): ) commits = api.connection(pr["node_id"], "commits", "commit { oid }") current = api.request("GET", f"/repos/{repository}/pulls/{number}") - if current["head"]["sha"] != pr["head"]["sha"]: - raise RuntimeError("PR head changed while reading review data; rerun required") + + def revision(item): + base = item.get("base", {}) + return item["head"]["sha"], base.get("ref"), base.get("sha"), item["state"] + + if revision(current) != revision(pr): + raise RuntimeError("PR changed while reading review data; rerun required") return { "repository": repository, "head": pr["head"]["sha"], + "base": {key: pr.get("base", {}).get(key) for key in ("ref", "sha")}, "author": pr["user"]["login"].lower(), "state": current["state"], "reviews": reviews, @@ -136,38 +164,93 @@ def parse_disposition(body): return fields +def timestamp(value): + return ( + datetime.fromisoformat(value.replace("Z", "+00:00")) + if value + else datetime.min.replace(tzinfo=UTC) + ) + + +def infiscale_start(body): + lines = body.strip().splitlines() + return bool(lines) and lines[0].removeprefix("👀").strip() == "收到,开始 review" # noqa: RUF001 + + +def codex_progress(comment): + """Use the Code Review row's own time; Security Review edits are unrelated.""" + body = comment["body"].replace("\r\n", "\n").strip() + if not body.startswith(CODEX_SUMMARY + "\n"): + return None + row = re.search(r"(?m)^\| 📝 \*\*Code Review\*\* \| ([^\n|]+)\|", body) + if not row: + return None + completed = bool( + re.fullmatch( + r"✅ \*\*Completed\*\*(?: )?", + row[1].strip(), + ) + ) + clock = re.search(r'\n") - and bool( - re.search( - r"(?m)^\| 📝 \*\*Code Review\*\* \| ✅ \*\*Completed\*\*" - r"(?: )? \|", - body, - ) - ) + return body == INFISCALE_COMPLETE + progress = codex_progress(comment) if bot == CODEX else None + return progress is not None and progress[1] + + +def review_complete(data, bot): + """Rounds for a bot do not overlap; a withdrawn round may use older evidence.""" + reviews = [r for r in data["reviews"] if actor_login(r.get("author")) == bot] + comments = [c for c in data["comments"] if actor_login(c.get("author")) == bot] + starts = [timestamp(r.get("createdAt")) for r in reviews if r["state"] == "PENDING"] + completed = [ + timestamp(r.get("submittedAt")) for r in reviews if r["state"] in PUBLISHED_REVIEWS + ] + progress = [] + for comment in comments: + if bot == "infiscale-bot" and infiscale_start(comment["body"]): + starts.append(timestamp(comment.get("createdAt"))) + if bot == CODEX: + status = codex_progress(comment) + if status: + progress.append(status) + if status[1]: + completed.append(status[0]) + elif completion_comment(comment): + completed.append(timestamp(comment.get("createdAt"))) + latest_status = max( + progress, key=lambda status: (status[0], not status[1]), default=None ) + if latest_status and not latest_status[1]: + starts.append(latest_status[0]) + start = max(starts, default=timestamp(None)) + current = [ + r + for r in reviews + if r["state"] in PUBLISHED_REVIEWS | {"DISMISSED"} + and timestamp(r.get("submittedAt")) >= start + ] + if current and all(r["state"] == "DISMISSED" for r in current): + return bool(completed) + if latest_status and not latest_status[1]: + return False + return any(when >= start for when in completed) def evaluate(data, bots, authorized, tracking_valid): """Check PR-wide completion, then apply the same reply policy to AI/human threads.""" - completed = { - actor_login(review.get("author")) - for review in data["reviews"] - if review["state"] in {"COMMENTED", "APPROVED", "CHANGES_REQUESTED"} - } | { - actor_login(comment.get("author")) - for comment in data["comments"] - if completion_comment(comment) - } errors = [ - f"{bot}: missing published review or successful completion comment" - for bot in sorted(bots - completed) + f"{bot}: waiting for this review round to complete (no valid completion evidence)" + for bot in sorted(bots) + if not review_complete(data, bot) ] findings = [] @@ -215,7 +298,7 @@ def evaluate(data, bots, authorized, tracking_valid): reason = "Fix must be a current PR commit SHA or its repository commit URL" elif not reason and status == "Deferred": if not tracking_valid(fields.get("tracking", "")): - reason = "Tracking must reference an existing, readable, open GitHub issue" + reason = "Tracking must reference a readable, open issue in this repository" findings.append({ "id": thread["id"], "url": root["url"], @@ -249,6 +332,47 @@ def summary(number, head, result): return "\n".join(lines) +def current_check(api, repository, number, head, check): + """Only one fixed-name gate remains; late writes cannot rename it back.""" + path = f"/repos/{repository}/commits/{head}/check-runs" + runs = api.pages( + f"{path}?check_name={quote(CHECK_NAME, safe='')}&filter=all", "check_runs" + ) + prefix = f"ai-review-disposition:{number}:" + runs = [ + run + for run in runs + if run["app"]["id"] == check["app"]["id"] + and (not run.get("external_id") or run["external_id"].startswith(prefix)) + ] + runs = {run["id"]: run for run in [*runs, check]}.values() + + def order(run): + key = re.fullmatch( + re.escape(prefix) + r"([0-9]+):([0-9]+)", run.get("external_id") or "" + ) + return (int(key[1]), int(key[2]), run["id"]) if key and int(key[1]) else None + + managed = [run for run in runs if order(run)] + newest = max(managed, key=order) if managed else check + # An explicit local CLI check is ordered by registration, not an Actions sequence. + newest = max( + [newest, *(run for run in runs if not order(run))], key=lambda run: run["id"] + ) + for run in runs: + if run["id"] != newest["id"]: + api.request( + "PATCH", + f"/repos/{repository}/check-runs/{run['id']}", + { + "name": f"{CHECK_NAME} (superseded #{run['id']})", + "status": "completed", + "conclusion": "cancelled", + }, + ) + return newest["id"] == check["id"] + + def check_pr(api, repository, number, bots): pr = api.request("GET", f"/repos/{repository}/pulls/{number}") if pr["state"] != "open": @@ -257,7 +381,14 @@ def check_pr(api, repository, number, bots): check = api.request( "POST", f"/repos/{repository}/check-runs", - {"name": CHECK_NAME, "head_sha": head, "status": "in_progress"}, + { + "name": CHECK_NAME, + "head_sha": head, + "status": "in_progress", + "external_id": f"ai-review-disposition:{number}:" + f"{os.environ.get('GITHUB_RUN_NUMBER', '0')}:" + f"{os.environ.get('GITHUB_RUN_ATTEMPT', '1')}", + }, ) @cache @@ -277,20 +408,27 @@ def authorized(login, author): @cache def tracking_valid(value): match = re.fullmatch( - r"https://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9_.-]+/issues/[1-9][0-9]*)", + r"https://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)/issues/([1-9][0-9]*)", value, ) - if not match: + if not match or match[1].lower() != repository.lower(): return False try: - item = api.request("GET", f"/repos/{match[1]}") - return item["state"] == "open" and "pull_request" not in item + item = api.request("GET", f"/repos/{repository}/issues/{match[2]}") + return ( + item["state"] == "open" + and "pull_request" not in item + and item["repository_url"].lower() + == f"https://api.github.com/repos/{repository}".lower() + ) except HTTPError as error: if error.code != 404: raise return False try: + if not current_check(api, repository, number, head, check): + return True data = snapshot(api, repository, number) if data["head"] != head or data["state"] != "open": raise RuntimeError("PR changed before evaluation; rerun required") @@ -301,6 +439,10 @@ def tracking_valid(value): result["errors"].append( "PR review data changed during evaluation; rerun required" ) + else: + authorized.cache_clear() + tracking_valid.cache_clear() + result = evaluate(data, bots, authorized, tracking_valid) ok = passed(result) report = summary(number, head, result) except Exception as error: @@ -309,6 +451,8 @@ def tracking_valid(value): report = ( f"PR #{number}: evaluation failed ({type(error).__name__}); rerun required." ) + if not current_check(api, repository, number, head, check): + return True api.request( "PATCH", f"/repos/{repository}/check-runs/{check['id']}", @@ -329,7 +473,11 @@ def tracking_valid(value): def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY")) - parser.add_argument("--pr-number", type=int, required=True, help="PR to check") + target = parser.add_mutually_exclusive_group(required=True) + target.add_argument("--pr-number", type=int, help="PR to check") + target.add_argument( + "--all-open-prs", action="store_true", help="Explicitly recheck every open PR" + ) parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) args = parser.parse_args() bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} @@ -339,13 +487,28 @@ def main(): or any(not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots) or not args.repository or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository) - or args.pr_number <= 0 + or (args.pr_number is not None and args.pr_number <= 0) or not token ): parser.error( - "Valid repository, nonempty bot logins, PR number > 0 and token required" + "Valid repository, bot logins, token and a positive PR or explicit sweep required" ) api = GitHub(token) + if args.all_open_prs: + numbers = sorted({ + pr["number"] for pr in api.pages(f"/repos/{args.repository}/pulls?state=open") + }) + ok = True + for number in numbers: + try: + ok = check_pr(api, args.repository, number, bots) and ok + except Exception as error: + print( + f"PR #{number}: check failed ({type(error).__name__}); rerun required.", + file=sys.stderr, + ) + ok = False + return 0 if ok else 1 ok = check_pr(api, args.repository, args.pr_number, bots) return 0 if ok else 1 diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index d632c54..61079eb 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -5,11 +5,13 @@ import unittest from unittest.mock import patch from urllib.error import HTTPError +from urllib.parse import parse_qs, urlsplit from scripts.check_ai_review_disposition import ( CHECK_NAME, GitHub, check_pr, + current_check, evaluate, main, parse_disposition, @@ -61,6 +63,7 @@ def fixture(body=None, resolved=True, reviewer=BOT): "id": "review-1", "body": "", "state": "COMMENTED", + "createdAt": "2026-10-09T01:00:00Z", "submittedAt": "2026-10-09T01:30:00Z", "author": {"login": BOT}, "commit": {"oid": HEAD}, @@ -235,12 +238,14 @@ def test_published_review_needs_neither_current_head_nor_custom_marker(self): data["reviews"][0].update(state=state, body="", commit={"oid": FIX}) self.assertTrue(passed(result(data))) - def test_later_pending_review_does_not_erase_a_published_review(self): + def test_newer_pending_review_waits_for_new_completion(self): data = fixture("Disposition: Invalid\nReason: False positive") review = copy.deepcopy(data["reviews"][0]) - review.update(id="review-2", state="PENDING", submittedAt=None) + review.update( + id="review-2", state="PENDING", submittedAt=None, createdAt="2026-10-09T03:00:00Z" + ) data["reviews"].append(review) - self.assertTrue(passed(result(data))) + self.assertFalse(passed(result(data))) def test_zero_findings_pass_only_after_review_completion(self): data = fixture() @@ -303,11 +308,11 @@ def test_quoted_completion_text_does_not_count(self): data.update(reviews=[], threads=[], comments=[comment(quoted, bot)]) self.assertFalse(passed(result(data, bots={bot}))) - def test_infiscale_start_comment_does_not_replace_a_published_review(self): + def test_new_infiscale_start_invalidates_old_completion(self): data = fixture("Disposition: Invalid\nReason: Test", reviewer="infiscale-bot") data["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} data["comments"] = [comment(INFISCALE_START, "infiscale-bot")] - self.assertTrue(passed(result(data, bots={"infiscale-bot"}))) + self.assertFalse(passed(result(data, bots={"infiscale-bot"}))) def test_codex_completion_accepts_graphql_bot_login_without_suffix(self): data = fixture() @@ -436,6 +441,122 @@ def test_summary_links_to_blocked_threads(self): self.assertIn(data["threads"][0]["comments"][0]["url"], report) +class RoundTests(unittest.TestCase): + def infiscale(self): + data = fixture( + "Disposition: Invalid\nReason: False positive", reviewer="infiscale-bot" + ) + data["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} + data["comments"] = [comment("👀 " + INFISCALE_START, "infiscale-bot")] + return data + + def test_only_a_review_after_the_latest_start_completes_the_round(self): + data = self.infiscale() + self.assertFalse(passed(result(data, {"infiscale-bot"}))) + review = copy.deepcopy(data["reviews"][0]) + review.update(id="review-2", submittedAt="2026-10-09T03:00:00Z") + data["reviews"].append(review) + self.assertTrue(passed(result(data, {"infiscale-bot"}))) + data["head"] = "c" * 40 + self.assertTrue(passed(result(data, {"infiscale-bot"}))) + + def test_zero_findings_message_must_belong_to_the_new_round(self): + data = self.infiscale() + data["comments"].append( + comment(INFISCALE_COMPLETE, "infiscale-bot", "2026-10-09T01:00:00Z") + ) + self.assertFalse(passed(result(data, {"infiscale-bot"}))) + data["comments"].append( + comment(INFISCALE_COMPLETE, "infiscale-bot", "2026-10-09T03:00:00Z") + ) + self.assertTrue(passed(result(data, {"infiscale-bot"}))) + + def test_withdrawn_round_can_fall_back_but_a_later_start_cannot(self): + data = self.infiscale() + withdrawn = copy.deepcopy(data["reviews"][0]) + withdrawn.update( + id="review-2", state="DISMISSED", submittedAt="2026-10-09T03:00:00Z" + ) + data["reviews"].append(withdrawn) + self.assertTrue(passed(result(data, {"infiscale-bot"}))) + data["reviews"] = [withdrawn] + self.assertFalse(passed(result(data, {"infiscale-bot"}))) + data["comments"].append( + comment(INFISCALE_COMPLETE, "infiscale-bot", "2026-10-09T01:00:00Z") + ) + self.assertTrue(passed(result(data, {"infiscale-bot"}))) + data["comments"].append( + comment(INFISCALE_START, "infiscale-bot", "2026-10-09T04:00:00Z") + ) + self.assertFalse(passed(result(data, {"infiscale-bot"}))) + + def test_one_remaining_review_is_sufficient(self): + data = self.infiscale() + review = copy.deepcopy(data["reviews"][0]) + review.update(id="review-2", submittedAt="2026-10-09T03:00:00Z", state="DISMISSED") + data["reviews"].append(review) + data["reviews"].append({**review, "id": "review-3", "state": "COMMENTED"}) + self.assertTrue(passed(result(data, {"infiscale-bot"}))) + + def test_human_quotes_and_other_bot_starts_do_not_reset_a_bot(self): + data = fixture("Disposition: Invalid\nReason: Test") + data["comments"] = [ + comment(INFISCALE_START), + comment(INFISCALE_START, "other[bot]"), + ] + self.assertTrue(passed(result(data))) + + def test_codex_in_progress_or_failed_overrides_old_reviews(self): + for state in ("⏳ **In progress**", "⚠️ **Failed**"): + data = fixture("Disposition: Invalid\nReason: Test") + data["reviews"][0]["author"] = {"login": CODEX} + body = CODEX_SUMMARY.replace("✅ **Completed**", state) + data["comments"] = [comment(body, CODEX)] + self.assertFalse(passed(result(data, {CODEX}))) + data["comments"][0]["body"] = CODEX_SUMMARY + self.assertTrue(passed(result(data, {CODEX}))) + + def test_codex_security_edit_cannot_refresh_old_code_review_completion(self): + data = fixture() + data["threads"] = [] + data["reviews"] = [ + { + "id": "pending", + "author": {"login": CODEX}, + "state": "PENDING", + "createdAt": "2026-10-15T01:00:00Z", + "submittedAt": None, + } + ] + old = comment(CODEX_SUMMARY, CODEX) + old["updatedAt"] = "2026-10-20T01:00:00Z" + data["comments"] = [old] + self.assertFalse(passed(result(data, {CODEX}))) + body = CODEX_SUMMARY.replace("2026-10-14", "2026-10-16").replace( + "✅ **Completed**", "⏳ **In progress**" + ) + data["comments"].append(comment(body, CODEX)) + self.assertFalse(passed(result(data, {CODEX}))) + + def test_legacy_codex_completion_without_a_clock_does_not_complete_new_pending(self): + body = CODEX_SUMMARY.replace( + ' ' + "2026-10-14T09:05:35Z", + "", + ) + data = fixture() + data.update(threads=[], reviews=[], comments=[comment(body, CODEX)]) + self.assertTrue(passed(result(data, {CODEX}))) + data["reviews"] = [ + { + "state": "PENDING", + "author": {"login": CODEX}, + "createdAt": "2026-10-10T01:00:00Z", + } + ] + self.assertFalse(passed(result(data, {CODEX}))) + + class ApiTests(unittest.TestCase): def test_http_client_reads_and_writes_github_json(self): api = GitHub("test-token") @@ -608,6 +729,7 @@ def graphql(query, variables, states=states): self.fail("Unexpected GraphQL query") with ( + patch("scripts.check_ai_review_disposition.current_check", return_value=True), patch.object( api, "request", side_effect=[pr, {"id": 99}, pr, pr, pr, pr, {}] ) as request, @@ -649,6 +771,33 @@ def test_snapshot_retains_repository_for_commit_link_validation(self): ): self.assertEqual(snapshot(api, "org/repo", 128)["repository"], "org/repo") + def test_snapshot_rejects_base_change_but_ignores_unrelated_repo_metadata(self): + before = { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "base": {"ref": "main", "sha": FIX, "repo": {"description": "old"}}, + "user": {"login": "contributor"}, + "state": "open", + } + for base in ({"ref": "develop", "sha": FIX}, {"ref": "main", "sha": HEAD}): + with self.subTest(base=base): + api = GitHub("test-token") + with ( + patch.object(api, "request", side_effect=[before, {**before, "base": base}]), + patch.object(api, "connection", return_value=[]), + self.assertRaises(RuntimeError), + ): + snapshot(api, "org/repo", 128) + api = GitHub("test-token") + after = {**before, "base": {**before["base"], "repo": {"description": "new"}}} + with ( + patch.object(api, "request", side_effect=[before, after]), + patch.object(api, "connection", return_value=[]), + ): + self.assertEqual( + snapshot(api, "org/repo", 128)["base"], {"ref": "main", "sha": FIX} + ) + def test_snapshot_reads_top_level_comments_for_completion(self): pr = { "node_id": "pr-1", @@ -785,7 +934,48 @@ def test_multiple_findings_share_one_issue_lookup(self): issue_reads = [ c for c in calls if c.args[:2] == ("GET", "/repos/org/repo/issues/42") ] - self.assertEqual(len(issue_reads), 1) + self.assertEqual(len(issue_reads), 2) + + def test_closed_issue_or_revoked_permission_during_final_verification_blocks(self): + for first, second, body, login in ( + ( + {"state": "open"}, + {"state": "closed"}, + "Disposition: Deferred\nReason: Later\nTracking: https://github.com/org/repo/issues/42", + "contributor", + ), + ( + {"permission": "write"}, + {"permission": "read"}, + "Disposition: Invalid\nReason: Test", + "maintainer", + ), + ): + with self.subTest(first=first): + data = fixture(body) + data["threads"][0]["comments"][-1]["author"]["login"] = login + calls, ok = self.run_check([data, copy.deepcopy(data)], [first, second]) + self.assertFalse(ok) + self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + + def test_cross_repository_links_are_rejected_without_reading_them(self): + for repo in ("org/other", "other/repo"): + data = fixture( + f"Disposition: Deferred\nReason: Later\nTracking: https://github.com/{repo}/issues/42" + ) + calls, ok = self.run_check([data]) + self.assertFalse(ok) + self.assertFalse(any("/issues/" in c.args[1] for c in calls)) + + def test_issue_transfer_redirect_cannot_bypass_repository_restriction(self): + data = fixture( + "Disposition: Deferred\nReason: Later\nTracking: https://github.com/org/repo/issues/42" + ) + _, ok = self.run_check( + [data], + {"state": "open", "repository_url": "https://api.github.com/repos/org/other"}, + ) + self.assertFalse(ok) def test_reply_permissions_are_queried_and_cached(self): for permission, expected in ( @@ -803,7 +993,7 @@ def test_reply_permissions_are_queried_and_cached(self): ) self.assertEqual(ok, expected) permission_reads = [c for c in calls if "/collaborators/" in c.args[1]] - self.assertEqual(len(permission_reads), 1) + self.assertEqual(len(permission_reads), 2 if expected else 1) self.assertEqual( permission_reads[0].args, ("GET", "/repos/org/repo/collaborators/maintainer/permission"), @@ -827,12 +1017,27 @@ def test_permission_lookup_errors_block_and_encode_the_login(self): def run_check(self, snapshots, lookup=None): api = GitHub("test-token") pr = {"head": {"sha": HEAD}, "state": "open"} - responses = [pr, {"id": 99}] - if lookup is not None: - responses.append(lookup) - responses.append({}) + lookups = iter(lookup) if isinstance(lookup, list) else None + + def respond(method, path, body=None): + if (method, path) == ("GET", "/repos/org/repo/pulls/128"): + return pr + if method == "POST": + return {"id": 99} + if method == "PATCH": + return {} + value = next(lookups) if lookups else lookup + if isinstance(value, Exception): + raise value + if value is None: + self.fail(f"Unexpected lookup: {path}") + if "state" in value: + return {"repository_url": "https://api.github.com/repos/org/repo", **value} + return value + with ( - patch.object(api, "request", side_effect=responses) as request, + patch.object(api, "request", side_effect=respond) as request, + patch("scripts.check_ai_review_disposition.current_check", return_value=True), patch("scripts.check_ai_review_disposition.snapshot", side_effect=snapshots), patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), patch("builtins.print"), @@ -841,8 +1046,161 @@ def run_check(self, snapshots, lookup=None): return request.call_args_list, ok +class CheckStore(GitHub): + """Exercise interleaved evaluations without writing to GitHub.""" + + def __init__(self): + super().__init__("test-token") + self.checks = {} + + def add(self, run, attempt=1, app=1, number=128): + check = { + "id": len(self.checks) + 1, + "name": CHECK_NAME, + "head_sha": HEAD, + "status": "in_progress", + "app": {"id": app}, + "external_id": f"ai-review-disposition:{number}:{run}:{attempt}", + } + self.checks[check["id"]] = check + return copy.deepcopy(check) + + def request(self, method, path, body=None): + if method == "GET" and "/pulls/" in path: + return {"state": "open", "head": {"sha": HEAD}} + if method == "POST": + check = self.add(0) + self.checks[check["id"]].update(copy.deepcopy(body)) + return copy.deepcopy(self.checks[check["id"]]) + if method == "GET": + query = parse_qs(urlsplit(path).query) + runs = [c for c in self.checks.values() if c["name"] == query["check_name"][0]] + start = (int(query["page"][0]) - 1) * 100 + return {"check_runs": copy.deepcopy(runs[start : start + 100])} + if method == "PATCH": + check = self.checks[int(path.rsplit("/", 1)[1])] + check.update(copy.deepcopy(body)) + return copy.deepcopy(check) + raise AssertionError(f"Unexpected API call: {method} {path}") + + def gate(self): + return [c for c in self.checks.values() if c["name"] == CHECK_NAME] + + +class LatestCheckTests(unittest.TestCase): + def claim(self, api, check): + return current_check(api, "org/repo", 128, HEAD, check) + + def test_late_old_result_cannot_override_new_failure_or_success(self): + for new_passes in (False, True): + with self.subTest(new_passes=new_passes): + api = CheckStore() + ready = fixture("Disposition: Invalid\nReason: Test") + missing = fixture() + old_data, new_data = (missing, ready) if new_passes else (ready, missing) + started = False + + def old_snapshot( + *args, api=api, new_data=new_data, new_passes=new_passes, old_data=old_data + ): + nonlocal started + if not started: + started = True + with ( + patch.dict("os.environ", {"GITHUB_RUN_NUMBER": "2"}), + patch( + "scripts.check_ai_review_disposition.snapshot", return_value=new_data + ), + ): + self.assertEqual(check_pr(api, "org/repo", 128, {BOT}), new_passes) + return old_data + + with ( + patch.dict( + "os.environ", + { + "GITHUB_RUN_NUMBER": "1", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_STEP_SUMMARY": "", + }, + ), + patch( + "scripts.check_ai_review_disposition.snapshot", side_effect=old_snapshot + ), + patch("builtins.print"), + ): + self.assertTrue(check_pr(api, "org/repo", 128, {BOT})) + # Even an already-sent result that arrives late never restores the gate name. + api.request( + "PATCH", + "/repos/org/repo/check-runs/1", + {"status": "completed", "conclusion": "success"}, + ) + self.assertEqual(len(api.gate()), 1) + self.assertEqual(api.gate()[0]["id"], 2) + self.assertEqual( + api.gate()[0]["conclusion"], "success" if new_passes else "failure" + ) + + def test_new_pending_or_cancelled_run_never_falls_back_to_old_success(self): + api = CheckStore() + old = api.add(1) + api.checks[old["id"]].update(status="completed", conclusion="success") + new = api.add(2) + self.assertTrue(self.claim(api, new)) + self.assertEqual(api.gate()[0]["status"], "in_progress") + api.checks[new["id"]].update(status="completed", conclusion="cancelled") + self.assertFalse(self.claim(api, old)) + self.assertEqual(api.gate()[0]["conclusion"], "cancelled") + + def test_a_delayed_older_registration_does_not_take_over(self): + api = CheckStore() + new = api.add(2) + old = api.add(1) + self.assertFalse(self.claim(api, old)) + self.assertEqual([c["id"] for c in api.gate()], [new["id"]]) + + def test_rerun_of_latest_generation_replaces_its_previous_attempt(self): + api = CheckStore() + old = api.add(2) + new = api.add(2, attempt=2) + self.assertTrue(self.claim(api, new)) + self.assertFalse(self.claim(api, old)) + + def test_check_history_is_paginated_and_other_apps_or_prs_are_untouched(self): + api = CheckStore() + for run in range(1, 102): + newest = api.add(run) + other_app = api.add(999, app=2) + other_pr = api.add(999, number=129) + self.assertTrue(self.claim(api, newest)) + self.assertEqual(api.checks[1]["conclusion"], "cancelled") + self.assertEqual(api.checks[newest["id"]]["name"], CHECK_NAME) + for check in (other_app, other_pr): + self.assertEqual(api.checks[check["id"]], check) + + def test_manual_cli_check_does_not_permanently_fence_out_future_actions(self): + api = CheckStore() + api.add(1) + manual = api.add(0) + self.assertTrue(self.claim(api, manual)) + future = api.add(2) + self.assertTrue(self.claim(api, future)) + self.assertFalse(self.claim(api, manual)) + + def test_legacy_check_without_external_id_is_replaced(self): + for external_id in (None, ""): + with self.subTest(external_id=external_id): + api = CheckStore() + old = api.add(0) + api.checks[old["id"]]["external_id"] = external_id + new = api.add(1) + self.assertTrue(self.claim(api, new)) + self.assertEqual([c["id"] for c in api.gate()], [new["id"]]) + + class MainTests(unittest.TestCase): - def run_main(self, *arguments, passed=True): + def run_main(self, *arguments, passed=True, numbers=None, results=None): with ( patch.dict("os.environ", {"GH_TOKEN": "test-token"}, clear=True), patch.object( @@ -854,8 +1212,47 @@ def run_main(self, *arguments, passed=True): ) as check, patch("sys.stderr", new_callable=io.StringIO), ): + if numbers is not None: + client.return_value.pages.return_value = [{"number": n} for n in numbers] + if results is not None: + check.side_effect = results return main(), client, check + def test_explicit_sweep_checks_all_open_prs_even_after_failure(self): + code, client, check = self.run_main( + "--all-open-prs", passed=False, numbers=[24, 7, 24] + ) + self.assertEqual(code, 1) + self.assertEqual([c.args[2] for c in check.call_args_list], [7, 24]) + client.return_value.pages.assert_called_once_with( + "/repos/org/repo/pulls?state=open" + ) + + def test_sweep_continues_after_a_pr_api_error(self): + code, _, check = self.run_main( + "--all-open-prs", numbers=[1, 2, 3], results=[RuntimeError("failed"), True, True] + ) + self.assertEqual(code, 1) + self.assertEqual([c.args[2] for c in check.call_args_list], [1, 2, 3]) + + def test_empty_open_pr_sweep_does_not_publish_checks(self): + code, _, check = self.run_main("--all-open-prs", numbers=[]) + self.assertEqual(code, 0) + check.assert_not_called() + + def test_open_pr_enumeration_reads_all_pages_without_issue_backlinks(self): + api = GitHub("test-token") + pages = [[{"number": n} for n in range(1, 101)], [{"number": 101}]] + with patch.object(api, "request", side_effect=pages) as request: + self.assertEqual(len(api.pages("/repos/org/repo/pulls?state=open")), 101) + self.assertEqual(request.call_count, 2) + self.assertTrue( + all( + "/pulls?state=open&per_page=100&page=" in c.args[1] + for c in request.call_args_list + ) + ) + def test_checks_only_the_requested_pr(self): code, client, check = self.run_main("--pr-number", "313") self.assertEqual(code, 0) From 71b6c20bfd6d1d7807eedd7107e922efd239db4a Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:15:18 +0800 Subject: [PATCH 13/21] fix[ci]: dispatch automated issue rechecks and migrate review test fixtures --- .../workflows/test-ai-review-disposition.yml | 36 +++++ docs/AI_REVIEW_DISPOSITION.md | 12 +- docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md | 125 +++++++++++++++ docs/examples/ai-review-close-issue.yml | 42 +++++ docs/examples/ai-review-disposition.yml | 17 +- docs/examples/ai-review-sandbox/README.md | 69 ++++++++ .../ai-review-final-read-lab.yml | 126 +++++++++++++++ .../ai-review-sandbox/ai-review-fixture.yml | 102 ++++++++++++ .../ai-review-latest-result-lab.yml | 142 +++++++++++++++++ docs/examples/ai-review-sandbox/ruleset.json | 42 +++++ scripts/check_ai_review_disposition.py | 7 +- .../tests/simulate_ai_review_disposition.py | 147 ++++++++++++++++++ scripts/tests/test_ai_review_disposition.py | 15 +- scripts/tests/test_ai_review_scenarios.py | 10 ++ 14 files changed, 883 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/test-ai-review-disposition.yml create mode 100644 docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md create mode 100644 docs/examples/ai-review-close-issue.yml create mode 100644 docs/examples/ai-review-sandbox/README.md create mode 100644 docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml create mode 100644 docs/examples/ai-review-sandbox/ai-review-fixture.yml create mode 100644 docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml create mode 100644 docs/examples/ai-review-sandbox/ruleset.json create mode 100644 scripts/tests/simulate_ai_review_disposition.py create mode 100644 scripts/tests/test_ai_review_scenarios.py diff --git a/.github/workflows/test-ai-review-disposition.yml b/.github/workflows/test-ai-review-disposition.yml new file mode 100644 index 0000000..7797c90 --- /dev/null +++ b/.github/workflows/test-ai-review-disposition.yml @@ -0,0 +1,36 @@ +name: Test AI Review Disposition + +on: + pull_request: + paths: + - 'scripts/**' + - 'docs/examples/ai-review*.yml' + - 'docs/examples/ai-review-sandbox/**' + - '.github/workflows/*ai-review*.yml' + push: + branches: [feat/Ai-dispose, main] + paths: + - 'scripts/**' + - 'docs/examples/ai-review*.yml' + - 'docs/examples/ai-review-sandbox/**' + - '.github/workflows/*ai-review*.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: '3.11' + - name: Run unit tests + run: python -m unittest discover -s scripts/tests -v + - name: Simulate AI rounds and human reply permissions without GitHub accounts + run: python -m scripts.tests.simulate_ai_review_disposition >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 62f3e63..6ff6f98 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -57,16 +57,22 @@ force-push 移除修复提交后,Accepted 失效。Issue 关闭后,Deferred 4. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 5. 在目标分支的 ruleset / 分支保护中启用 [**Require conversation resolution before merging**](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-a-pull-request-before-merging),并保留人工 approval 要求。此项必须与 Required Status Check 同时配置;脚本不会修改仓库规则,也不会因未 resolved 而失败。 -PR opened/reopened/synchronize、目标分支变化和 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。普通聊天不会开启新审查轮次。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器,因此 fork PR 也可复查。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。 +PR opened/reopened/synchronize、目标分支变化和 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。普通聊天不会开启新审查轮次。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。本次验收范围为同仓库 PR / Issue,不要求 fork PR 或 Issue 转移场景。 本仓库 Issue closed/reopened/deleted/transferred 时,caller 使用显式的 `all-open-prs: true` 检查所有开放 PR,不维护 Issue 到 PR 的反向关联,也不把 Issue 编号当作 PR 编号。仍引用无效 Issue 的 Deferred 会阻断;其他 PR 按各自实时状态判断。一个 PR 失败不会跳过后续 PR,新建普通 Issue 不触发。 -Resolve/Unresolve 无需触发本 Check,也不需要额外发评论或手动复查;它们由 GitHub 原生 conversation resolution 规则处理。使用 `GITHUB_TOKEN` 发布的 Review、评论或 Issue 事件通常不会触发后续 Actions,应由对应流程显式 dispatch 复查,或用 App token 发布。 +Resolve/Unresolve 无需触发本 Check,也不需要额外发评论或手动复查;它们由 GitHub 原生 conversation resolution 规则处理。 + +使用 `GITHUB_TOKEN` 修改 Issue 不会自动启动 `issues` 监听。自动关闭 Issue 的接入示例见 [ai-review-close-issue.yml](examples/ai-review-close-issue.yml):关闭后 dispatch **同一份 caller**,设置 `all-open-prs=true`,由新的 caller 运行复查所有开放 PR。该自动化需要 `issues: write`、`actions: write`,仍使用自带 Token;无需额外钥匙或 Issue 到 PR 的反向关联。其他自动化修改 Issue、发布 Review 或评论后,也须显式触发复查。 + +手动 Run workflow 可填写正整数 `pr-number`;全仓复查则勾选 `all-open-prs` 并保持 PR 编号为 0。未指定有效目标会失败,不能意外退化为全仓扫描。手动编号经 JSON 数字转换后传给 reusable workflow。删除 Issue 的 HTTP 410 与不存在的 HTTP 404 均给出无效 Tracking 的具体提示,其余 API 错误仍保守阻断。 同一 PR 的新运行取消旧运行;Issue 全仓复查有独立并发组,仍按每个 PR 争取结果发布权。只部署一份 caller,按其运行编号及 attempt 判断新旧。B 接管后只认 B:B 运行中、失败或取消时均不回退到 A 的通过结果。旧 Check 改为带 superseded 后缀的历史名称,只有当前检查使用固定门禁名;最后写结果不设置名称,因此旧请求迟到也不能重新占用 B 的门禁名称。历史记录保留与否不影响 B 的判定。 通过前再次完整读取 PR 状态、目标分支、提交、Review 和评论,并清除缓存重新校验回复者权限及 Issue 有效性。数据变化或 API 错误不放行。补查使用 caller 的 Run workflow;重跑旧编号不能覆盖更新的运行编号。取消、超时或 Check 写入失败可能保留当前 in-progress 状态,需发起新检查。该方案是异步门禁,不提供不可删改的历史审计或 merge queue 合成 SHA 支持。 +不同分支可以指向同一 commit 并分别创建真实 PR。实测多 PR 共用 head 时 GitHub 门禁关联异常;当前每条开放 PR 应使用独立 head。对照测试中,给其中一条 PR 追加文件内容不变的 commit 后恢复正常;这不是脚本已支持共享 head 的证明。 + CLI(会写入指定 PR 的 Check): ```bash @@ -79,4 +85,6 @@ GH_TOKEN="" python scripts/check_ai_review_disposition.py \ 正式启用门禁前,在目标仓库验证:新轮开始阻断、完成后恢复;全部 dismissed 时允许有效旧依据兜底;Issue 关闭使 Deferred 失败、更新模板后恢复;B 失败不能被 A 的迟到成功覆盖,B 成功不被旧记录阻塞。还需验证本 Check 通过但线程未 resolved 时,GitHub 原生规则继续阻止合并;Resolve/Unresolve 只更新原生条件,无需重跑本 Check。 +测试夹具、隔离 ruleset 和运行步骤见 [隔离验收模板](examples/ai-review-sandbox/README.md),历史实测及模拟边界见 [验收记录](AI_REVIEW_DISPOSITION_TEST_REPORT.md)。离线模拟使用 `python -m scripts.tests.simulate_ai_review_disposition`,不会访问 GitHub 或冒充真实账号。 + 参考:[Actions 事件](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)、[Checks API](https://docs.github.com/en/rest/checks/runs)、[复用 workflow](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows)。 diff --git a/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md b/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md new file mode 100644 index 0000000..1db77f1 --- /dev/null +++ b/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md @@ -0,0 +1,125 @@ +# AI Review 验收与模拟记录 + +本次变更迁移了隔离测试材料,并修正手动编号、删除 Issue 的 HTTP 410 提示;新增自动关闭 Issue 后触发原 caller 的接入示例。 + +验证分为两类:离线模拟使用虚拟 Infiscale / Codex 与第二个人工账号,真实 API 实验使用明确标注的 GitHub Actions 测试审查者。两类都不冒充真实 Bot 已接入或真实第二账号已授权。 + +当前范围是同仓库 PR 与 Issue。fork PR、Issue 转移按用户使用范围排除,不作为本次接入前提。共享 head 多 PR 在真实 GitHub 中可以出现,现有实现的限制仍保留;使用独立 head 的 PR。 + +## 本次可复现检查 + +```bash +python -m unittest discover -s scripts/tests -v +python -m scripts.tests.simulate_ai_review_disposition +``` + +模拟涵盖:Infiscale 新轮、发布意见、零问题、dismissed 历史兜底;Codex 进行中/失败/完成;第二人工账号 write/admin/read/none;最终复核期间撤权;Bot 不得自行处理;Issue 关闭、删除和检查期间变更。模拟通过说明判定逻辑符合这些输入,不能证明真实 App 回调与账号授权。 + +测试模板及规则见 [隔离验收说明](examples/ai-review-sandbox/README.md)。下面保留对旧提交 `be25a22a1c39b9c64fe8931e858e29829be1ada5` 的历史记录;其中“本轮未修复”等措辞描述当时状态,本次新结果另行追加。 + +## 原候选版本的历史验收记录 + +日期:2026-10-26。仓库:[liaoxiang0304/VR_DexCopilot](https://github.com/liaoxiang0304/VR_DexCopilot)。 + +**结论:已经完成真实 Actions / Checks API / 合并门禁测试,但尚未全部验收通过,暂不建议直接推广。** + +共享脚本与 reusable workflow 均固定到候选提交 `be25a22a1c39b9c64fe8931e858e29829be1ada5`,无需合入公共 CI main。模拟审查者为真实的 `github-actions[bot]`,其评论均明确标注 SANDBOX FIXTURE;本次不声称 Infiscale / Codex 实际完成审查。 + +## 已验证的场景 + +| 场景 | 实际结果与证据 | +| --- | --- | +| 没有 AI 完成记录 | 创建 PR 自动失败,不能因零线程放行:[初次运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285069563) | +| 作者行内回复自动复查 | collector → workflow_run 成功:[自动运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285663160) | +| 手动触发 | 原版失败;测试仓库转换输入为数字后成功:[修正后](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285803976) | +| 普通后续讨论 | 会复查,但沿用有效完成记录和模板:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286031460) | +| 有效 Deferred / Issue 关闭 | 关闭后自动全仓复查,PR #3 失败、PR #4 仍被检查且通过;实际合并被拒绝:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286270592) | +| Issue 重开 | 未编辑 Deferred 也恢复通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286378424);该 sweep 的总状态失败是因为已有 PR #1 无完成记录,不能只看 workflow 总颜色 | +| Accepted 缺 Fix / Fix 被移出 PR | 均失败:[缺 Fix](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286513076)、[force-push 移除](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286847889);有效 Fix 在运行 15 曾通过 | +| resolved 且 outdated 线程 | 实际 GraphQL 状态均为 true;仍要求模板。删除唯一回复后失败,重新回复后通过:[删除](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40287573105)、[恢复](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40287616423) | +| B 处理中,A 曾成功 | 实验固定 Check 仍为 in_progress,实际合并返回 HTTP 405:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285932263) | +| B 失败,A 迟到写成功 | 保留 B 的失败,实际合并返回 HTTP 405:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285932263) | +| B 取消,A 迟到写成功 | 保留 B 的取消,实际合并返回 HTTP 405:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286136866) | +| B 成功,A 迟到写失败 | 保留 B 成功:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286025437);真实 [PR #4](https://github.com/liaoxiang0304/VR_DexCopilot/pull/4) 在两个 Required Checks 通过后合并成功 | + +A/B 实验通过待测 `current_check()` 对真实 Checks API 制造迟到写入,并用独立 Check 名 `AI Review / Disposition Integration Test` 验证。它验证 Check 改名、接管和真实合并阻断;不等同于覆盖 GitHub 全部调度竞态。 + +## 不依赖真实 AI 的补测 + +用户选择先完成其余测试,真实 Bot 验收标为待完成。下列均使用明确标注的 GitHub Actions 测试审查者,不冒充 Infiscale / Codex。 + +| 场景 | 实测结果 | +| --- | --- | +| Deferred 链接实际指向本仓库 PR | 拒绝通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289406119) | +| Deferred 链接指向本仓库不存在的 Issue | 拒绝通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289455526) | +| Deferred 链接指向本仓库已关闭 Issue | 拒绝通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289512716) | +| Bot 用有效模板回复自己的意见,作者未回复 | 仍为 Unaddressed:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289851068) | +| 编辑 Bot 原始意见,人工旧回复仍有效 | 无需重复确认:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289746270) | +| 删除一次性 Issue | 自动触发全仓复查并失败:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289979556);API 返回 HTTP 410,目前提示为通用 HTTPError | +| 首次验证 Issue 开放后立刻关闭它 | 最后复核重新读取,拒绝旧成功;真实 API 共读取 Issue 两次:[实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290499879) | +| 首次评估后立刻编辑原意见 | 第二次 PR 快照检测到变化并拒绝旧成功;重新检查后通过:[实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290629552) | +| 修改目标分支,再改回 | 两次均自动复查,无需强制 AI 重审:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40291961436) | +| PR 关闭后重开 | 自动复查:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40292010661) | +| 只改 PR 标题 | workflow 跳过评估,Check ID 保持不变:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40292060503) | + +最终复核实验使用同一个候选脚本,API 包装只在精确时间点对测试 Issue / Bot 自己的意见进行真实写入,既不伪造读取结果,也不修改候选评估逻辑。独立 Check `AI Review / Final Read Integration Test` 按预期失败,实验 job 因断言正确而成功;它不是 Required Check。 + +## 发现的问题 + +### 1. 手动 PR 编号类型错误,已仅在测试仓库修正 + +[原始失败运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285281539) 的注释为:`Unexpected value '3'`。PR 编号进入 reusable workflow 时仍为字符串,脚本根本没启动。 + +需要在公共 CI 的 `docs/examples/ai-review-disposition.yml` 同步这一行;公共 PR #24 本次尚未修改: + +```diff +- || inputs.pr-number ++ || fromJSON(inputs.pr-number || '0') +``` + +[测试仓库修复提交](https://github.com/liaoxiang0304/VR_DexCopilot/commit/9075f49c568aa79e98c2be6cad76bee669103535) 已实测成功。交付的本地测试包也已同步该修正,因此它含有这处尚未进入公共候选的 caller 修正。 + +### 2. 共享 head 多 PR 的关联限制已复现,尚未解决 + +原实测 [PR #6](https://github.com/liaoxiang0304/VR_DexCopilot/pull/6) 和 [PR #7](https://github.com/liaoxiang0304/VR_DexCopilot/pull/7) 共用 head `2db00048253c38e7090765bec363f07632ec1cdf`。只有 #6 有测试审查:脚本分别给出成功 / 失败,但两条 PR 的实际合并均被 GitHub 拒绝,提示 `2 of 2 required status checks are expected`。 + +补测给 #6 追加一个 **tree 完全不变** 的独立提交 `e5315a94450879e073ca7cc097d5fb9a63bfb861`。[重新运行实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40291018228) 后,浏览器确认两个 Required Checks 成功、合并按钮恢复可用。没有执行 #6 的合并。 + +因此独立 head 的对照恢复正常;共享 head 场景仍未支持,不能标为通过。当前 #6 已改为独立 head,原同 head 状态及 API 拒绝记录保存在测试证据中。 + +### 3. 自动化使用 GITHUB_TOKEN 关闭 Issue,不会自动触发 caller + +实测 [工作流关闭 Issue 的实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290499879) 后,正式 Check ID 仍为 `121464063640`,保持原成功状态;独立复核实验已能检测到关闭并失败。[主动触发正式检查](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290556150) 后,正式 Check 才失败。 + +这是 [GitHub 的事件抑制规则](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) 的实际影响。人工关闭 Issue 的自动复查已通过;现方案不能宣称覆盖所有自动化关闭来源。负责关闭 Issue 的 Actions 工作流需要主动调用全仓复查,例如 reusable workflow 的 `all-open-prs: true`;不需要 Issue 反查 PR。该接入补充本轮未写入公共 CI。 + +### 4. 删除 Issue 已阻断,错误提示仍可改进 + +一次性 [Issue #8](https://github.com/liaoxiang0304/VR_DexCopilot/issues/8) 确实被删除,GitHub REST 返回 HTTP 410。现脚本把它作为 API 错误保守阻断,未误放行;但用户只看到 `evaluation failed (HTTPError)`。可考虑把 410 与 404 一样归为无效 Tracking,从而给出清晰的处理提示。本轮未改候选脚本。 + +## 尚未验收与范围限制 + +- **真实 Bot 验收:待完成(按用户选择暂缓)**。包括实际开始/完成格式、零问题、新轮和 dismissed 历史兜底。 +- **需要第二个人工账号**:非作者 write/admin 回复、无权限人工回复、权限被撤回、最终权限复核竞态。Bot 回复被拒已验证,不能替代这些人工权限测试。尝试将 Bot 创建的测试 Issue 转成 PR 后,PR 作者仍是当前用户,因此没有将该尝试计为通过。 +- **需要另一授权测试仓库**:真实 fork PR、Issue 转移。当前授权仅限 VR_DexCopilot,未创建或写入其他仓库。 +- 外仓库链接的实测被自动审批拒绝,理由是此前限定只考虑本仓库;已移除该测试,未在评论里发布该外仓库链接。 +- 受控的 Issue 与意见变更竞态已实测;大规模分页及其余单元测试边界不代表都已现场执行。 + +## 当前现场 + +- [接入 PR #2](https://github.com/liaoxiang0304/VR_DexCopilot/pull/2) 和 [正常合并对照 PR #4](https://github.com/liaoxiang0304/VR_DexCopilot/pull/4) 已合并。 +- 一次性权限测试 [PR #10](https://github.com/liaoxiang0304/VR_DexCopilot/pull/10) 已关闭且未合并;[Issue #8](https://github.com/liaoxiang0304/VR_DexCopilot/issues/8) 为删除事件测试对象,已删除;[Issue #9](https://github.com/liaoxiang0304/VR_DexCopilot/issues/9) 已关闭。 +- [PR #3](https://github.com/liaoxiang0304/VR_DexCopilot/pull/3) 保留用于后续真实 Bot 验收;[Issue #5](https://github.com/liaoxiang0304/VR_DexCopilot/issues/5) 已关闭。 +- `AI_REVIEW_BOTS` 已从测试身份恢复为 `chatgpt-codex-connector[bot],infiscale-bot`,并通过 Issue 关闭事件重新检查开放 PR。真实 Bot 尚未完成时当前红色是预期行为。最新恢复复查为 [运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40292442890)。 +- `AI_REVIEW_SANDBOX=true` 保留,方便继续手动 A/B 实验;fixture / lab 都只用于本测试仓库。 +- [规则集](https://github.com/liaoxiang0304/VR_DexCopilot/rules/25862703) 仅约束 `test/ai-review-merge-target`,没有 bypass actor;同时要求正式 Check、实验 Check 和解决会话。`main` 未加入这些门禁。 +- 只新增测试工作流、验收文档和专用分支测试文件。原 `README.md`、`flexiv_team14.py` 的 blob SHA 均与测试前一致;既有 PR #1 的内容未改动,但全仓复查会给它增加检查结果。 + +验收依据为具体 Check 和实际合并 API 返回,不能把预期失败的 workflow 总颜色当成验收失败,也不能用实验 job 的绿色代替正式 Check。 + +## 参考 + +- [GitHub:Ruleset 参数与检查来源](https://docs.github.com/en/rest/repos/rules#create-a-repository-ruleset) +- [GitHub:GITHUB_TOKEN 产生事件的触发限制](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) + +补测不修改公共 CI PR #24;本次新增的 fixture / final-read workflow 只在测试仓库使用。 diff --git a/docs/examples/ai-review-close-issue.yml b/docs/examples/ai-review-close-issue.yml new file mode 100644 index 0000000..41c1342 --- /dev/null +++ b/docs/examples/ai-review-close-issue.yml @@ -0,0 +1,42 @@ +# Optional example for automation that closes Issues using GITHUB_TOKEN. +# Copy to the target repository; the normal caller must be on its default branch. +name: Close Issue and Recheck AI Dispositions + +on: + workflow_dispatch: + inputs: + issue-number: + description: 'Positive Issue number to close in this repository' + required: true + type: number + +permissions: + issues: write + actions: write + +jobs: + close-and-recheck: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Close the Issue and dispatch the existing caller + env: + GH_TOKEN: ${{ github.token }} + ISSUE_NUMBER: ${{ inputs.issue-number }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + [[ "$ISSUE_NUMBER" =~ ^[1-9][0-9]*$ ]] || { + echo "A positive integer Issue number is required" >&2 + exit 1 + } + is_pr=$(gh api "repos/$GITHUB_REPOSITORY/issues/$ISSUE_NUMBER" --jq 'has("pull_request")') + if [[ "$is_pr" == "true" ]]; then + echo "Use an Issue, not a pull request" >&2 + exit 1 + fi + gh api "repos/$GITHUB_REPOSITORY/issues/$ISSUE_NUMBER" \ + --method PATCH -f state=closed > /dev/null + # Issue events from GITHUB_TOKEN do not start Actions; dispatch does. + # Reuse the SAME caller so its run numbers still order newer results. + gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ + --ref "$DEFAULT_BRANCH" -f all-open-prs=true diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index c0adc3c..8ee53cc 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -15,9 +15,15 @@ on: workflow_dispatch: inputs: pr-number: - description: 'Positive PR number to recheck' - required: true + description: 'Positive PR number; leave 0 when rechecking all open PRs' + required: false type: number + default: 0 + all-open-prs: + description: 'Explicitly recheck all open PRs after automated Issue changes' + required: false + type: boolean + default: false permissions: contents: read @@ -29,6 +35,7 @@ jobs: disposition: if: >- ${{ github.event_name != 'issues' + && !(github.event_name == 'workflow_dispatch' && inputs.all-open-prs) && (github.event_name != 'issue_comment' || github.event.issue.pull_request) && (github.event_name != 'pull_request_target' || github.event.action != 'edited' || github.event.changes.base) }} @@ -38,14 +45,16 @@ jobs: pr-number: >- ${{ github.event.pull_request.number || github.event.issue.number - || inputs.pr-number + || fromJSON(inputs.pr-number || '0') || fromJSON(github.event.workflow_run.display_title || '0') }} # Set this repository/organization variable to exact bot logins. bot-logins: ${{ vars.AI_REVIEW_BOTS }} shared-ref: main issue-recheck: - if: ${{ github.event_name == 'issues' }} + if: >- + ${{ github.event_name == 'issues' + || (github.event_name == 'workflow_dispatch' && inputs.all-open-prs) }} uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main with: all-open-prs: true diff --git a/docs/examples/ai-review-sandbox/README.md b/docs/examples/ai-review-sandbox/README.md new file mode 100644 index 0000000..db6d216 --- /dev/null +++ b/docs/examples/ai-review-sandbox/README.md @@ -0,0 +1,69 @@ +# 隔离验收模板 + +模板只用于专用测试仓库,不会在公共 CI 仓库自动启用。历史实测和模拟范围见 [验收记录](../../AI_REVIEW_DISPOSITION_TEST_REPORT.md)。生产 caller 仍默认使用 `main`。 + +## 准备 + +1. 将上级目录的 `ai-review-disposition.yml`、`ai-review-events.yml` 复制到测试仓库 `.github/workflows/` 并提交默认分支。测试未合入 main 的候选时,把 caller 两处 workflow `uses` 和两处 `shared-ref` 同时改为 `feat/Ai-dispose`,或同一个候选 SHA。 +2. 将本目录三个 `.yml` 也复制到测试仓库 `.github/workflows/`。设置 Variable `AI_REVIEW_SANDBOX=true`;实验脚本的 `AI_REVIEW_TEST_REF` 默认 `feat/Ai-dispose`,指定提交时应与 caller 使用相同 SHA。 +3. 创建目标分支 `test/ai-review-merge-target`。测试 PR 来源分支以 `test/ai-review-e2e-` 开头,每条 PR 使用独立 head。 +4. 在测试 PR 新增 `.ai-review-sandbox/sample.py`,第 5 行须在 diff 中: + +```python +"""Disposable fixture; workflows never execute this PR file.""" + + +def sample(): + value = 1 + return value +``` + +设置 `AI_REVIEW_BOTS=github-actions[bot]`,运行 **AI Review Sandbox Fixture** 的 `create-review`,填写 PR 编号和 `with-finding=true`。这是真实 GitHub Actions 身份,评论明确标注 fixture,不冒充 Infiscale / Codex。其 Review 使用 `GITHUB_TOKEN`,需要手动运行正式 caller 检查该 PR;随后作者新增、编辑、删除模板回复将走真实事件链自动复查。 + +`reply` 用于验证 Bot 不能自行处理意见;`edit-root` 用于验证原意见编辑无需重复确认。`target-comment-id` 只接受该 fixture Bot 在所选 PR 上自己发布的根评论。 + +## 测试规则 + +先在健康 PR 上产生一次成功的正式 Check 和 B-success 实验 Check,再应用 `ruleset.json`: + +```bash +gh api repos/OWNER/TEST_REPO/rulesets --method POST \ + --input docs/examples/ai-review-sandbox/ruleset.json +``` + +JSON 仅约束 `test/ai-review-merge-target`,没有 bypass,要求正式 Check、A/B 实验 Check 和会话解决。它是服务器规则的配置模板,提交 Git 文件不会自动启用。不要将实验 Check 加入生产门禁,或把测试规则用于业务 main。 + +## 真实 API 实验 + +| 工作流 | 输入与用途 | 预期 | +| --- | --- | --- | +| AI Review Latest Result Lab | PR;B-success / B-failure / B-cancelled;暂停 0–60 秒 | B 处理中、失败、取消均阻止合并;A 的迟到结果不能覆盖 B | +| AI Review Final Read Lab | PR;开放 Issue;fixture 根评论 ID;issue-close / review-edit | 首次读取后真实修改数据,最后复核拒绝旧成功 | + +最终复核实验要求人工 Deferred 指向该 Issue,Issue 标题以 `[Sandbox disposable]` 开头。实验只编辑 fixture Bot 自己的意见或关闭测试 Issue;结束后 dispatch 正式 caller 全仓复查。 + +实验 job 绿色表示断言成立,其独立实验 Check 可能按预期红色或取消。最终复核实验的 Check 不是 Required Check。A/B 实验还需核对真实合并区,不能只看 API 断言。 + +## 自动关 Issue + +将上级目录 `ai-review-close-issue.yml` 复制到默认分支。让 Deferred 引用开放 Issue,再运行 **Close Issue and Recheck AI Dispositions**。应出现新的正式 caller `workflow_dispatch`,逐个检查开放 PR,使该 Deferred 失败。 + +其他使用 `GITHUB_TOKEN` 修改 Issue 的工作流也须在修改后触发同一 caller;负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 需要 `issues: write`: + +```bash +gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ + --ref "$DEFAULT_BRANCH" -f all-open-prs=true +``` + +无需额外 Token 或 Issue 到 PR 的反向关联。不要由另一工作流直接运行正式检查脚本或另建 caller:新旧结果按同一 caller 的运行编号排序。 + +## 离线模拟与范围 + +```bash +python -m unittest discover -s scripts/tests -v +python -m scripts.tests.simulate_ai_review_disposition +``` + +模拟使用合成的 AI/人工身份和权限响应,运行实际判定与末次复核逻辑,不需要真实账号或密钥。它能证明规则行为,不能证明 App 已接入或真实授权已生效。 + +本次范围为同仓库 PR / Issue,fork PR、Issue 转移不作为验收前提;跨仓库链接拒绝校验保留。结束后恢复真实 `AI_REVIEW_BOTS` 并重新检查,也可设 `AI_REVIEW_SANDBOX=false` 停用夹具。 diff --git a/docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml b/docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml new file mode 100644 index 0000000..88aed99 --- /dev/null +++ b/docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml @@ -0,0 +1,126 @@ +# Test-only controlled timing experiment; never a production required check. +name: AI Review Final Read Lab +on: + workflow_dispatch: + inputs: + pr-number: + description: 'Disposable test PR number' + type: number + required: true + issue-number: + description: 'Open disposable Issue currently referenced by Deferred' + type: number + required: true + root-comment-id: + description: 'Existing fixture bot root comment on that PR' + type: number + required: true + scenario: + description: 'Mutation immediately after the first external lookup' + type: choice + required: true + options: [issue-close, review-edit] +permissions: + actions: write + contents: read + pull-requests: write + issues: write + checks: write +jobs: + experiment: + if: ${{ vars.AI_REVIEW_SANDBOX == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + concurrency: + group: ai-review-final-read-lab-${{ github.repository }}-${{ inputs.pr-number }} + cancel-in-progress: false + steps: + - uses: actions/checkout@v4 + with: + repository: IS-Model-Framework/.github + ref: ${{ vars.AI_REVIEW_TEST_REF || 'feat/Ai-dispose' }} + path: .ci-shared + persist-credentials: false + sparse-checkout: scripts + - uses: actions/setup-python@v7 + with: + python-version: '3.11' + - name: Verify real final reads with a controlled concurrent mutation + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr-number }} + ISSUE_NUMBER: ${{ inputs.issue-number }} + ROOT_COMMENT_ID: ${{ inputs.root-comment-id }} + SCENARIO: ${{ inputs.scenario }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + python - <<'PY' + import os + import subprocess + import sys + from urllib.parse import quote + sys.path.insert(0, '.ci-shared') + from scripts import check_ai_review_disposition as checker + + repository = os.environ['GITHUB_REPOSITORY'] + number = int(os.environ['PR_NUMBER']) + issue_number = int(os.environ['ISSUE_NUMBER']) + root_id = int(os.environ['ROOT_COMMENT_ID']) + scenario = os.environ['SCENARIO'] + assert min(number, issue_number, root_id) > 0 + checker.CHECK_NAME = 'AI Review / Final Read Integration Test' + real = checker.GitHub(os.environ['GH_TOKEN']) + pr = real.request('GET', f'/repos/{repository}/pulls/{number}') + assert pr['state'] == 'open' and pr['head']['ref'].startswith('test/ai-review-e2e-') + assert pr['base']['ref'] == 'test/ai-review-merge-target' + issue_path = f'/repos/{repository}/issues/{issue_number}' + issue = real.request('GET', issue_path) + assert issue['state'] == 'open' and issue['title'].startswith('[Sandbox disposable]') + assert 'pull_request' not in issue + root_path = f'/repos/{repository}/pulls/comments/{root_id}' + root = real.request('GET', root_path) + assert root['user']['login'] == 'github-actions[bot]' + assert root['pull_request_url'] == f'https://api.github.com/repos/{repository}/pulls/{number}' + + class MutatingAPI(checker.GitHub): + lookups = 0 + def request(self, method, path, body=None): + result = super().request(method, path, body) + if method == 'GET' and path == issue_path: + self.lookups += 1 + if self.lookups == 1: + # Return the real open response read just before the mutation. + # The candidate itself must detect the change on its final read. + if scenario == 'issue-close': + super().request('PATCH', issue_path, {'state': 'closed'}) + elif scenario == 'review-edit': + super().request('PATCH', root_path, { + 'body': 'SANDBOX FIXTURE: changed during evaluation, run ' + + os.environ['GITHUB_RUN_ID'], + }) + else: + raise ValueError('Unknown scenario') + return result + + api = MutatingAPI(os.environ['GH_TOKEN']) + assert checker.check_pr(api, repository, number, {'github-actions[bot]'}) is False + name = quote(checker.CHECK_NAME, safe='') + checks = api.pages(f'/repos/{repository}/commits/{pr["head"]["sha"]}/check-runs' + f'?check_name={name}&filter=all', 'check_runs') + current = max(checks, key=lambda check: check['id']) + assert current['conclusion'] == 'failure' + if scenario == 'issue-close': + assert api.lookups == 2 + assert 'Tracking must reference' in current['output']['summary'] + else: + assert 'PR review data changed during evaluation' in current['output']['summary'] + print('PASS:', scenario, 'was detected; stale success was refused.') + with open(os.environ['GITHUB_STEP_SUMMARY'], 'a', encoding='utf-8') as report: + report.write(f'Controlled real-API final-read test passed: **{scenario}**.\n\n' + f'Issue lookups: {api.lookups}. Fixture Check deliberately failed.\n') + # Our own Issue mutation also uses GITHUB_TOKEN: refresh the real gate. + subprocess.run([ + 'gh', 'workflow', 'run', 'ai-review-disposition.yml', '--repo', repository, + '--ref', os.environ['DEFAULT_BRANCH'], '-f', 'all-open-prs=true', + ], check=True) + PY diff --git a/docs/examples/ai-review-sandbox/ai-review-fixture.yml b/docs/examples/ai-review-sandbox/ai-review-fixture.yml new file mode 100644 index 0000000..bffacd4 --- /dev/null +++ b/docs/examples/ai-review-sandbox/ai-review-fixture.yml @@ -0,0 +1,102 @@ +# Test-only actor. This is GitHub Actions, not Codex or Infiscale. +name: AI Review Sandbox Fixture +on: + workflow_dispatch: + inputs: + pr-number: + description: 'Disposable test PR number' + required: true + type: number + with-finding: + description: 'Create one inline finding to exercise disposition replies' + required: true + type: boolean + default: true + operation: + description: 'Explicit fixture action; never impersonates a human' + required: true + type: choice + default: create-review + options: [create-review, reply, edit-root] + target-comment-id: + description: 'Existing github-actions root comment ID for reply/edit' + required: false + type: number + default: 0 +permissions: + contents: read + pull-requests: write +jobs: + fixture: + if: ${{ vars.AI_REVIEW_SANDBOX == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Publish an explicitly labelled fixture review + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr-number }} + WITH_FINDING: ${{ inputs.with-finding }} + OPERATION: ${{ inputs.operation }} + TARGET_COMMENT_ID: ${{ inputs.target-comment-id }} + run: | + python - <<'PY' + import json + import os + from urllib.request import Request, urlopen + + repo = os.environ['GITHUB_REPOSITORY'] + number = int(os.environ['PR_NUMBER']) + if number <= 0: + raise ValueError('Authorized test repository and positive PR required') + + def api(path, body=None, method=None): + request = Request('https://api.github.com/repos/' + repo + path, + method=method or ('POST' if body is not None else 'GET'), + data=json.dumps(body).encode() if body is not None else None, + headers={'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'Content-Type': 'application/json'}) + with urlopen(request, timeout=30) as response: + return json.load(response) + + pr = api(f'/pulls/{number}') + if (pr['state'] != 'open' + or not pr['head']['ref'].startswith('test/ai-review-e2e-') + or pr['base']['ref'] != 'test/ai-review-merge-target'): + raise ValueError('Use only an open disposable fixture PR') + operation = os.environ['OPERATION'] + if operation in {'reply', 'edit-root'}: + target = int(os.environ['TARGET_COMMENT_ID']) + root = api(f'/pulls/comments/{target}') + if (root['user']['login'] != 'github-actions[bot]' + or root.get('in_reply_to_id') + or root['pull_request_url'] != f'https://api.github.com/repos/{repo}/pulls/{number}'): + raise ValueError('Use only this fixture bot\'s own root on the selected PR') + if operation == 'reply': + result = api(f'/pulls/{number}/comments/{target}/replies', { + 'body': 'Disposition: Rejected\nReason: SANDBOX bot reply must not satisfy a human response.', + }) + else: + result = api(f'/pulls/comments/{target}', { + 'body': 'SANDBOX FIXTURE: edited original finding. Existing human disposition ' + 'must remain valid; no repeated confirmation is required.', + }, method='PATCH') + print('Fixture action:', operation, result['html_url']) + raise SystemExit(0) + if operation != 'create-review': + raise ValueError('Unknown fixture operation') + review = { + 'commit_id': pr['head']['sha'], 'event': 'COMMENT', + 'body': 'SANDBOX FIXTURE: a GitHub Actions review for API/policy testing. ' + 'This is not an Infiscale or Codex review.', + } + if os.environ['WITH_FINDING'] == 'true': + review['comments'] = [{ + 'path': '.ai-review-sandbox/sample.py', 'line': 5, 'side': 'RIGHT', + 'body': 'SANDBOX FIXTURE: record an explicit disposition for this test value. ' + 'This is not a real AI finding.', + }] + created = api(f'/pulls/{number}/reviews', review) + print('Fixture review:', created['html_url']) + PY diff --git a/docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml b/docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml new file mode 100644 index 0000000..002c6d2 --- /dev/null +++ b/docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml @@ -0,0 +1,142 @@ +# Test-repository-only experiment. Never add this check to production rulesets. +name: AI Review Latest Result Lab + +on: + workflow_dispatch: + inputs: + pr-number: + description: 'Open test PR number in this test repository' + required: true + type: number + scenario: + description: 'The result that B must retain after A writes late' + required: true + type: choice + default: B-success + options: [B-success, B-failure, B-cancelled] + pause-seconds: + description: 'Pause with B pending so you can inspect the merge box (0-60)' + required: false + type: number + default: 15 + +permissions: + contents: read + pull-requests: read + checks: write + +jobs: + experiment: + if: ${{ vars.AI_REVIEW_SANDBOX == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + concurrency: + group: ai-review-latest-result-lab-${{ github.repository }}-${{ inputs.pr-number }} + cancel-in-progress: false + steps: + - name: Checkout the exact candidate scripts + uses: actions/checkout@v4 + with: + repository: IS-Model-Framework/.github + ref: ${{ vars.AI_REVIEW_TEST_REF || 'feat/Ai-dispose' }} + path: .ci-shared + persist-credentials: false + sparse-checkout: scripts + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.11' + - name: Exercise the real Checks API with a deliberately late A result + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr-number }} + SCENARIO: ${{ inputs.scenario }} + PAUSE_SECONDS: ${{ inputs.pause-seconds }} + run: | + python - <<'PY' + import os + import sys + import time + from urllib.parse import quote + + sys.path.insert(0, '.ci-shared') + from scripts import check_ai_review_disposition as checker + + # Isolate fixture checks from the real evaluator's required check. + checker.CHECK_NAME = 'AI Review / Disposition Integration Test' + api = checker.GitHub(os.environ['GH_TOKEN']) + repository = os.environ['GITHUB_REPOSITORY'] + number = int(os.environ['PR_NUMBER']) + pause = int(os.environ['PAUSE_SECONDS']) + if number <= 0 or not 0 <= pause <= 60: + raise ValueError('Positive PR number and pause between 0 and 60 required') + outcomes = { + 'B-success': ('success', 'failure'), + 'B-failure': ('failure', 'success'), + 'B-cancelled': ('cancelled', 'success'), + } + expected, late_result = outcomes[os.environ['SCENARIO']] + pr = api.request('GET', f'/repos/{repository}/pulls/{number}') + if (pr['state'] != 'open' + or not pr['head']['ref'].startswith('test/ai-review-e2e-') + or pr['base']['ref'] != 'test/ai-review-merge-target'): + raise ValueError('Use an open test PR') + head = pr['head']['sha'] + generation = int(os.environ['GITHUB_RUN_NUMBER']) + attempt = int(os.environ['GITHUB_RUN_ATTEMPT']) * 2 + + def create(attempt_number): + return api.request('POST', f'/repos/{repository}/check-runs', { + 'name': checker.CHECK_NAME, + 'head_sha': head, + 'status': 'in_progress', + 'external_id': f'ai-review-disposition:{number}:{generation}:{attempt_number}', + }) + + def finish(check, conclusion): + # As in production, finishing never sets the check's name. + api.request('PATCH', f"/repos/{repository}/check-runs/{check['id']}", { + 'status': 'completed', + 'conclusion': conclusion, + 'output': {'title': f'Lab result: {conclusion}', 'summary': 'Sandbox fixture check.'}, + }) + + def gate(): + name = quote(checker.CHECK_NAME, safe='') + checks = api.pages( + f'/repos/{repository}/commits/{head}/check-runs?check_name={name}&filter=all', + 'check_runs', + ) + return [c for c in checks if c['app']['id'] == newer['app']['id']] + + older = create(attempt - 1) + assert checker.current_check(api, repository, number, head, older) + finish(older, 'success') + newer = create(attempt) + assert checker.current_check(api, repository, number, head, newer) + checks = gate() + assert len(checks) == 1 and checks[0]['id'] == newer['id'] + assert checks[0]['status'] == 'in_progress' + print(f"B is pending for {pause}s. Inspect PR #{number}'s merge box now.", flush=True) + time.sleep(pause) + + finish(newer, expected) + # This deliberately bypasses A's final ownership test to simulate a request + # already sent before cancellation, but received after B's final result. + finish(older, late_result) + checks = gate() + assert len(checks) == 1 and checks[0]['id'] == newer['id'] + assert checks[0]['conclusion'] == expected + assert not checker.current_check(api, repository, number, head, older) + print(f"PASS: B remains {expected}; A's late {late_result} did not take over.") + with open(os.environ['GITHUB_STEP_SUMMARY'], 'a', encoding='utf-8') as report: + report.write( + f'## Latest-result experiment passed\n\n' + f'PR: {pr["html_url"]}\n\n' + f'Head: `{head}`\n\n' + f'Expected and actual required fixture check: **{expected}**.\n\n' + f'A wrote **{late_result}** after B. Only B retains the fixed check name.\n\n' + f'The experiment job succeeds when the assertions hold; ' + f'the fixture check itself intentionally reflects the selected B result.\n' + ) + PY diff --git a/docs/examples/ai-review-sandbox/ruleset.json b/docs/examples/ai-review-sandbox/ruleset.json new file mode 100644 index 0000000..52200b3 --- /dev/null +++ b/docs/examples/ai-review-sandbox/ruleset.json @@ -0,0 +1,42 @@ +{ + "name": "AI review sandbox only", + "target": "branch", + "enforcement": "active", + "bypass_actors": [], + "conditions": { + "ref_name": { + "include": [ + "refs/heads/test/ai-review-merge-target" + ], + "exclude": [] + } + }, + "rules": [ + { + "type": "pull_request", + "parameters": { + "dismiss_stale_reviews_on_push": false, + "require_code_owner_review": false, + "require_last_push_approval": false, + "required_approving_review_count": 0, + "required_review_thread_resolution": true + } + }, + { + "type": "required_status_checks", + "parameters": { + "strict_required_status_checks_policy": false, + "required_status_checks": [ + { + "context": "AI Review / Disposition Check", + "integration_id": 15368 + }, + { + "context": "AI Review / Disposition Integration Test", + "integration_id": 15368 + } + ] + } + } + ] +} diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 6fe9e0d..50e5eef 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -298,7 +298,10 @@ def evaluate(data, bots, authorized, tracking_valid): reason = "Fix must be a current PR commit SHA or its repository commit URL" elif not reason and status == "Deferred": if not tracking_valid(fields.get("tracking", "")): - reason = "Tracking must reference a readable, open issue in this repository" + reason = ( + "Tracking must reference an existing, readable, open issue in this " + "repository; deleted issues cannot be deferred" + ) findings.append({ "id": thread["id"], "url": root["url"], @@ -422,7 +425,7 @@ def tracking_valid(value): == f"https://api.github.com/repos/{repository}".lower() ) except HTTPError as error: - if error.code != 404: + if error.code not in {404, 410}: raise return False diff --git a/scripts/tests/simulate_ai_review_disposition.py b/scripts/tests/simulate_ai_review_disposition.py new file mode 100644 index 0000000..8b83ef9 --- /dev/null +++ b/scripts/tests/simulate_ai_review_disposition.py @@ -0,0 +1,147 @@ +"""Offline scenarios using synthetic actors and the real disposition checker.""" + +import copy +from urllib.error import HTTPError + +from scripts.tests.test_ai_review_disposition import ( + BOT, + CODEX, + CODEX_SUMMARY, + INFISCALE_COMPLETE, + INFISCALE_START, + ApiTests, + comment, + fixture, + result, +) +from scripts.check_ai_review_disposition import passed + + +def scenarios(): + """Yield names, actual outcomes, and independently specified expectations.""" + ai = fixture( + "Disposition: Rejected\nReason: Already handled", reviewer="infiscale-bot" + ) + ai["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} + ai["comments"] = [comment(INFISCALE_START, "infiscale-bot")] + yield ( + "Infiscale started; old review cannot finish new round", + passed(result(ai, {"infiscale-bot"})), + False, + ) + latest = {**ai["reviews"][0], "id": "new", "submittedAt": "2026-10-09T03:00:00Z"} + ai["reviews"].append(latest) + yield ( + "Infiscale publishes findings after start", + passed(result(ai, {"infiscale-bot"})), + True, + ) + latest["state"] = "DISMISSED" + yield ( + "Withdrawn round can use older valid review", + passed(result(ai, {"infiscale-bot"})), + True, + ) + ai["reviews"] = [latest] + yield ( + "All reviews dismissed without valid history", + passed(result(ai, {"infiscale-bot"})), + False, + ) + ai["threads"] = [] + ai["comments"].append( + comment(INFISCALE_COMPLETE, "infiscale-bot", "2026-10-09T04:00:00Z") + ) + yield ( + "Infiscale exact zero-finding completion", + passed(result(ai, {"infiscale-bot"})), + True, + ) + ai["comments"].append( + comment(INFISCALE_START, "infiscale-bot", "2026-10-09T05:00:00Z") + ) + yield ( + "Later Infiscale round requires new completion", + passed(result(ai, {"infiscale-bot"})), + False, + ) + + codex = fixture() + codex.update(threads=[], reviews=[]) + for label, status, expected in ( + ("in progress", "⏳ **In progress**", False), + ("failed", "⚠️ **Failed**", False), + ("completed", "✅ **Completed**", True), + ): + codex["comments"] = [ + comment(CODEX_SUMMARY.replace("✅ **Completed**", status), CODEX) + ] + codex["comments"][0]["author"] = { + "login": CODEX.removesuffix("[bot]"), + "__typename": "Bot", + } + yield "Codex " + label, passed(result(codex, {CODEX})), expected + + # check_pr() performs actual authorization and final-cache logic; only its API + # transport and snapshots are replaced. No GitHub credential/account is used. + harness = ApiTests() + for role, expected in ( + ("write", True), + ("admin", True), + ("read", False), + ("none", False), + ): + data = fixture("Disposition: Rejected\nReason: Second human account") + data["threads"][0]["comments"][-1]["author"]["login"] = "second-human" + _, ok = harness.run_check([data, copy.deepcopy(data)], {"permission": role}) + yield "Second human has " + role + " permission", ok, expected + data = fixture("Disposition: Rejected\nReason: Previously authorized") + data["threads"][0]["comments"][-1]["author"]["login"] = "second-human" + _, ok = harness.run_check( + [data, copy.deepcopy(data)], [{"permission": "write"}, {"permission": "read"}] + ) + yield "Second human loses write access during final check", ok, False + data = fixture("Disposition: Rejected\nReason: Bot cannot self-dispose") + data["threads"][0]["comments"][-1]["author"] = {"login": BOT, "__typename": "Bot"} + yield "Bot reply cannot replace a human disposition", passed(result(data)), False + + data = fixture( + "Disposition: Deferred\nReason: Follow up\nTracking: https://github.com/org/repo/issues/42" + ) + for label, lookup, expected in ( + ("open Issue", {"state": "open"}, True), + ("closed Issue", {"state": "closed"}, False), + ( + "deleted Issue", + HTTPError("https://api.github.com/issue", 410, "Gone", {}, None), + False, + ), + ( + "Issue closes during final check", + [{"state": "open"}, {"state": "closed"}], + False, + ), + ): + _, ok = harness.run_check([data, copy.deepcopy(data)], lookup) + yield label, ok, expected + + +def main(): + print("Simulation only: synthetic AI and human identities; no GitHub requests.\n") + print("| Scenario | Expected gate | Actual gate | Matches |") + print("| --- | --- | --- | --- |") + failures = 0 + count = 0 + for name, actual, expected in scenarios(): + failures += actual != expected + count += 1 + expected_gate = "pass" if expected else "block" + actual_gate = "pass" if actual else "block" + matches = "yes" if actual == expected else "NO" + print(f"| {name} | {expected_gate} | {actual_gate} | {matches} |") + print(f"\n{count - failures}/{count} scenarios matched expectations.") + return int(bool(failures)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 61079eb..583def4 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -893,7 +893,7 @@ def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): "Disposition: Deferred\nReason: Follow up\n" "Tracking: https://github.com/org/repo/issues/42" ) - for status in (404, 401, 403, 429, 500): + for status in (404, 410, 401, 403, 429, 500): with self.subTest(status=status): error = HTTPError("https://api.github.com/issue", status, "error", {}, None) calls, ok = self.run_check([data], error) @@ -901,6 +901,19 @@ def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + def test_deleted_issue_reports_invalid_tracking_instead_of_api_failure(self): + data = fixture( + "Disposition: Deferred\nReason: Follow up\n" + "Tracking: https://github.com/org/repo/issues/42" + ) + error = HTTPError("https://api.github.com/issue", 410, "Gone", {}, None) + calls, ok = self.run_check([data], error) + self.assertFalse(ok) + report = calls[-1].args[2]["output"]["summary"] + self.assertIn("[Deferred]", report) + self.assertIn("deleted issues", report) + self.assertNotIn("evaluation failed", report) + def test_only_canonical_github_issue_urls_are_queried(self): for url in ( "https://jira.test/browse/PROJ-42", diff --git a/scripts/tests/test_ai_review_scenarios.py b/scripts/tests/test_ai_review_scenarios.py new file mode 100644 index 0000000..6d66f1a --- /dev/null +++ b/scripts/tests/test_ai_review_scenarios.py @@ -0,0 +1,10 @@ +import unittest + +from scripts.tests.simulate_ai_review_disposition import scenarios + + +class ScenarioTests(unittest.TestCase): + def test_simulated_bot_rounds_and_second_human_permissions(self): + for name, actual, expected in scenarios(): + with self.subTest(scenario=name): + self.assertEqual(actual, expected) From ea4e503a91a039debb47160d3a8bac6a67736842 Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:34:38 +0800 Subject: [PATCH 14/21] docs[ci]: record migrated AI review gate acceptance results --- docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md b/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md index 1db77f1..90198d5 100644 --- a/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md +++ b/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md @@ -17,6 +17,28 @@ python -m scripts.tests.simulate_ai_review_disposition 测试模板及规则见 [隔离验收说明](examples/ai-review-sandbox/README.md)。下面保留对旧提交 `be25a22a1c39b9c64fe8931e858e29829be1ada5` 的历史记录;其中“本轮未修复”等措辞描述当时状态,本次新结果另行追加。 +## 本次修复的实测结果 + +共享候选:`71b6c20bfd6d1d7807eedd7107e922efd239db4a`,分支 `feat/Ai-dispose`。本次只迁移源码与可复制的规则模板,未给公共 CI 仓库自动启用测试门禁。 + +| 检查 | 结果与证据 | +| --- | --- | +| 单元测试与模拟 | Python 3.11:96 项测试通过;Infiscale / Codex / 第二人工账号的 19 个合成场景符合预期;[GitHub Actions](https://github.com/IS-Model-Framework/.github/actions/runs/40305981879) | +| 自动关闭 Issue 的接入 | [关闭工作流](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306714886) 使用 GITHUB_TOKEN 成功关闭测试 Issue,并 dispatch 原 caller;[caller](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306733764) 自动将 Deferred 从成功改为失败 | +| 关闭 Issue 的参数防护 | [负例运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40308211445) 按预期拒绝 PR 编号,测试 PR #3 保持开放,未误关闭 PR | +| 全仓复查不会提前退出 | 同一 caller 运行 51 中 PR #3 失败,PR #6 仍被检查并通过;复用原 caller 的运行编号,旧成功不能夺回结果 | +| 手动编号与布尔输入 | [运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306831237) 成功接收数字转换后的 PR 编号;显式 `all-open-prs=false` 只检查该 PR,其他 PR 的 Check ID 未变化 | +| 已删除 Issue HTTP 410 | 对同一个已删除 Issue #8,Check 给出带 Deferred 链接的 Tracking 错误,并说明已删除 Issue 无法 Deferred;不再显示通用 evaluation failed | +| 迁移后的最终复核夹具 | [实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307014684) 检测 Issue 在检查期间关闭;实验结束自动 dispatch [原 caller](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307047812) 刷新正式门禁 | +| 迁移后的 Bot 夹具 | [实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307186703) 仅编辑所选 PR 中自己发布的意见;已有授权人工回复继续有效 | +| 迁移后的 A/B 夹具 | [B-success 实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307269178) 使用新候选脚本,通过迟到写入断言 | + +Ruff 检查和格式检查、actionlint、三个夹具的 Python 语法检查均通过。结束后已恢复真实 `AI_REVIEW_BOTS`,并通过原 caller 全仓复查撤掉测试身份的成功结果;当前等待真实 AI 完成而失败是预期状态。 + +自动化须采用新的关闭示例,或在自己的 Issue 修改步骤后追加 dispatch;GitHub 不会替未接入的任意工作流补发被 GITHUB_TOKEN 抑制的事件。调用入口使用自带 Token 的 `actions: write`,无需额外密钥。 + +共享 head 多 PR 的限制仍然存在;两个不同分支指向同一 commit 时能在真实 GitHub 创建多个 PR,本次未把该限制伪称为已修复。真实 Bot App 接入和第二个人工账号的真实授权仍待现场验收;其判定逻辑已有离线模拟。fork PR、Issue 转移按当前使用范围排除。 + ## 原候选版本的历史验收记录 日期:2026-10-26。仓库:[liaoxiang0304/VR_DexCopilot](https://github.com/liaoxiang0304/VR_DexCopilot)。 From a3d5881e2c73bd526bbb373792f2c3bd8a65a96e Mon Sep 17 00:00:00 2001 From: Xiao Yu <115685713+liaoxiang0304@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:09:44 +0800 Subject: [PATCH 15/21] refactor[ci]: simplify AI review checks and remove sandbox duplication --- .../workflows/test-ai-review-disposition.yml | 10 -- docs/AI_REVIEW_DISPOSITION.md | 102 +++++------- docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md | 147 ------------------ docs/examples/ai-review-disposition.yml | 19 +-- docs/examples/ai-review-sandbox/README.md | 69 -------- .../ai-review-final-read-lab.yml | 126 --------------- .../ai-review-sandbox/ai-review-fixture.yml | 102 ------------ .../ai-review-latest-result-lab.yml | 142 ----------------- docs/examples/ai-review-sandbox/ruleset.json | 42 ----- scripts/check_ai_review_disposition.py | 20 +-- .../tests/simulate_ai_review_disposition.py | 147 ------------------ scripts/tests/test_ai_review_disposition.py | 84 ++++------ scripts/tests/test_ai_review_scenarios.py | 10 -- 13 files changed, 80 insertions(+), 940 deletions(-) delete mode 100644 docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md delete mode 100644 docs/examples/ai-review-sandbox/README.md delete mode 100644 docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml delete mode 100644 docs/examples/ai-review-sandbox/ai-review-fixture.yml delete mode 100644 docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml delete mode 100644 docs/examples/ai-review-sandbox/ruleset.json delete mode 100644 scripts/tests/simulate_ai_review_disposition.py delete mode 100644 scripts/tests/test_ai_review_scenarios.py diff --git a/.github/workflows/test-ai-review-disposition.yml b/.github/workflows/test-ai-review-disposition.yml index 7797c90..0ea29f9 100644 --- a/.github/workflows/test-ai-review-disposition.yml +++ b/.github/workflows/test-ai-review-disposition.yml @@ -5,14 +5,6 @@ on: paths: - 'scripts/**' - 'docs/examples/ai-review*.yml' - - 'docs/examples/ai-review-sandbox/**' - - '.github/workflows/*ai-review*.yml' - push: - branches: [feat/Ai-dispose, main] - paths: - - 'scripts/**' - - 'docs/examples/ai-review*.yml' - - 'docs/examples/ai-review-sandbox/**' - '.github/workflows/*ai-review*.yml' workflow_dispatch: @@ -32,5 +24,3 @@ jobs: python-version: '3.11' - name: Run unit tests run: python -m unittest discover -s scripts/tests -v - - name: Simulate AI rounds and human reply permissions without GitHub accounts - run: python -m scripts.tests.simulate_ai_review_disposition >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 6ff6f98..37c4153 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -1,90 +1,66 @@ # AI Review / Disposition Check -合并门禁分工:本 Check 验证每个指定 AI 按下述轮次规则完成审查,以及 AI 和人工 reviewer 的每条行内线程都有有效模板回复;GitHub 原生的 **Require conversation resolution before merging** 规则负责要求讨论线程全部 resolved。两项都满足才能合并,无需采纳所有意见,也不代替人工 approval。 - -## 检查规则 - -- 默认明确指定一个 PR;closed/merged PR 跳过。只有显式的 `--all-open-prs` 才扫描本仓库全部开放 PR。Check 写入各 PR 的最新 head commit。 -- `AI_REVIEW_BOTS` 是必填的逗号分隔 login 列表,每个账号都必须完成审查。按 login 精确匹配,忽略大小写;GraphQL `Bot` login 缺少 `[bot]` 后缀时补齐,普通 `User` 不补。 -- 完成依据是该 Bot 发布的 `COMMENTED`、`APPROVED` 或 `CHANGES_REQUESTED` Review,或下表中的成功结束评论。`PENDING`、`DISMISSED`、开始/失败/配额不足提示本身不算完成。 -- 每个 AI 单独按开始消息及时间划分轮次,同一 AI 在同一 PR 上的轮次不得重叠。新一轮开始或出现更新的 pending / 进行中状态后,旧结果不能提前放行。没有开始记录的历史数据,兼容已有的已发布 Review 或成功结束评论。 -- 本轮发布的 Review 全部被 dismissed 后,本轮作废,允许更早的有效 Review 或成功摘要兜底;没有有效依据则阻断。随后又开始新一轮时,仍须等待该轮完成。 -- 审查完成不绑定当前 head,修复后 push 无需强制重审;Accepted 的修复提交仍须属于当前 PR。 -- 检查指定 AI 和 PR 作者之外的人工账号创建的全部已发布 inline threads,包括 outdated 和 resolved threads。PR 作者自己的人工线程、未配置 Bot 的线程、PR 顶层评论和 Review 总评不计为待处理线程;pending review 不计入。配置的 AI 即使是 `User` 或 PR 作者,仍按 AI 处理。 -- 模板回复者须为 PR 作者或当前具有仓库写权限的人工账号;Bot 和配置的 AI 服务账号不能自行处理意见。组织成员身份本身不代表写权限。 -- 采用编辑时间最新的明确模板回复,同一时间取 thread 中更后的回复;新的无效模板会替代旧模板,普通讨论不会。AI/人工使用相同规则,后续讨论或原始意见编辑不额外要求重复确认;新问题应新开线程。 -- 本 Check 只验证每个纳入检查的线程有有效回复,不读取或判断 resolved 状态。仅 resolved、仅回复 “done”,或在 PR 总结中统一回答均不能通过。工具不自动回复或 resolve。 -- 有效回复可以让本 Check 在未 resolved 时通过;GitHub 原生 conversation resolution 规则继续阻止合并。点击 Resolve/Unresolve 后,GitHub 更新原生合并条件,无需为了该状态重跑本 Check。原生规则覆盖所有代码讨论,范围可能比本 Check 筛选的线程更广。 - -| Bot login | 开始与完成依据 | -| --- | --- | -| `infiscale-bot` | 首行 `收到,开始 review`(允许前置 👀)为开始;之后有已发布 Review,或去除首尾空白后全文为 `未发现本次 PR 引入的新问题。LGTM!`,视为完成 | -| `chatgpt-codex-connector[bot]` | 自带摘要以 `` 开头,采用 `Code Review` 行自己的状态和时间;最新状态须为 `✅ **Completed**`,进行中或失败不能用旧 Review 提前放行 | +通过条件:每个指定 AI 完成审查,且应处理的行内线程都有有效回复。GitHub 原生 **Require conversation resolution before merging** 负责要求线程 resolved;人工 approval 单独保留。检查器不执行 PR 代码,也不自动回复或 resolve。 + +## 审查与回复规则 -仅匹配相应 Bot 发布的 PR 顶层评论;人工引用、行内回复、Security Review 完成均不能作为完成依据。整条摘要的编辑时间不能刷新旧的 Code Review 完成时间。infiscale 的判定以其一轮 Review 几乎同时发布的行为约定为前提;CI 不修改 Bot,也不额外要求人工确认审查结束。 +- `AI_REVIEW_BOTS` 必填,逗号分隔精确 login,忽略大小写;每个账号分别判定。GraphQL Bot login 缺少 `[bot]` 时补齐。 +- 已发布的 `COMMENTED`、`APPROVED`、`CHANGES_REQUESTED` Review 或下表成功摘要可证明完成。新开始消息、更新的 pending / 进行中状态使旧结果不能提前放行。同一 AI 的轮次不得重叠;新 commit 本身不强制重审。 +- 本轮全部 Review 被 dismissed 后,本轮失效,可用更早有效 Review 或成功摘要兜底;没有依据则阻断。随后新一轮仍须重新完成。 +- 指定 AI、PR 作者之外的人工 reviewer 创建的 inline threads 均须处理,包括 outdated / resolved。顶层评论、Review 总评、未发布的 pending 意见、作者自己的人工线程和未配置 Bot 的线程不作为处理目标。 +- 回复须来自 PR 作者或当前有 write/admin 权限的人工账号;AI 账号和 Bot 不能自行处理。采用编辑时间最新的明确模板,同一时间取更后的回复;新无效模板会替代旧模板。普通讨论、原意见编辑不要求重复确认,新问题应另开线程。 -## 回复模板 +| AI | 开始与完成依据(仅接受相应账号的 PR 顶层评论) | +| --- | --- | +| `infiscale-bot` | 首行 `收到,开始 review`(允许前置 👀)为开始;之后发布 Review 或全文为 `未发现本次 PR 引入的新问题。LGTM!` 即完成。前提是一轮 Review 几乎同时发布 | +| `chatgpt-codex-connector[bot]` | 摘要以 `` 开头;取 Code Review 行自己的状态与时间,须为 `✅ **Completed**`。进行中、失败或 Security Review 更新不能刷新旧完成记录 | -直接在对应 inline thread 中发送普通文本。第一行必须为 `Disposition: ...`;每个字段一行,允许空行及字段名/状态大小写变化,不接受引用、代码块、重复字段或额外字段。 +在对应线程发送普通文本,每个字段一行;字段名和状态不区分大小写,允许空行,不接受引用、代码块、重复或未知字段: ```text Disposition: Accepted Reason: 已修复边界判断。 -Fix: https://github.com/IS-Model-Framework/example/commit/0123456789abcdef0123456789abcdef01234567 -Tracking: N/A +Fix: <当前 PR 中的完整 40 位 commit SHA> ``` -| Disposition | 必填证据(所有状态都须有一行非空 `Reason`) | +| Disposition | 必填内容(所有状态均须非空 Reason) | | --- | --- | -| Accepted | `Fix` 为完整 40 位 SHA,或当前仓库的标准 commit 链接;提交必须仍在当前 PR 的 commits 中 | -| Rejected | 拒绝理由 | -| Invalid | 误报理由 | -| Deferred | `Tracking` 为当前仓库的 GitHub Issue 完整链接;API 确认该 Issue 存在、可读、仍开放且不是 PR | - -不适用的 `Fix` / `Tracking` 可省略或填 `N/A`。commit 链接仅接受 `https://github.com/owner/repo/commit/<40位SHA>`,Issue 链接仅接受 `https://github.com/owner/repo/issues/<正整数>`,均不接受查询参数或锚点。两种链接均限定当前仓库;跨仓库 Issue 在请求前拒绝,转移后的重定向也不能绕过仓库校验。只使用目标仓库的 `GITHUB_TOKEN`,无需额外钥匙。 - -force-push 移除修复提交后,Accepted 失效。Issue 关闭后,Deferred 失效,需要作者新增或编辑有效处理回复,例如改为 Accepted 并提供当前 PR 的修复 commit,或改为 Rejected 并说明理由。工具不会自动替作者修改模板。 - -工具验证引用有效,不判断理由是否充分、提交是否真正修复问题或延期是否合理;这些由人工审查确认。 +| Accepted | Fix 为完整 40 位 SHA,或本仓库标准 commit URL;提交必须仍属于当前 PR | +| Rejected / Invalid | 拒绝或误报理由 | +| Deferred | Tracking 为本仓库真实、可读且开放的 Issue URL,不能是 PR | -## CI 接入 +不适用的 Fix / Tracking 可省略或填 `N/A`。只接受 `https://github.com/owner/repo/commit/`、`https://github.com/owner/repo/issues/<正整数>`,不接受查询参数、锚点或跨仓库链接。转移重定向不能绕过仓库限制。force-push 移除修复提交、Issue 关闭或删除均使相应回复失效;作者需更新为有效回复。检查器不判断理由是否充分、commit 是否真正修复或延期是否合理。 -本组织有共享 Python CI 和独立 CI;本检查通过独立 caller 接入,保持现有测试及 `CI Result` 不变。组织 `.github` 仓库的 workflow 不会自动在其他仓库运行。 +## 接入 -1. 将 [ai-review-events.yml](examples/ai-review-events.yml) 和 [ai-review-disposition.yml](examples/ai-review-disposition.yml) 复制到目标仓库 `.github/workflows/` 并合入默认分支。 -2. 设置组织/仓库 Variable `AI_REVIEW_BOTS`,如 `chatgpt-codex-connector[bot],infiscale-bot`。空值会报错,不提供隐式默认 Bot。 -3. caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`;不执行或检出 PR 代码。 -4. 首次运行后,将脚本发布的 **`AI Review / Disposition Check`** 加入组织/仓库 ruleset 的 Required Status Checks,来源选 GitHub Actions。不要选择 Actions job 的成功状态,事件的 `GITHUB_SHA` 不一定是 PR head。 -5. 在目标分支的 ruleset / 分支保护中启用 [**Require conversation resolution before merging**](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-a-pull-request-before-merging),并保留人工 approval 要求。此项必须与 Required Status Check 同时配置;脚本不会修改仓库规则,也不会因未 resolved 而失败。 +1. 将 [caller](examples/ai-review-disposition.yml) 和 [事件收集器](examples/ai-review-events.yml) 复制到目标仓库 `.github/workflows/`,合入默认分支。 +2. 设置 Variable `AI_REVIEW_BOTS`,例如 `chatgpt-codex-connector[bot],infiscale-bot`。caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。 +3. 首次运行后,将脚本发布的 **AI Review / Disposition Check** 设为 Required Status Check,来源 GitHub Actions;不要选择 Actions job 的状态,其 SHA 不一定是 PR head。 +4. 同时启用 **Require conversation resolution before merging** 并保留人工 approval。Resolve/Unresolve 由 GitHub 原生规则处理,不需额外运行本检查。 -PR opened/reopened/synchronize、目标分支变化和 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。普通聊天不会开启新审查轮次。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限 collector,再通过默认分支的 `workflow_run` 触发检查器。collector 的 `run-name` 必须保持为 PR 编号;该值仅用于路由,判定始终重新读取实时 API,不接受 collector 的代码、artifact 或审查结论。本次验收范围为同仓库 PR / Issue,不要求 fork PR 或 Issue 转移场景。 +PR opened/reopened/synchronize、目标分支及 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限收集器,再由默认分支的 workflow_run 启动可信检查器。收集器的 run-name 保持 PR 编号,不传入代码或审查结论。 -本仓库 Issue closed/reopened/deleted/transferred 时,caller 使用显式的 `all-open-prs: true` 检查所有开放 PR,不维护 Issue 到 PR 的反向关联,也不把 Issue 编号当作 PR 编号。仍引用无效 Issue 的 Deferred 会阻断;其他 PR 按各自实时状态判断。一个 PR 失败不会跳过后续 PR,新建普通 Issue 不触发。 +本仓库 Issue closed/reopened/deleted/transferred 时复查全部开放 PR,不维护 Issue → PR 反向关联;一个 PR 失败不会跳过后续 PR。新建普通 Issue 不触发。 -Resolve/Unresolve 无需触发本 Check,也不需要额外发评论或手动复查;它们由 GitHub 原生 conversation resolution 规则处理。 +### 自动化修改 Issue -使用 `GITHUB_TOKEN` 修改 Issue 不会自动启动 `issues` 监听。自动关闭 Issue 的接入示例见 [ai-review-close-issue.yml](examples/ai-review-close-issue.yml):关闭后 dispatch **同一份 caller**,设置 `all-open-prs=true`,由新的 caller 运行复查所有开放 PR。该自动化需要 `issues: write`、`actions: write`,仍使用自带 Token;无需额外钥匙或 Issue 到 PR 的反向关联。其他自动化修改 Issue、发布 Review 或评论后,也须显式触发复查。 +GitHub 不会因 `GITHUB_TOKEN` 修改 Issue 自动启动后续 Actions。使用 [关闭 Issue 并复查的示例](examples/ai-review-close-issue.yml),或在已有自动化修改后 dispatch **同一份 caller**: -手动 Run workflow 可填写正整数 `pr-number`;全仓复查则勾选 `all-open-prs` 并保持 PR 编号为 0。未指定有效目标会失败,不能意外退化为全仓扫描。手动编号经 JSON 数字转换后传给 reusable workflow。删除 Issue 的 HTTP 410 与不存在的 HTTP 404 均给出无效 Tracking 的具体提示,其余 API 错误仍保守阻断。 - -同一 PR 的新运行取消旧运行;Issue 全仓复查有独立并发组,仍按每个 PR 争取结果发布权。只部署一份 caller,按其运行编号及 attempt 判断新旧。B 接管后只认 B:B 运行中、失败或取消时均不回退到 A 的通过结果。旧 Check 改为带 superseded 后缀的历史名称,只有当前检查使用固定门禁名;最后写结果不设置名称,因此旧请求迟到也不能重新占用 B 的门禁名称。历史记录保留与否不影响 B 的判定。 - -通过前再次完整读取 PR 状态、目标分支、提交、Review 和评论,并清除缓存重新校验回复者权限及 Issue 有效性。数据变化或 API 错误不放行。补查使用 caller 的 Run workflow;重跑旧编号不能覆盖更新的运行编号。取消、超时或 Check 写入失败可能保留当前 in-progress 状态,需发起新检查。该方案是异步门禁,不提供不可删改的历史审计或 merge queue 合成 SHA 支持。 +```bash +gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ + --ref "$DEFAULT_BRANCH" -f all-open-prs=true +``` -不同分支可以指向同一 commit 并分别创建真实 PR。实测多 PR 共用 head 时 GitHub 门禁关联异常;当前每条开放 PR 应使用独立 head。对照测试中,给其中一条 PR 追加文件内容不变的 commit 后恢复正常;这不是脚本已支持共享 head 的证明。 +DEFAULT_BRANCH 为仓库默认分支,负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 另需 `issues: write`。无需额外 Token;其他自动化发布 Review / 评论后同样须主动复查。不要由另一工作流直接运行正式检查脚本,结果顺序依赖同一 caller 的运行编号。 -CLI(会写入指定 PR 的 Check): +手动检查填写正整数 pr-number;全仓复查勾选 all-open-prs、保持编号 0。默认不会隐式全仓扫描。CI 始终实时读取 PR 并将 Check 写入最新 head;通过前再次读取数据,清缓存复核权限和 Issue 状态。数据变化或 API 错误不放行,Issue 的 404/410 会给出具体 Tracking 提示。 -```bash -GH_TOKEN="" python scripts/check_ai_review_disposition.py \ - --repository IS-Model-Framework/example --pr-number 128 \ - --bots 'chatgpt-codex-connector[bot],infiscale-bot' -``` +同一 PR 的新运行取消旧运行;全仓复查有独立并发组。B 接管后只认 B,运行中、失败或取消均不回退 A 的成功;旧 Check 改名保留,迟到结果不能恢复旧门禁名称。补查使用 Run workflow,重跑旧编号不能覆盖更新编号;读取/发布失败或遗留 in-progress 时发起新检查。 -仅支持 GitHub.com。退出码:0 通过、closed PR 跳过或已被更新检查取代,1 未通过,2 参数错误或未捕获的执行错误。全仓复查使用 `--all-open-prs` 替代 `--pr-number`,逐一处理全部开放 PR 并汇总退出码。验证:`python -m unittest discover -s scripts/tests -v`。 +## 验证与边界 -正式启用门禁前,在目标仓库验证:新轮开始阻断、完成后恢复;全部 dismissed 时允许有效旧依据兜底;Issue 关闭使 Deferred 失败、更新模板后恢复;B 失败不能被 A 的迟到成功覆盖,B 成功不被旧记录阻塞。还需验证本 Check 通过但线程未 resolved 时,GitHub 原生规则继续阻止合并;Resolve/Unresolve 只更新原生条件,无需重跑本 Check。 +运行 `python -m unittest discover -s scripts/tests -v`。主测试包含 AI 轮次、第二人工账号权限/撤权、分页、最终复核和 A/B 迟到写入模拟,无需真实账号或 Token。真实 Bot 接入仍须现场验证;不能把模拟当成实际授权已生效。 -测试夹具、隔离 ruleset 和运行步骤见 [隔离验收模板](examples/ai-review-sandbox/README.md),历史实测及模拟边界见 [验收记录](AI_REVIEW_DISPOSITION_TEST_REPORT.md)。离线模拟使用 `python -m scripts.tests.simulate_ai_review_disposition`,不会访问 GitHub 或冒充真实账号。 +自动关 Issue 的 [触发工作流](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306714886) 和 [后续复查](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306733764) 已在隔离仓库实测。一次性实验、规则配置和历史结果保留在[测试仓库](https://github.com/liaoxiang0304/VR_DexCopilot),不作为生产接入文件。 -参考:[Actions 事件](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)、[Checks API](https://docs.github.com/en/rest/checks/runs)、[复用 workflow](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows)。 +仅支持 GitHub.com、同仓库 PR/Issue;fork PR、Issue 转移不作为本次验收前提。多 PR 共用同一 head 存在 GitHub 门禁关联限制,各 PR 应使用独立 head。不支持 merge queue 合成 SHA 或不可删改的历史审计。 diff --git a/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md b/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md deleted file mode 100644 index 90198d5..0000000 --- a/docs/AI_REVIEW_DISPOSITION_TEST_REPORT.md +++ /dev/null @@ -1,147 +0,0 @@ -# AI Review 验收与模拟记录 - -本次变更迁移了隔离测试材料,并修正手动编号、删除 Issue 的 HTTP 410 提示;新增自动关闭 Issue 后触发原 caller 的接入示例。 - -验证分为两类:离线模拟使用虚拟 Infiscale / Codex 与第二个人工账号,真实 API 实验使用明确标注的 GitHub Actions 测试审查者。两类都不冒充真实 Bot 已接入或真实第二账号已授权。 - -当前范围是同仓库 PR 与 Issue。fork PR、Issue 转移按用户使用范围排除,不作为本次接入前提。共享 head 多 PR 在真实 GitHub 中可以出现,现有实现的限制仍保留;使用独立 head 的 PR。 - -## 本次可复现检查 - -```bash -python -m unittest discover -s scripts/tests -v -python -m scripts.tests.simulate_ai_review_disposition -``` - -模拟涵盖:Infiscale 新轮、发布意见、零问题、dismissed 历史兜底;Codex 进行中/失败/完成;第二人工账号 write/admin/read/none;最终复核期间撤权;Bot 不得自行处理;Issue 关闭、删除和检查期间变更。模拟通过说明判定逻辑符合这些输入,不能证明真实 App 回调与账号授权。 - -测试模板及规则见 [隔离验收说明](examples/ai-review-sandbox/README.md)。下面保留对旧提交 `be25a22a1c39b9c64fe8931e858e29829be1ada5` 的历史记录;其中“本轮未修复”等措辞描述当时状态,本次新结果另行追加。 - -## 本次修复的实测结果 - -共享候选:`71b6c20bfd6d1d7807eedd7107e922efd239db4a`,分支 `feat/Ai-dispose`。本次只迁移源码与可复制的规则模板,未给公共 CI 仓库自动启用测试门禁。 - -| 检查 | 结果与证据 | -| --- | --- | -| 单元测试与模拟 | Python 3.11:96 项测试通过;Infiscale / Codex / 第二人工账号的 19 个合成场景符合预期;[GitHub Actions](https://github.com/IS-Model-Framework/.github/actions/runs/40305981879) | -| 自动关闭 Issue 的接入 | [关闭工作流](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306714886) 使用 GITHUB_TOKEN 成功关闭测试 Issue,并 dispatch 原 caller;[caller](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306733764) 自动将 Deferred 从成功改为失败 | -| 关闭 Issue 的参数防护 | [负例运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40308211445) 按预期拒绝 PR 编号,测试 PR #3 保持开放,未误关闭 PR | -| 全仓复查不会提前退出 | 同一 caller 运行 51 中 PR #3 失败,PR #6 仍被检查并通过;复用原 caller 的运行编号,旧成功不能夺回结果 | -| 手动编号与布尔输入 | [运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306831237) 成功接收数字转换后的 PR 编号;显式 `all-open-prs=false` 只检查该 PR,其他 PR 的 Check ID 未变化 | -| 已删除 Issue HTTP 410 | 对同一个已删除 Issue #8,Check 给出带 Deferred 链接的 Tracking 错误,并说明已删除 Issue 无法 Deferred;不再显示通用 evaluation failed | -| 迁移后的最终复核夹具 | [实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307014684) 检测 Issue 在检查期间关闭;实验结束自动 dispatch [原 caller](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307047812) 刷新正式门禁 | -| 迁移后的 Bot 夹具 | [实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307186703) 仅编辑所选 PR 中自己发布的意见;已有授权人工回复继续有效 | -| 迁移后的 A/B 夹具 | [B-success 实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40307269178) 使用新候选脚本,通过迟到写入断言 | - -Ruff 检查和格式检查、actionlint、三个夹具的 Python 语法检查均通过。结束后已恢复真实 `AI_REVIEW_BOTS`,并通过原 caller 全仓复查撤掉测试身份的成功结果;当前等待真实 AI 完成而失败是预期状态。 - -自动化须采用新的关闭示例,或在自己的 Issue 修改步骤后追加 dispatch;GitHub 不会替未接入的任意工作流补发被 GITHUB_TOKEN 抑制的事件。调用入口使用自带 Token 的 `actions: write`,无需额外密钥。 - -共享 head 多 PR 的限制仍然存在;两个不同分支指向同一 commit 时能在真实 GitHub 创建多个 PR,本次未把该限制伪称为已修复。真实 Bot App 接入和第二个人工账号的真实授权仍待现场验收;其判定逻辑已有离线模拟。fork PR、Issue 转移按当前使用范围排除。 - -## 原候选版本的历史验收记录 - -日期:2026-10-26。仓库:[liaoxiang0304/VR_DexCopilot](https://github.com/liaoxiang0304/VR_DexCopilot)。 - -**结论:已经完成真实 Actions / Checks API / 合并门禁测试,但尚未全部验收通过,暂不建议直接推广。** - -共享脚本与 reusable workflow 均固定到候选提交 `be25a22a1c39b9c64fe8931e858e29829be1ada5`,无需合入公共 CI main。模拟审查者为真实的 `github-actions[bot]`,其评论均明确标注 SANDBOX FIXTURE;本次不声称 Infiscale / Codex 实际完成审查。 - -## 已验证的场景 - -| 场景 | 实际结果与证据 | -| --- | --- | -| 没有 AI 完成记录 | 创建 PR 自动失败,不能因零线程放行:[初次运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285069563) | -| 作者行内回复自动复查 | collector → workflow_run 成功:[自动运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285663160) | -| 手动触发 | 原版失败;测试仓库转换输入为数字后成功:[修正后](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285803976) | -| 普通后续讨论 | 会复查,但沿用有效完成记录和模板:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286031460) | -| 有效 Deferred / Issue 关闭 | 关闭后自动全仓复查,PR #3 失败、PR #4 仍被检查且通过;实际合并被拒绝:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286270592) | -| Issue 重开 | 未编辑 Deferred 也恢复通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286378424);该 sweep 的总状态失败是因为已有 PR #1 无完成记录,不能只看 workflow 总颜色 | -| Accepted 缺 Fix / Fix 被移出 PR | 均失败:[缺 Fix](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286513076)、[force-push 移除](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286847889);有效 Fix 在运行 15 曾通过 | -| resolved 且 outdated 线程 | 实际 GraphQL 状态均为 true;仍要求模板。删除唯一回复后失败,重新回复后通过:[删除](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40287573105)、[恢复](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40287616423) | -| B 处理中,A 曾成功 | 实验固定 Check 仍为 in_progress,实际合并返回 HTTP 405:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285932263) | -| B 失败,A 迟到写成功 | 保留 B 的失败,实际合并返回 HTTP 405:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285932263) | -| B 取消,A 迟到写成功 | 保留 B 的取消,实际合并返回 HTTP 405:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286136866) | -| B 成功,A 迟到写失败 | 保留 B 成功:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40286025437);真实 [PR #4](https://github.com/liaoxiang0304/VR_DexCopilot/pull/4) 在两个 Required Checks 通过后合并成功 | - -A/B 实验通过待测 `current_check()` 对真实 Checks API 制造迟到写入,并用独立 Check 名 `AI Review / Disposition Integration Test` 验证。它验证 Check 改名、接管和真实合并阻断;不等同于覆盖 GitHub 全部调度竞态。 - -## 不依赖真实 AI 的补测 - -用户选择先完成其余测试,真实 Bot 验收标为待完成。下列均使用明确标注的 GitHub Actions 测试审查者,不冒充 Infiscale / Codex。 - -| 场景 | 实测结果 | -| --- | --- | -| Deferred 链接实际指向本仓库 PR | 拒绝通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289406119) | -| Deferred 链接指向本仓库不存在的 Issue | 拒绝通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289455526) | -| Deferred 链接指向本仓库已关闭 Issue | 拒绝通过:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289512716) | -| Bot 用有效模板回复自己的意见,作者未回复 | 仍为 Unaddressed:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289851068) | -| 编辑 Bot 原始意见,人工旧回复仍有效 | 无需重复确认:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289746270) | -| 删除一次性 Issue | 自动触发全仓复查并失败:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40289979556);API 返回 HTTP 410,目前提示为通用 HTTPError | -| 首次验证 Issue 开放后立刻关闭它 | 最后复核重新读取,拒绝旧成功;真实 API 共读取 Issue 两次:[实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290499879) | -| 首次评估后立刻编辑原意见 | 第二次 PR 快照检测到变化并拒绝旧成功;重新检查后通过:[实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290629552) | -| 修改目标分支,再改回 | 两次均自动复查,无需强制 AI 重审:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40291961436) | -| PR 关闭后重开 | 自动复查:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40292010661) | -| 只改 PR 标题 | workflow 跳过评估,Check ID 保持不变:[运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40292060503) | - -最终复核实验使用同一个候选脚本,API 包装只在精确时间点对测试 Issue / Bot 自己的意见进行真实写入,既不伪造读取结果,也不修改候选评估逻辑。独立 Check `AI Review / Final Read Integration Test` 按预期失败,实验 job 因断言正确而成功;它不是 Required Check。 - -## 发现的问题 - -### 1. 手动 PR 编号类型错误,已仅在测试仓库修正 - -[原始失败运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40285281539) 的注释为:`Unexpected value '3'`。PR 编号进入 reusable workflow 时仍为字符串,脚本根本没启动。 - -需要在公共 CI 的 `docs/examples/ai-review-disposition.yml` 同步这一行;公共 PR #24 本次尚未修改: - -```diff -- || inputs.pr-number -+ || fromJSON(inputs.pr-number || '0') -``` - -[测试仓库修复提交](https://github.com/liaoxiang0304/VR_DexCopilot/commit/9075f49c568aa79e98c2be6cad76bee669103535) 已实测成功。交付的本地测试包也已同步该修正,因此它含有这处尚未进入公共候选的 caller 修正。 - -### 2. 共享 head 多 PR 的关联限制已复现,尚未解决 - -原实测 [PR #6](https://github.com/liaoxiang0304/VR_DexCopilot/pull/6) 和 [PR #7](https://github.com/liaoxiang0304/VR_DexCopilot/pull/7) 共用 head `2db00048253c38e7090765bec363f07632ec1cdf`。只有 #6 有测试审查:脚本分别给出成功 / 失败,但两条 PR 的实际合并均被 GitHub 拒绝,提示 `2 of 2 required status checks are expected`。 - -补测给 #6 追加一个 **tree 完全不变** 的独立提交 `e5315a94450879e073ca7cc097d5fb9a63bfb861`。[重新运行实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40291018228) 后,浏览器确认两个 Required Checks 成功、合并按钮恢复可用。没有执行 #6 的合并。 - -因此独立 head 的对照恢复正常;共享 head 场景仍未支持,不能标为通过。当前 #6 已改为独立 head,原同 head 状态及 API 拒绝记录保存在测试证据中。 - -### 3. 自动化使用 GITHUB_TOKEN 关闭 Issue,不会自动触发 caller - -实测 [工作流关闭 Issue 的实验](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290499879) 后,正式 Check ID 仍为 `121464063640`,保持原成功状态;独立复核实验已能检测到关闭并失败。[主动触发正式检查](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40290556150) 后,正式 Check 才失败。 - -这是 [GitHub 的事件抑制规则](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) 的实际影响。人工关闭 Issue 的自动复查已通过;现方案不能宣称覆盖所有自动化关闭来源。负责关闭 Issue 的 Actions 工作流需要主动调用全仓复查,例如 reusable workflow 的 `all-open-prs: true`;不需要 Issue 反查 PR。该接入补充本轮未写入公共 CI。 - -### 4. 删除 Issue 已阻断,错误提示仍可改进 - -一次性 [Issue #8](https://github.com/liaoxiang0304/VR_DexCopilot/issues/8) 确实被删除,GitHub REST 返回 HTTP 410。现脚本把它作为 API 错误保守阻断,未误放行;但用户只看到 `evaluation failed (HTTPError)`。可考虑把 410 与 404 一样归为无效 Tracking,从而给出清晰的处理提示。本轮未改候选脚本。 - -## 尚未验收与范围限制 - -- **真实 Bot 验收:待完成(按用户选择暂缓)**。包括实际开始/完成格式、零问题、新轮和 dismissed 历史兜底。 -- **需要第二个人工账号**:非作者 write/admin 回复、无权限人工回复、权限被撤回、最终权限复核竞态。Bot 回复被拒已验证,不能替代这些人工权限测试。尝试将 Bot 创建的测试 Issue 转成 PR 后,PR 作者仍是当前用户,因此没有将该尝试计为通过。 -- **需要另一授权测试仓库**:真实 fork PR、Issue 转移。当前授权仅限 VR_DexCopilot,未创建或写入其他仓库。 -- 外仓库链接的实测被自动审批拒绝,理由是此前限定只考虑本仓库;已移除该测试,未在评论里发布该外仓库链接。 -- 受控的 Issue 与意见变更竞态已实测;大规模分页及其余单元测试边界不代表都已现场执行。 - -## 当前现场 - -- [接入 PR #2](https://github.com/liaoxiang0304/VR_DexCopilot/pull/2) 和 [正常合并对照 PR #4](https://github.com/liaoxiang0304/VR_DexCopilot/pull/4) 已合并。 -- 一次性权限测试 [PR #10](https://github.com/liaoxiang0304/VR_DexCopilot/pull/10) 已关闭且未合并;[Issue #8](https://github.com/liaoxiang0304/VR_DexCopilot/issues/8) 为删除事件测试对象,已删除;[Issue #9](https://github.com/liaoxiang0304/VR_DexCopilot/issues/9) 已关闭。 -- [PR #3](https://github.com/liaoxiang0304/VR_DexCopilot/pull/3) 保留用于后续真实 Bot 验收;[Issue #5](https://github.com/liaoxiang0304/VR_DexCopilot/issues/5) 已关闭。 -- `AI_REVIEW_BOTS` 已从测试身份恢复为 `chatgpt-codex-connector[bot],infiscale-bot`,并通过 Issue 关闭事件重新检查开放 PR。真实 Bot 尚未完成时当前红色是预期行为。最新恢复复查为 [运行](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40292442890)。 -- `AI_REVIEW_SANDBOX=true` 保留,方便继续手动 A/B 实验;fixture / lab 都只用于本测试仓库。 -- [规则集](https://github.com/liaoxiang0304/VR_DexCopilot/rules/25862703) 仅约束 `test/ai-review-merge-target`,没有 bypass actor;同时要求正式 Check、实验 Check 和解决会话。`main` 未加入这些门禁。 -- 只新增测试工作流、验收文档和专用分支测试文件。原 `README.md`、`flexiv_team14.py` 的 blob SHA 均与测试前一致;既有 PR #1 的内容未改动,但全仓复查会给它增加检查结果。 - -验收依据为具体 Check 和实际合并 API 返回,不能把预期失败的 workflow 总颜色当成验收失败,也不能用实验 job 的绿色代替正式 Check。 - -## 参考 - -- [GitHub:Ruleset 参数与检查来源](https://docs.github.com/en/rest/repos/rules#create-a-repository-ruleset) -- [GitHub:GITHUB_TOKEN 产生事件的触发限制](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) - -补测不修改公共 CI PR #24;本次新增的 fixture / final-read workflow 只在测试仓库使用。 diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index 8ee53cc..d2ccec5 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -34,29 +34,20 @@ permissions: jobs: disposition: if: >- - ${{ github.event_name != 'issues' - && !(github.event_name == 'workflow_dispatch' && inputs.all-open-prs) - && (github.event_name != 'issue_comment' || github.event.issue.pull_request) + ${{ (github.event_name != 'issue_comment' || github.event.issue.pull_request) && (github.event_name != 'pull_request_target' || github.event.action != 'edited' || github.event.changes.base) }} uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main with: + all-open-prs: >- + ${{ github.event_name == 'issues' + || (github.event_name == 'workflow_dispatch' && inputs.all-open-prs) }} # Collector run-name is the PR number, even when workflow_run.pull_requests is empty. pr-number: >- ${{ github.event.pull_request.number - || github.event.issue.number + || (github.event_name == 'issue_comment' && github.event.issue.number) || fromJSON(inputs.pr-number || '0') || fromJSON(github.event.workflow_run.display_title || '0') }} # Set this repository/organization variable to exact bot logins. bot-logins: ${{ vars.AI_REVIEW_BOTS }} shared-ref: main - - issue-recheck: - if: >- - ${{ github.event_name == 'issues' - || (github.event_name == 'workflow_dispatch' && inputs.all-open-prs) }} - uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main - with: - all-open-prs: true - bot-logins: ${{ vars.AI_REVIEW_BOTS }} - shared-ref: main diff --git a/docs/examples/ai-review-sandbox/README.md b/docs/examples/ai-review-sandbox/README.md deleted file mode 100644 index db6d216..0000000 --- a/docs/examples/ai-review-sandbox/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# 隔离验收模板 - -模板只用于专用测试仓库,不会在公共 CI 仓库自动启用。历史实测和模拟范围见 [验收记录](../../AI_REVIEW_DISPOSITION_TEST_REPORT.md)。生产 caller 仍默认使用 `main`。 - -## 准备 - -1. 将上级目录的 `ai-review-disposition.yml`、`ai-review-events.yml` 复制到测试仓库 `.github/workflows/` 并提交默认分支。测试未合入 main 的候选时,把 caller 两处 workflow `uses` 和两处 `shared-ref` 同时改为 `feat/Ai-dispose`,或同一个候选 SHA。 -2. 将本目录三个 `.yml` 也复制到测试仓库 `.github/workflows/`。设置 Variable `AI_REVIEW_SANDBOX=true`;实验脚本的 `AI_REVIEW_TEST_REF` 默认 `feat/Ai-dispose`,指定提交时应与 caller 使用相同 SHA。 -3. 创建目标分支 `test/ai-review-merge-target`。测试 PR 来源分支以 `test/ai-review-e2e-` 开头,每条 PR 使用独立 head。 -4. 在测试 PR 新增 `.ai-review-sandbox/sample.py`,第 5 行须在 diff 中: - -```python -"""Disposable fixture; workflows never execute this PR file.""" - - -def sample(): - value = 1 - return value -``` - -设置 `AI_REVIEW_BOTS=github-actions[bot]`,运行 **AI Review Sandbox Fixture** 的 `create-review`,填写 PR 编号和 `with-finding=true`。这是真实 GitHub Actions 身份,评论明确标注 fixture,不冒充 Infiscale / Codex。其 Review 使用 `GITHUB_TOKEN`,需要手动运行正式 caller 检查该 PR;随后作者新增、编辑、删除模板回复将走真实事件链自动复查。 - -`reply` 用于验证 Bot 不能自行处理意见;`edit-root` 用于验证原意见编辑无需重复确认。`target-comment-id` 只接受该 fixture Bot 在所选 PR 上自己发布的根评论。 - -## 测试规则 - -先在健康 PR 上产生一次成功的正式 Check 和 B-success 实验 Check,再应用 `ruleset.json`: - -```bash -gh api repos/OWNER/TEST_REPO/rulesets --method POST \ - --input docs/examples/ai-review-sandbox/ruleset.json -``` - -JSON 仅约束 `test/ai-review-merge-target`,没有 bypass,要求正式 Check、A/B 实验 Check 和会话解决。它是服务器规则的配置模板,提交 Git 文件不会自动启用。不要将实验 Check 加入生产门禁,或把测试规则用于业务 main。 - -## 真实 API 实验 - -| 工作流 | 输入与用途 | 预期 | -| --- | --- | --- | -| AI Review Latest Result Lab | PR;B-success / B-failure / B-cancelled;暂停 0–60 秒 | B 处理中、失败、取消均阻止合并;A 的迟到结果不能覆盖 B | -| AI Review Final Read Lab | PR;开放 Issue;fixture 根评论 ID;issue-close / review-edit | 首次读取后真实修改数据,最后复核拒绝旧成功 | - -最终复核实验要求人工 Deferred 指向该 Issue,Issue 标题以 `[Sandbox disposable]` 开头。实验只编辑 fixture Bot 自己的意见或关闭测试 Issue;结束后 dispatch 正式 caller 全仓复查。 - -实验 job 绿色表示断言成立,其独立实验 Check 可能按预期红色或取消。最终复核实验的 Check 不是 Required Check。A/B 实验还需核对真实合并区,不能只看 API 断言。 - -## 自动关 Issue - -将上级目录 `ai-review-close-issue.yml` 复制到默认分支。让 Deferred 引用开放 Issue,再运行 **Close Issue and Recheck AI Dispositions**。应出现新的正式 caller `workflow_dispatch`,逐个检查开放 PR,使该 Deferred 失败。 - -其他使用 `GITHUB_TOKEN` 修改 Issue 的工作流也须在修改后触发同一 caller;负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 需要 `issues: write`: - -```bash -gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ - --ref "$DEFAULT_BRANCH" -f all-open-prs=true -``` - -无需额外 Token 或 Issue 到 PR 的反向关联。不要由另一工作流直接运行正式检查脚本或另建 caller:新旧结果按同一 caller 的运行编号排序。 - -## 离线模拟与范围 - -```bash -python -m unittest discover -s scripts/tests -v -python -m scripts.tests.simulate_ai_review_disposition -``` - -模拟使用合成的 AI/人工身份和权限响应,运行实际判定与末次复核逻辑,不需要真实账号或密钥。它能证明规则行为,不能证明 App 已接入或真实授权已生效。 - -本次范围为同仓库 PR / Issue,fork PR、Issue 转移不作为验收前提;跨仓库链接拒绝校验保留。结束后恢复真实 `AI_REVIEW_BOTS` 并重新检查,也可设 `AI_REVIEW_SANDBOX=false` 停用夹具。 diff --git a/docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml b/docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml deleted file mode 100644 index 88aed99..0000000 --- a/docs/examples/ai-review-sandbox/ai-review-final-read-lab.yml +++ /dev/null @@ -1,126 +0,0 @@ -# Test-only controlled timing experiment; never a production required check. -name: AI Review Final Read Lab -on: - workflow_dispatch: - inputs: - pr-number: - description: 'Disposable test PR number' - type: number - required: true - issue-number: - description: 'Open disposable Issue currently referenced by Deferred' - type: number - required: true - root-comment-id: - description: 'Existing fixture bot root comment on that PR' - type: number - required: true - scenario: - description: 'Mutation immediately after the first external lookup' - type: choice - required: true - options: [issue-close, review-edit] -permissions: - actions: write - contents: read - pull-requests: write - issues: write - checks: write -jobs: - experiment: - if: ${{ vars.AI_REVIEW_SANDBOX == 'true' }} - runs-on: ubuntu-latest - timeout-minutes: 5 - concurrency: - group: ai-review-final-read-lab-${{ github.repository }}-${{ inputs.pr-number }} - cancel-in-progress: false - steps: - - uses: actions/checkout@v4 - with: - repository: IS-Model-Framework/.github - ref: ${{ vars.AI_REVIEW_TEST_REF || 'feat/Ai-dispose' }} - path: .ci-shared - persist-credentials: false - sparse-checkout: scripts - - uses: actions/setup-python@v7 - with: - python-version: '3.11' - - name: Verify real final reads with a controlled concurrent mutation - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ inputs.pr-number }} - ISSUE_NUMBER: ${{ inputs.issue-number }} - ROOT_COMMENT_ID: ${{ inputs.root-comment-id }} - SCENARIO: ${{ inputs.scenario }} - DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} - run: | - python - <<'PY' - import os - import subprocess - import sys - from urllib.parse import quote - sys.path.insert(0, '.ci-shared') - from scripts import check_ai_review_disposition as checker - - repository = os.environ['GITHUB_REPOSITORY'] - number = int(os.environ['PR_NUMBER']) - issue_number = int(os.environ['ISSUE_NUMBER']) - root_id = int(os.environ['ROOT_COMMENT_ID']) - scenario = os.environ['SCENARIO'] - assert min(number, issue_number, root_id) > 0 - checker.CHECK_NAME = 'AI Review / Final Read Integration Test' - real = checker.GitHub(os.environ['GH_TOKEN']) - pr = real.request('GET', f'/repos/{repository}/pulls/{number}') - assert pr['state'] == 'open' and pr['head']['ref'].startswith('test/ai-review-e2e-') - assert pr['base']['ref'] == 'test/ai-review-merge-target' - issue_path = f'/repos/{repository}/issues/{issue_number}' - issue = real.request('GET', issue_path) - assert issue['state'] == 'open' and issue['title'].startswith('[Sandbox disposable]') - assert 'pull_request' not in issue - root_path = f'/repos/{repository}/pulls/comments/{root_id}' - root = real.request('GET', root_path) - assert root['user']['login'] == 'github-actions[bot]' - assert root['pull_request_url'] == f'https://api.github.com/repos/{repository}/pulls/{number}' - - class MutatingAPI(checker.GitHub): - lookups = 0 - def request(self, method, path, body=None): - result = super().request(method, path, body) - if method == 'GET' and path == issue_path: - self.lookups += 1 - if self.lookups == 1: - # Return the real open response read just before the mutation. - # The candidate itself must detect the change on its final read. - if scenario == 'issue-close': - super().request('PATCH', issue_path, {'state': 'closed'}) - elif scenario == 'review-edit': - super().request('PATCH', root_path, { - 'body': 'SANDBOX FIXTURE: changed during evaluation, run ' - + os.environ['GITHUB_RUN_ID'], - }) - else: - raise ValueError('Unknown scenario') - return result - - api = MutatingAPI(os.environ['GH_TOKEN']) - assert checker.check_pr(api, repository, number, {'github-actions[bot]'}) is False - name = quote(checker.CHECK_NAME, safe='') - checks = api.pages(f'/repos/{repository}/commits/{pr["head"]["sha"]}/check-runs' - f'?check_name={name}&filter=all', 'check_runs') - current = max(checks, key=lambda check: check['id']) - assert current['conclusion'] == 'failure' - if scenario == 'issue-close': - assert api.lookups == 2 - assert 'Tracking must reference' in current['output']['summary'] - else: - assert 'PR review data changed during evaluation' in current['output']['summary'] - print('PASS:', scenario, 'was detected; stale success was refused.') - with open(os.environ['GITHUB_STEP_SUMMARY'], 'a', encoding='utf-8') as report: - report.write(f'Controlled real-API final-read test passed: **{scenario}**.\n\n' - f'Issue lookups: {api.lookups}. Fixture Check deliberately failed.\n') - # Our own Issue mutation also uses GITHUB_TOKEN: refresh the real gate. - subprocess.run([ - 'gh', 'workflow', 'run', 'ai-review-disposition.yml', '--repo', repository, - '--ref', os.environ['DEFAULT_BRANCH'], '-f', 'all-open-prs=true', - ], check=True) - PY diff --git a/docs/examples/ai-review-sandbox/ai-review-fixture.yml b/docs/examples/ai-review-sandbox/ai-review-fixture.yml deleted file mode 100644 index bffacd4..0000000 --- a/docs/examples/ai-review-sandbox/ai-review-fixture.yml +++ /dev/null @@ -1,102 +0,0 @@ -# Test-only actor. This is GitHub Actions, not Codex or Infiscale. -name: AI Review Sandbox Fixture -on: - workflow_dispatch: - inputs: - pr-number: - description: 'Disposable test PR number' - required: true - type: number - with-finding: - description: 'Create one inline finding to exercise disposition replies' - required: true - type: boolean - default: true - operation: - description: 'Explicit fixture action; never impersonates a human' - required: true - type: choice - default: create-review - options: [create-review, reply, edit-root] - target-comment-id: - description: 'Existing github-actions root comment ID for reply/edit' - required: false - type: number - default: 0 -permissions: - contents: read - pull-requests: write -jobs: - fixture: - if: ${{ vars.AI_REVIEW_SANDBOX == 'true' }} - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - name: Publish an explicitly labelled fixture review - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ inputs.pr-number }} - WITH_FINDING: ${{ inputs.with-finding }} - OPERATION: ${{ inputs.operation }} - TARGET_COMMENT_ID: ${{ inputs.target-comment-id }} - run: | - python - <<'PY' - import json - import os - from urllib.request import Request, urlopen - - repo = os.environ['GITHUB_REPOSITORY'] - number = int(os.environ['PR_NUMBER']) - if number <= 0: - raise ValueError('Authorized test repository and positive PR required') - - def api(path, body=None, method=None): - request = Request('https://api.github.com/repos/' + repo + path, - method=method or ('POST' if body is not None else 'GET'), - data=json.dumps(body).encode() if body is not None else None, - headers={'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], - 'Accept': 'application/vnd.github+json', - 'Content-Type': 'application/json'}) - with urlopen(request, timeout=30) as response: - return json.load(response) - - pr = api(f'/pulls/{number}') - if (pr['state'] != 'open' - or not pr['head']['ref'].startswith('test/ai-review-e2e-') - or pr['base']['ref'] != 'test/ai-review-merge-target'): - raise ValueError('Use only an open disposable fixture PR') - operation = os.environ['OPERATION'] - if operation in {'reply', 'edit-root'}: - target = int(os.environ['TARGET_COMMENT_ID']) - root = api(f'/pulls/comments/{target}') - if (root['user']['login'] != 'github-actions[bot]' - or root.get('in_reply_to_id') - or root['pull_request_url'] != f'https://api.github.com/repos/{repo}/pulls/{number}'): - raise ValueError('Use only this fixture bot\'s own root on the selected PR') - if operation == 'reply': - result = api(f'/pulls/{number}/comments/{target}/replies', { - 'body': 'Disposition: Rejected\nReason: SANDBOX bot reply must not satisfy a human response.', - }) - else: - result = api(f'/pulls/comments/{target}', { - 'body': 'SANDBOX FIXTURE: edited original finding. Existing human disposition ' - 'must remain valid; no repeated confirmation is required.', - }, method='PATCH') - print('Fixture action:', operation, result['html_url']) - raise SystemExit(0) - if operation != 'create-review': - raise ValueError('Unknown fixture operation') - review = { - 'commit_id': pr['head']['sha'], 'event': 'COMMENT', - 'body': 'SANDBOX FIXTURE: a GitHub Actions review for API/policy testing. ' - 'This is not an Infiscale or Codex review.', - } - if os.environ['WITH_FINDING'] == 'true': - review['comments'] = [{ - 'path': '.ai-review-sandbox/sample.py', 'line': 5, 'side': 'RIGHT', - 'body': 'SANDBOX FIXTURE: record an explicit disposition for this test value. ' - 'This is not a real AI finding.', - }] - created = api(f'/pulls/{number}/reviews', review) - print('Fixture review:', created['html_url']) - PY diff --git a/docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml b/docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml deleted file mode 100644 index 002c6d2..0000000 --- a/docs/examples/ai-review-sandbox/ai-review-latest-result-lab.yml +++ /dev/null @@ -1,142 +0,0 @@ -# Test-repository-only experiment. Never add this check to production rulesets. -name: AI Review Latest Result Lab - -on: - workflow_dispatch: - inputs: - pr-number: - description: 'Open test PR number in this test repository' - required: true - type: number - scenario: - description: 'The result that B must retain after A writes late' - required: true - type: choice - default: B-success - options: [B-success, B-failure, B-cancelled] - pause-seconds: - description: 'Pause with B pending so you can inspect the merge box (0-60)' - required: false - type: number - default: 15 - -permissions: - contents: read - pull-requests: read - checks: write - -jobs: - experiment: - if: ${{ vars.AI_REVIEW_SANDBOX == 'true' }} - runs-on: ubuntu-latest - timeout-minutes: 5 - concurrency: - group: ai-review-latest-result-lab-${{ github.repository }}-${{ inputs.pr-number }} - cancel-in-progress: false - steps: - - name: Checkout the exact candidate scripts - uses: actions/checkout@v4 - with: - repository: IS-Model-Framework/.github - ref: ${{ vars.AI_REVIEW_TEST_REF || 'feat/Ai-dispose' }} - path: .ci-shared - persist-credentials: false - sparse-checkout: scripts - - name: Set up Python - uses: actions/setup-python@v7 - with: - python-version: '3.11' - - name: Exercise the real Checks API with a deliberately late A result - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ inputs.pr-number }} - SCENARIO: ${{ inputs.scenario }} - PAUSE_SECONDS: ${{ inputs.pause-seconds }} - run: | - python - <<'PY' - import os - import sys - import time - from urllib.parse import quote - - sys.path.insert(0, '.ci-shared') - from scripts import check_ai_review_disposition as checker - - # Isolate fixture checks from the real evaluator's required check. - checker.CHECK_NAME = 'AI Review / Disposition Integration Test' - api = checker.GitHub(os.environ['GH_TOKEN']) - repository = os.environ['GITHUB_REPOSITORY'] - number = int(os.environ['PR_NUMBER']) - pause = int(os.environ['PAUSE_SECONDS']) - if number <= 0 or not 0 <= pause <= 60: - raise ValueError('Positive PR number and pause between 0 and 60 required') - outcomes = { - 'B-success': ('success', 'failure'), - 'B-failure': ('failure', 'success'), - 'B-cancelled': ('cancelled', 'success'), - } - expected, late_result = outcomes[os.environ['SCENARIO']] - pr = api.request('GET', f'/repos/{repository}/pulls/{number}') - if (pr['state'] != 'open' - or not pr['head']['ref'].startswith('test/ai-review-e2e-') - or pr['base']['ref'] != 'test/ai-review-merge-target'): - raise ValueError('Use an open test PR') - head = pr['head']['sha'] - generation = int(os.environ['GITHUB_RUN_NUMBER']) - attempt = int(os.environ['GITHUB_RUN_ATTEMPT']) * 2 - - def create(attempt_number): - return api.request('POST', f'/repos/{repository}/check-runs', { - 'name': checker.CHECK_NAME, - 'head_sha': head, - 'status': 'in_progress', - 'external_id': f'ai-review-disposition:{number}:{generation}:{attempt_number}', - }) - - def finish(check, conclusion): - # As in production, finishing never sets the check's name. - api.request('PATCH', f"/repos/{repository}/check-runs/{check['id']}", { - 'status': 'completed', - 'conclusion': conclusion, - 'output': {'title': f'Lab result: {conclusion}', 'summary': 'Sandbox fixture check.'}, - }) - - def gate(): - name = quote(checker.CHECK_NAME, safe='') - checks = api.pages( - f'/repos/{repository}/commits/{head}/check-runs?check_name={name}&filter=all', - 'check_runs', - ) - return [c for c in checks if c['app']['id'] == newer['app']['id']] - - older = create(attempt - 1) - assert checker.current_check(api, repository, number, head, older) - finish(older, 'success') - newer = create(attempt) - assert checker.current_check(api, repository, number, head, newer) - checks = gate() - assert len(checks) == 1 and checks[0]['id'] == newer['id'] - assert checks[0]['status'] == 'in_progress' - print(f"B is pending for {pause}s. Inspect PR #{number}'s merge box now.", flush=True) - time.sleep(pause) - - finish(newer, expected) - # This deliberately bypasses A's final ownership test to simulate a request - # already sent before cancellation, but received after B's final result. - finish(older, late_result) - checks = gate() - assert len(checks) == 1 and checks[0]['id'] == newer['id'] - assert checks[0]['conclusion'] == expected - assert not checker.current_check(api, repository, number, head, older) - print(f"PASS: B remains {expected}; A's late {late_result} did not take over.") - with open(os.environ['GITHUB_STEP_SUMMARY'], 'a', encoding='utf-8') as report: - report.write( - f'## Latest-result experiment passed\n\n' - f'PR: {pr["html_url"]}\n\n' - f'Head: `{head}`\n\n' - f'Expected and actual required fixture check: **{expected}**.\n\n' - f'A wrote **{late_result}** after B. Only B retains the fixed check name.\n\n' - f'The experiment job succeeds when the assertions hold; ' - f'the fixture check itself intentionally reflects the selected B result.\n' - ) - PY diff --git a/docs/examples/ai-review-sandbox/ruleset.json b/docs/examples/ai-review-sandbox/ruleset.json deleted file mode 100644 index 52200b3..0000000 --- a/docs/examples/ai-review-sandbox/ruleset.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "AI review sandbox only", - "target": "branch", - "enforcement": "active", - "bypass_actors": [], - "conditions": { - "ref_name": { - "include": [ - "refs/heads/test/ai-review-merge-target" - ], - "exclude": [] - } - }, - "rules": [ - { - "type": "pull_request", - "parameters": { - "dismiss_stale_reviews_on_push": false, - "require_code_owner_review": false, - "require_last_push_approval": false, - "required_approving_review_count": 0, - "required_review_thread_resolution": true - } - }, - { - "type": "required_status_checks", - "parameters": { - "strict_required_status_checks_policy": false, - "required_status_checks": [ - { - "context": "AI Review / Disposition Check", - "integration_id": 15368 - }, - { - "context": "AI Review / Disposition Integration Test", - "integration_id": 15368 - } - ] - } - } - ] -} diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 50e5eef..5cf631a 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -197,15 +197,6 @@ def codex_progress(comment): return timestamp(clock[1] if clock else fallback), completed -def completion_comment(comment): - bot = actor_login(comment.get("author")) - body = comment["body"].replace("\r\n", "\n").strip() - if bot == "infiscale-bot": - return body == INFISCALE_COMPLETE - progress = codex_progress(comment) if bot == CODEX else None - return progress is not None and progress[1] - - def review_complete(data, bot): """Rounds for a bot do not overlap; a withdrawn round may use older evidence.""" reviews = [r for r in data["reviews"] if actor_login(r.get("author")) == bot] @@ -216,16 +207,17 @@ def review_complete(data, bot): ] progress = [] for comment in comments: - if bot == "infiscale-bot" and infiscale_start(comment["body"]): - starts.append(timestamp(comment.get("createdAt"))) - if bot == CODEX: + if bot == "infiscale-bot": + if infiscale_start(comment["body"]): + starts.append(timestamp(comment.get("createdAt"))) + elif comment["body"].strip() == INFISCALE_COMPLETE: + completed.append(timestamp(comment.get("createdAt"))) + elif bot == CODEX: status = codex_progress(comment) if status: progress.append(status) if status[1]: completed.append(status[0]) - elif completion_comment(comment): - completed.append(timestamp(comment.get("createdAt"))) latest_status = max( progress, key=lambda status: (status[0], not status[1]), default=None ) diff --git a/scripts/tests/simulate_ai_review_disposition.py b/scripts/tests/simulate_ai_review_disposition.py deleted file mode 100644 index 8b83ef9..0000000 --- a/scripts/tests/simulate_ai_review_disposition.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Offline scenarios using synthetic actors and the real disposition checker.""" - -import copy -from urllib.error import HTTPError - -from scripts.tests.test_ai_review_disposition import ( - BOT, - CODEX, - CODEX_SUMMARY, - INFISCALE_COMPLETE, - INFISCALE_START, - ApiTests, - comment, - fixture, - result, -) -from scripts.check_ai_review_disposition import passed - - -def scenarios(): - """Yield names, actual outcomes, and independently specified expectations.""" - ai = fixture( - "Disposition: Rejected\nReason: Already handled", reviewer="infiscale-bot" - ) - ai["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} - ai["comments"] = [comment(INFISCALE_START, "infiscale-bot")] - yield ( - "Infiscale started; old review cannot finish new round", - passed(result(ai, {"infiscale-bot"})), - False, - ) - latest = {**ai["reviews"][0], "id": "new", "submittedAt": "2026-10-09T03:00:00Z"} - ai["reviews"].append(latest) - yield ( - "Infiscale publishes findings after start", - passed(result(ai, {"infiscale-bot"})), - True, - ) - latest["state"] = "DISMISSED" - yield ( - "Withdrawn round can use older valid review", - passed(result(ai, {"infiscale-bot"})), - True, - ) - ai["reviews"] = [latest] - yield ( - "All reviews dismissed without valid history", - passed(result(ai, {"infiscale-bot"})), - False, - ) - ai["threads"] = [] - ai["comments"].append( - comment(INFISCALE_COMPLETE, "infiscale-bot", "2026-10-09T04:00:00Z") - ) - yield ( - "Infiscale exact zero-finding completion", - passed(result(ai, {"infiscale-bot"})), - True, - ) - ai["comments"].append( - comment(INFISCALE_START, "infiscale-bot", "2026-10-09T05:00:00Z") - ) - yield ( - "Later Infiscale round requires new completion", - passed(result(ai, {"infiscale-bot"})), - False, - ) - - codex = fixture() - codex.update(threads=[], reviews=[]) - for label, status, expected in ( - ("in progress", "⏳ **In progress**", False), - ("failed", "⚠️ **Failed**", False), - ("completed", "✅ **Completed**", True), - ): - codex["comments"] = [ - comment(CODEX_SUMMARY.replace("✅ **Completed**", status), CODEX) - ] - codex["comments"][0]["author"] = { - "login": CODEX.removesuffix("[bot]"), - "__typename": "Bot", - } - yield "Codex " + label, passed(result(codex, {CODEX})), expected - - # check_pr() performs actual authorization and final-cache logic; only its API - # transport and snapshots are replaced. No GitHub credential/account is used. - harness = ApiTests() - for role, expected in ( - ("write", True), - ("admin", True), - ("read", False), - ("none", False), - ): - data = fixture("Disposition: Rejected\nReason: Second human account") - data["threads"][0]["comments"][-1]["author"]["login"] = "second-human" - _, ok = harness.run_check([data, copy.deepcopy(data)], {"permission": role}) - yield "Second human has " + role + " permission", ok, expected - data = fixture("Disposition: Rejected\nReason: Previously authorized") - data["threads"][0]["comments"][-1]["author"]["login"] = "second-human" - _, ok = harness.run_check( - [data, copy.deepcopy(data)], [{"permission": "write"}, {"permission": "read"}] - ) - yield "Second human loses write access during final check", ok, False - data = fixture("Disposition: Rejected\nReason: Bot cannot self-dispose") - data["threads"][0]["comments"][-1]["author"] = {"login": BOT, "__typename": "Bot"} - yield "Bot reply cannot replace a human disposition", passed(result(data)), False - - data = fixture( - "Disposition: Deferred\nReason: Follow up\nTracking: https://github.com/org/repo/issues/42" - ) - for label, lookup, expected in ( - ("open Issue", {"state": "open"}, True), - ("closed Issue", {"state": "closed"}, False), - ( - "deleted Issue", - HTTPError("https://api.github.com/issue", 410, "Gone", {}, None), - False, - ), - ( - "Issue closes during final check", - [{"state": "open"}, {"state": "closed"}], - False, - ), - ): - _, ok = harness.run_check([data, copy.deepcopy(data)], lookup) - yield label, ok, expected - - -def main(): - print("Simulation only: synthetic AI and human identities; no GitHub requests.\n") - print("| Scenario | Expected gate | Actual gate | Matches |") - print("| --- | --- | --- | --- |") - failures = 0 - count = 0 - for name, actual, expected in scenarios(): - failures += actual != expected - count += 1 - expected_gate = "pass" if expected else "block" - actual_gate = "pass" if actual else "block" - matches = "yes" if actual == expected else "NO" - print(f"| {name} | {expected_gate} | {actual_gate} | {matches} |") - print(f"\n{count - failures}/{count} scenarios matched expectations.") - return int(bool(failures)) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 583def4..959371d 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -90,6 +90,23 @@ def result(data, bots=None, authorized=None, tracking_valid=None): ) +def pr_metadata(**changes): + return { + "node_id": "pr-1", + "head": {"sha": HEAD}, + "user": {"login": "contributor"}, + "state": "open", + **changes, + } + + +def page(nodes, next_cursor=None): + return { + "nodes": nodes, + "pageInfo": {"hasNextPage": next_cursor is not None, "endCursor": next_cursor}, + } + + class PolicyTests(unittest.TestCase): def test_all_dispositions_pass_independently_of_resolution(self): replies = [ @@ -613,11 +630,8 @@ def respond(request, timeout): def test_connections_read_more_than_100_nodes(self): api = GitHub("test-token") pages = [ - { - "nodes": list(range(100)), - "pageInfo": {"hasNextPage": True, "endCursor": "next"}, - }, - {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}}, + page(list(range(100)), "next"), + page([100]), ] for field in ("reviews", "comments"): with self.subTest(field=field): @@ -630,13 +644,10 @@ def test_long_thread_comments_are_paginated(self): api = GitHub("test-token") thread = { "id": "thread-1", - "comments": { - "nodes": list(range(100)), - "pageInfo": {"hasNextPage": True, "endCursor": "next"}, - }, + "comments": page(list(range(100)), "next"), } - page = {"nodes": [100], "pageInfo": {"hasNextPage": False, "endCursor": None}} - with patch.object(api, "graphql", return_value={"node": {"comments": page}}): + last_page = page([100]) + with patch.object(api, "graphql", return_value={"node": {"comments": last_page}}): comments = api.connection( thread["id"], "comments", @@ -651,15 +662,7 @@ def test_long_thread_comments_are_paginated(self): def test_snapshot_keeps_inline_replies_and_top_level_completion_separate(self): api = GitHub("test-token") data = fixture("Disposition: Invalid\nReason: Test") - pr = { - "node_id": "pr-1", - "head": {"sha": HEAD}, - "user": {"login": data["author"]}, - "state": "open", - } - - def page(nodes): - return {"nodes": nodes, "pageInfo": {"hasNextPage": False, "endCursor": None}} + pr = pr_metadata(user={"login": data["author"]}) thread = copy.deepcopy(data["threads"][0]) thread["comments"] = page(thread["comments"]) @@ -694,15 +697,7 @@ def test_graphql_errors_reject_partial_data(self): def test_resolution_changes_during_check_do_not_block(self): api = GitHub("test-token") data = fixture("Disposition: Invalid\nReason: False positive") - pr = { - "node_id": "pr-1", - "head": {"sha": HEAD}, - "user": {"login": data["author"]}, - "state": "open", - } - - def page(nodes): - return {"nodes": nodes, "pageInfo": {"hasNextPage": False, "endCursor": None}} + pr = pr_metadata(user={"login": data["author"]}) for resolutions in ((False, True), (True, False)): with self.subTest(resolutions=resolutions): @@ -743,12 +738,7 @@ def graphql(query, variables, states=states): def test_snapshot_rejects_head_change_during_read(self): api = GitHub("test-token") - before = { - "node_id": "pr-1", - "head": {"sha": HEAD}, - "user": {"login": "contributor"}, - "state": "open", - } + before = pr_metadata() after = {**before, "head": {"sha": FIX}} with ( patch.object(api, "request", side_effect=[before, after]), @@ -758,12 +748,7 @@ def test_snapshot_rejects_head_change_during_read(self): snapshot(api, "org/repo", 128) def test_snapshot_retains_repository_for_commit_link_validation(self): - pr = { - "node_id": "pr-1", - "head": {"sha": HEAD}, - "user": {"login": "contributor"}, - "state": "open", - } + pr = pr_metadata() api = GitHub("test-token") with ( patch.object(api, "request", return_value=pr), @@ -772,13 +757,9 @@ def test_snapshot_retains_repository_for_commit_link_validation(self): self.assertEqual(snapshot(api, "org/repo", 128)["repository"], "org/repo") def test_snapshot_rejects_base_change_but_ignores_unrelated_repo_metadata(self): - before = { - "node_id": "pr-1", - "head": {"sha": HEAD}, - "base": {"ref": "main", "sha": FIX, "repo": {"description": "old"}}, - "user": {"login": "contributor"}, - "state": "open", - } + before = pr_metadata( + base={"ref": "main", "sha": FIX, "repo": {"description": "old"}} + ) for base in ({"ref": "develop", "sha": FIX}, {"ref": "main", "sha": HEAD}): with self.subTest(base=base): api = GitHub("test-token") @@ -799,12 +780,7 @@ def test_snapshot_rejects_base_change_but_ignores_unrelated_repo_metadata(self): ) def test_snapshot_reads_top_level_comments_for_completion(self): - pr = { - "node_id": "pr-1", - "head": {"sha": HEAD}, - "user": {"login": "contributor"}, - "state": "open", - } + pr = pr_metadata() api = GitHub("test-token") completed = comment(INFISCALE_COMPLETE, "infiscale-bot") with ( diff --git a/scripts/tests/test_ai_review_scenarios.py b/scripts/tests/test_ai_review_scenarios.py deleted file mode 100644 index 6d66f1a..0000000 --- a/scripts/tests/test_ai_review_scenarios.py +++ /dev/null @@ -1,10 +0,0 @@ -import unittest - -from scripts.tests.simulate_ai_review_disposition import scenarios - - -class ScenarioTests(unittest.TestCase): - def test_simulated_bot_rounds_and_second_human_permissions(self): - for name, actual, expected in scenarios(): - with self.subTest(scenario=name): - self.assertEqual(actual, expected) From 01cf7d3a8721a367fd3c2972987ae12f9cc3a7ec Mon Sep 17 00:00:00 2001 From: xiaoyu <2455995107@qq.com> Date: Mon, 26 Oct 2026 20:11:26 +0800 Subject: [PATCH 16/21] fix[ci]: harden AI review disposition checks Problem: - Interrupted evaluations can leave stale or unfinished merge checks. - Edited comments and truncated commit lists can invalidate disposition evidence. Solution: - Pre-register sweep checks, evaluate four PRs in parallel, and recover interrupted runs. - Validate comment editors, complete large PR commit lists, and bound read retries. - Document Codex completion precedence and asynchronous recovery limits. Test: - Python 3.11: 123 unit tests passed. - Ruff lint/format, actionlint, and git diff --check passed. - Read-only GitHub probes verified editor fields and all 794 comparison commits. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 29 +- docs/AI_REVIEW_DISPOSITION.md | 25 +- docs/examples/ai-review-disposition.yml | 7 + docs/examples/ai-review-recovery.yml | 26 + scripts/check_ai_review_disposition.py | 290 +++++++++-- scripts/tests/test_ai_review_disposition.py | 12 +- scripts/tests/test_ai_review_reliability.py | 463 ++++++++++++++++++ 7 files changed, 801 insertions(+), 51 deletions(-) create mode 100644 docs/examples/ai-review-recovery.yml create mode 100644 scripts/tests/test_ai_review_reliability.py diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index 0d260d5..8bbd7f4 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -17,6 +17,11 @@ on: required: false type: boolean default: false + recover-run-id: + description: 'Interrupted caller run to recover; uses that run generation' + required: false + type: number + default: 0 shared-ref: description: 'Revision of the shared CI scripts; defaults to main' required: false @@ -24,6 +29,7 @@ on: default: main permissions: + actions: read contents: read pull-requests: read issues: read @@ -33,11 +39,14 @@ jobs: disposition: name: Evaluate AI Review Dispositions runs-on: ubuntu-latest - timeout-minutes: 15 - # Keep the newest evaluation for this PR; other PRs run independently. + timeout-minutes: ${{ (inputs.all-open-prs || inputs.recover-run-id != 0) && 360 || 15 }} + # Sweeps must make progress; generation checks still reject older results. concurrency: - group: ai-review-disposition-${{ github.repository }}-${{ inputs.all-open-prs && 'all-open-prs' || inputs.pr-number }} - cancel-in-progress: true + group: ai-review-disposition-${{ github.repository }}-${{ inputs.recover-run-id && format('recover-{0}', inputs.recover-run-id) || (inputs.all-open-prs && 'all-open-prs' || inputs.pr-number) }} + cancel-in-progress: ${{ !inputs.all-open-prs && inputs.recover-run-id == 0 }} + env: + GH_TOKEN: ${{ github.token }} + AI_REVIEW_BOTS: ${{ inputs.bot-logins }} steps: - name: Checkout trusted shared scripts uses: actions/checkout@v4 @@ -59,9 +68,19 @@ jobs: AI_REVIEW_BOTS: ${{ inputs.bot-logins }} PR_NUMBER: ${{ inputs.pr-number }} ALL_OPEN_PRS: ${{ inputs.all-open-prs }} + RECOVER_RUN_ID: ${{ inputs.recover-run-id }} + AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-checks.jsonl run: | - if [[ "$ALL_OPEN_PRS" == "true" ]]; then + if [[ "$RECOVER_RUN_ID" != "0" ]]; then + python .ci-shared/scripts/check_ai_review_disposition.py --recover-run "$RECOVER_RUN_ID" + elif [[ "$ALL_OPEN_PRS" == "true" ]]; then python .ci-shared/scripts/check_ai_review_disposition.py --all-open-prs else python .ci-shared/scripts/check_ai_review_disposition.py --pr-number "$PR_NUMBER" fi + + - name: Close interrupted checks registered by this job + if: ${{ always() && hashFiles('.ci-shared/scripts/check_ai_review_disposition.py') != '' }} + env: + AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-checks.jsonl + run: python3 .ci-shared/scripts/check_ai_review_disposition.py --cleanup-file "$AI_REVIEW_CHECKS_FILE" diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 37c4153..d89e4a2 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -5,10 +5,11 @@ ## 审查与回复规则 - `AI_REVIEW_BOTS` 必填,逗号分隔精确 login,忽略大小写;每个账号分别判定。GraphQL Bot login 缺少 `[bot]` 时补齐。 -- 已发布的 `COMMENTED`、`APPROVED`、`CHANGES_REQUESTED` Review 或下表成功摘要可证明完成。新开始消息、更新的 pending / 进行中状态使旧结果不能提前放行。同一 AI 的轮次不得重叠;新 commit 本身不强制重审。 +- 已发布的 `COMMENTED`、`APPROVED`、`CHANGES_REQUESTED` Review 或下表成功摘要可证明完成。Codex 存在可识别摘要时,以 Code Review 行状态为准:进行中或失败期间,即使随后发布新 Review,也须等摘要 Completed;全部 dismissed 的兜底规则见下一条。无摘要时可使用已发布 Review。新开始消息、更新的 pending / 进行中状态使旧结果不能提前放行。同一 AI 的轮次不得重叠;新 commit 本身不强制重审。 - 本轮全部 Review 被 dismissed 后,本轮失效,可用更早有效 Review 或成功摘要兜底;没有依据则阻断。随后新一轮仍须重新完成。 - 指定 AI、PR 作者之外的人工 reviewer 创建的 inline threads 均须处理,包括 outdated / resolved。顶层评论、Review 总评、未发布的 pending 意见、作者自己的人工线程和未配置 Bot 的线程不作为处理目标。 -- 回复须来自 PR 作者或当前有 write/admin 权限的人工账号;AI 账号和 Bot 不能自行处理。采用编辑时间最新的明确模板,同一时间取更后的回复;新无效模板会替代旧模板。普通讨论、原意见编辑不要求重复确认,新问题应另开线程。 +- 回复须来自 PR 作者或当前有 write/admin 权限的人工账号;编辑后的模板还须由这样的人工账号编辑。AI 账号和 Bot 不能借用人工评论作者身份处理,编辑者不可读时也不放行。采用编辑时间最新的明确模板,同一时间取更后的回复;新无效模板或未授权编辑会替代旧模板并阻断,不能回退旧有效回复。普通讨论、原意见编辑不要求重复确认,新问题应另开线程。 +- AI 完成/开始评论的当前内容也须由相应 AI 编辑。人工编辑的 Bot 评论只使旧完成记录失效,不能构成完成;随后由该 AI 发布的新有效完成依据可恢复。 | AI | 开始与完成依据(仅接受相应账号的 PR 顶层评论) | | --- | --- | @@ -29,18 +30,20 @@ Fix: <当前 PR 中的完整 40 位 commit SHA> | Rejected / Invalid | 拒绝或误报理由 | | Deferred | Tracking 为本仓库真实、可读且开放的 Issue URL,不能是 PR | -不适用的 Fix / Tracking 可省略或填 `N/A`。只接受 `https://github.com/owner/repo/commit/`、`https://github.com/owner/repo/issues/<正整数>`,不接受查询参数、锚点或跨仓库链接。转移重定向不能绕过仓库限制。force-push 移除修复提交、Issue 关闭或删除均使相应回复失效;作者需更新为有效回复。检查器不判断理由是否充分、commit 是否真正修复或延期是否合理。 +不适用的 Fix / Tracking 可省略或填 `N/A`。只接受 `https://github.com/owner/repo/commit/`、`https://github.com/owner/repo/issues/<正整数>`,不接受查询参数、锚点或跨仓库链接。转移重定向不能绕过仓库限制。PR commits 连接截断时,使用固定 base/head SHA 的分页 Compare API 补全,并校验提交总数;超过 250 条的 PR 无需改填其他 Fix。force-push 移除修复提交、Issue 关闭或删除均使相应回复失效;作者需更新为有效回复。检查器不判断理由是否充分、commit 是否真正修复或延期是否合理。 ## 接入 -1. 将 [caller](examples/ai-review-disposition.yml) 和 [事件收集器](examples/ai-review-events.yml) 复制到目标仓库 `.github/workflows/`,合入默认分支。 -2. 设置 Variable `AI_REVIEW_BOTS`,例如 `chatgpt-codex-connector[bot],infiscale-bot`。caller 需要 `contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。 +1. 将 [caller](examples/ai-review-disposition.yml)、[事件收集器](examples/ai-review-events.yml) 和 [失败恢复入口](examples/ai-review-recovery.yml) 复制到目标仓库 `.github/workflows/`,合入默认分支。caller 文件名保持 `ai-review-disposition.yml`,run-name 保持 PR 编号或 `all-open-prs`,供初始化失败时恢复路由。 +2. 设置 Variable `AI_REVIEW_BOTS`,例如 `chatgpt-codex-connector[bot],infiscale-bot`。caller 和恢复入口需要 `actions: read`、`contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。 3. 首次运行后,将脚本发布的 **AI Review / Disposition Check** 设为 Required Status Check,来源 GitHub Actions;不要选择 Actions job 的状态,其 SHA 不一定是 PR head。 4. 同时启用 **Require conversation resolution before merging** 并保留人工 approval。Resolve/Unresolve 由 GitHub 原生规则处理,不需额外运行本检查。 +升级时先合入共享实现,再同步更新目标仓库 caller 和恢复入口;旧 caller 缺少上述 run-name 时,恢复入口无法自动定位初始化失败的目标。 + PR opened/reopened/synchronize、目标分支及 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限收集器,再由默认分支的 workflow_run 启动可信检查器。收集器的 run-name 保持 PR 编号,不传入代码或审查结论。 -本仓库 Issue closed/reopened/deleted/transferred 时复查全部开放 PR,不维护 Issue → PR 反向关联;一个 PR 失败不会跳过后续 PR。新建普通 Issue 不触发。 +本仓库 Issue closed/reopened/deleted/transferred 时复查全部开放 PR,不维护 Issue → PR 反向关联。先为全部目标登记阻断 Check,再最多并行评估 4 个 PR;一个 PR 失败不会跳过后续 PR。全仓扫描最长 360 分钟,后续 Issue 事件不取消正在推进的扫描,等待中的扫描由最新事件合并替代。新建普通 Issue 不触发。 ### 自动化修改 Issue @@ -53,13 +56,17 @@ gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ DEFAULT_BRANCH 为仓库默认分支,负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 另需 `issues: write`。无需额外 Token;其他自动化发布 Review / 评论后同样须主动复查。不要由另一工作流直接运行正式检查脚本,结果顺序依赖同一 caller 的运行编号。 -手动检查填写正整数 pr-number;全仓复查勾选 all-open-prs、保持编号 0。默认不会隐式全仓扫描。CI 始终实时读取 PR 并将 Check 写入最新 head;通过前再次读取数据,清缓存复核权限和 Issue 状态。数据变化或 API 错误不放行,Issue 的 404/410 会给出具体 Tracking 提示。 +手动检查填写正整数 pr-number;全仓复查勾选 all-open-prs、保持编号 0。默认不会隐式全仓扫描。CI 始终实时读取 PR 并将 Check 写入最新 head;通过前再次读取数据,清缓存复核权限和 Issue 状态。只读 REST/GraphQL 请求遇瞬时网络错误、429、500/502/503/504 或带 Retry-After 的 403 时最多尝试 3 次;遵守 Retry-After,等待超过 60 秒则中止并报告失败,不提前重试。创建/修改 Check 不盲重试。数据变化或读取失败不发布成功,Issue 的 404/410 会给出具体 Tracking 提示。 + +同一 PR 的新运行取消旧运行;全仓复查有独立并发组。B 登记后只认 B,运行中、失败或取消均不回退 A 的成功;旧 Check 改名保留,迟到结果不能恢复旧门禁名称。补查使用 Run workflow,重跑旧编号不能覆盖更新编号。 + +普通退出由 always 收尾读取本机登记日志,将未完成 Check 以新的 Check ID 标记 failure;硬超时、取消、检出/初始化失败由默认分支的 workflow_run 恢复入口补做。恢复使用失败 caller 原来的 run_number/run_attempt,不使用恢复工作流自己的编号;保留已完成目标,不能覆盖较新运行。仅读取可信脚本写出的本机日志或实时 API,不下载或执行来源工作流的 artifact。最终发布失败会记录 Check ID 和重新 dispatch 的提示。 -同一 PR 的新运行取消旧运行;全仓复查有独立并发组。B 接管后只认 B,运行中、失败或取消均不回退 A 的成功;旧 Check 改名保留,迟到结果不能恢复旧门禁名称。补查使用 Run workflow,重跑旧编号不能覆盖更新编号;读取/发布失败或遗留 in-progress 时发起新检查。 +恢复是异步的:事件发生到新 Check 登记、或失败到恢复运行之间存在窗口。若首次读取、枚举或登记失败,旧 success 可能在恢复前仍可见;GitHub API 完全不可读写、恢复入口未安装或自身失败时,脚本无法保证立即撤销它。必须监控 caller/恢复运行失败并重新 dispatch;要求这个窗口内也绝不允许合并时,需额外的 GitHub 侧合并门禁,不能仅依赖本异步检查。登记后的遗留 in_progress 会继续阻断。 ## 验证与边界 -运行 `python -m unittest discover -s scripts/tests -v`。主测试包含 AI 轮次、第二人工账号权限/撤权、分页、最终复核和 A/B 迟到写入模拟,无需真实账号或 Token。真实 Bot 接入仍须现场验证;不能把模拟当成实际授权已生效。 +运行 `python -m unittest discover -s scripts/tests -v`。测试包含 AI 轮次、编辑者授权、第二人工账号权限/撤权、超过 250 条提交、限流重试、初始化/发布失败、批量预登记和恢复后迟到写入模拟,无需真实账号或 Token。接入时另验收 caller 与恢复入口的 run-name、取消/超时和初始化失败路由。真实 Bot 接入仍须现场验证;不能把模拟当成实际授权已生效。 自动关 Issue 的 [触发工作流](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306714886) 和 [后续复查](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306733764) 已在隔离仓库实测。一次性实验、规则配置和历史结果保留在[测试仓库](https://github.com/liaoxiang0304/VR_DexCopilot),不作为生产接入文件。 diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index d2ccec5..bc7d079 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -1,6 +1,12 @@ # Copy to each project's .github/workflows/ai-review-disposition.yml. # Both this file and the event collector must exist on the default branch. name: AI Review Disposition +# Recovery reads this routing value if the run fails before publishing a Check. +run-name: >- + ${{ (github.event_name == 'issues' || inputs.all-open-prs) && 'all-open-prs' + || github.event.pull_request.number + || (github.event_name == 'issue_comment' && github.event.issue.number) + || inputs.pr-number || github.event.workflow_run.display_title || '0' }} on: pull_request_target: @@ -26,6 +32,7 @@ on: default: false permissions: + actions: read contents: read pull-requests: read issues: read diff --git a/docs/examples/ai-review-recovery.yml b/docs/examples/ai-review-recovery.yml new file mode 100644 index 0000000..d9e5071 --- /dev/null +++ b/docs/examples/ai-review-recovery.yml @@ -0,0 +1,26 @@ +# Copy to each project's .github/workflows/ai-review-recovery.yml. +# Uses only default-branch shared code and live API state, never source-run artifacts. +name: AI Review Disposition Recovery + +on: + workflow_run: + workflows: [AI Review Disposition] + types: [completed] + +permissions: + actions: read + contents: read + pull-requests: read + issues: read + checks: write + +jobs: + recover: + if: >- + ${{ contains(fromJSON('["failure","cancelled","timed_out","action_required","startup_failure"]'), + github.event.workflow_run.conclusion) }} + uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main + with: + recover-run-id: ${{ github.event.workflow_run.id }} + bot-logins: ${{ vars.AI_REVIEW_BOTS }} + shared-ref: main diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 5cf631a..93b9b2b 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -6,17 +6,22 @@ import os import re import sys +import time +from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import UTC, datetime +from email.utils import parsedate_to_datetime from functools import cache -from urllib.error import HTTPError +from threading import Lock +from urllib.error import HTTPError, URLError from urllib.parse import quote from urllib.request import Request, urlopen CHECK_NAME = "AI Review / Disposition Check" STATUSES = ("Accepted", "Rejected", "Deferred", "Invalid") AUTHOR_FIELDS = "author { login __typename }" +EDIT_FIELDS = "editor { login __typename } lastEditedAt" COMMENT_FIELDS = f""" - id body url updatedAt {AUTHOR_FIELDS} + id body url updatedAt {AUTHOR_FIELDS} {EDIT_FIELDS} pullRequestReview {{ state }} """ PAGE_FIELDS = "pageInfo { hasNextPage endCursor }" @@ -24,6 +29,7 @@ CODEX_SUMMARY = "" PUBLISHED_REVIEWS = {"COMMENTED", "APPROVED", "CHANGES_REQUESTED"} INFISCALE_COMPLETE = "未发现本次 PR 引入的新问题。LGTM!" # noqa: RUF001 +JOURNAL_LOCK = Lock() def actor_login(author): @@ -34,6 +40,12 @@ def actor_login(author): return login +def content_actor(comment): + if comment.get("lastEditedAt") or comment.get("editor"): + return comment.get("editor") or {} + return comment.get("author") or {} + + class GitHub: def __init__(self, token): self.token = token @@ -49,8 +61,43 @@ def request(self, method, path, body=None): "Content-Type": "application/json", }, ) - with urlopen(request, timeout=30) as response: - return json.load(response) + read_only = method == "GET" or ( + method == "POST" + and path == "/graphql" + and re.match(r"\s*query\b", (body or {}).get("query", "")) + ) + for attempt in range(3): + try: + with urlopen(request, timeout=30) as response: + return json.load(response) + except HTTPError as error: + retry_after = (error.headers or {}).get("Retry-After") + if ( + not read_only + or attempt == 2 + or not ( + error.code in {429, 500, 502, 503, 504} + or (error.code == 403 and retry_after) + ) + ): + raise + delay = 2**attempt + if retry_after: + try: + delay = max(0, float(retry_after)) + except ValueError: + delay = max( + 0, + (parsedate_to_datetime(retry_after) - datetime.now(UTC)).total_seconds(), + ) + # Do not retry earlier than GitHub allows, or sleep without a bound. + if delay > 60: + raise + time.sleep(delay) + except (URLError, TimeoutError): + if not read_only or attempt == 2: + raise + time.sleep(2**attempt) def graphql(self, query, variables): result = self.request("POST", "/graphql", {"query": query, "variables": variables}) @@ -100,7 +147,9 @@ def snapshot(api, repository, number): pr["node_id"], "reviews", f"id state createdAt submittedAt {AUTHOR_FIELDS}" ) comments = api.connection( - pr["node_id"], "comments", f"id body createdAt updatedAt {AUTHOR_FIELDS}" + pr["node_id"], + "comments", + f"id body createdAt updatedAt {AUTHOR_FIELDS} {EDIT_FIELDS}", ) threads = api.connection( pr["node_id"], @@ -118,6 +167,17 @@ def snapshot(api, repository, number): page=thread["comments"], ) commits = api.connection(pr["node_id"], "commits", "commit { oid }") + commit_ids = [node["commit"]["oid"] for node in commits] + expected = pr.get("commits", len(commit_ids)) + if len(commit_ids) != expected: + # PullRequest.commits silently stops at 250; paginated compare is BASE..HEAD. + base, head = pr["base"]["sha"], pr["head"]["sha"] + commit_ids = [ + commit["sha"] + for commit in api.pages(f"/repos/{repository}/compare/{base}...{head}", "commits") + ] + if len(set(commit_ids)) != expected or head not in commit_ids: + raise RuntimeError("Incomplete PR commit comparison; refusing partial evidence") current = api.request("GET", f"/repos/{repository}/pulls/{number}") def revision(item): @@ -135,7 +195,7 @@ def revision(item): "reviews": reviews, "comments": comments, "threads": threads, - "commits": [node["commit"]["oid"] for node in commits], + "commits": commit_ids, } @@ -207,6 +267,12 @@ def review_complete(data, bot): ] progress = [] for comment in comments: + if bot in {"infiscale-bot", CODEX} and actor_login(content_actor(comment)) != bot: + changed = timestamp(comment.get("lastEditedAt") or comment.get("updatedAt")) + starts.append(changed) + if bot == CODEX: + progress.append((changed, False)) + continue if bot == "infiscale-bot": if infiscale_start(comment["body"]): starts.append(timestamp(comment.get("createdAt"))) @@ -272,6 +338,14 @@ def evaluate(data, bots, authorized, tracking_valid): and login not in bots and authorized(login, data["author"]) ): + editor = content_actor(comment) + editor_login = actor_login(editor) + if ( + editor.get("__typename") != "User" + or editor_login in bots + or not authorized(editor_login, data["author"]) + ): + fields["error"] = "Disposition edits require an authorized human editor" candidates.append((comment, fields)) latest = max(reversed(candidates), key=lambda c: c[0]["updatedAt"], default=None) status = "Unaddressed" @@ -368,11 +442,15 @@ def order(run): return newest["id"] == check["id"] -def check_pr(api, repository, number, bots): - pr = api.request("GET", f"/repos/{repository}/pulls/{number}") - if pr["state"] != "open": - return True - head = pr["head"]["sha"] +def generation(): + return ( + int(os.environ.get("GITHUB_RUN_NUMBER", "0")), + int(os.environ.get("GITHUB_RUN_ATTEMPT", "1")), + ) + + +def register_check(api, repository, number, head, sequence=None): + run, attempt = sequence if sequence is not None else generation() check = api.request( "POST", f"/repos/{repository}/check-runs", @@ -380,11 +458,118 @@ def check_pr(api, repository, number, bots): "name": CHECK_NAME, "head_sha": head, "status": "in_progress", - "external_id": f"ai-review-disposition:{number}:" - f"{os.environ.get('GITHUB_RUN_NUMBER', '0')}:" - f"{os.environ.get('GITHUB_RUN_ATTEMPT', '1')}", + "external_id": f"ai-review-disposition:{number}:{run}:{attempt}", }, ) + journal = os.environ.get("AI_REVIEW_CHECKS_FILE") + if journal: + with JOURNAL_LOCK, open(journal, "a", encoding="utf-8") as stream: + stream.write( + json.dumps({"number": number, "head": head, "sequence": [run, attempt]}) + "\n" + ) + return check + + +def finish_pending(api, repository, number, head, sequence): + """Fence a failed run with a new Check ID so a late success cannot resurrect it.""" + external_id = f"ai-review-disposition:{number}:{sequence[0]}:{sequence[1]}" + runs = api.pages( + f"/repos/{repository}/commits/{head}/check-runs" + f"?check_name={quote(CHECK_NAME, safe='')}&filter=all", + "check_runs", + ) + own = [ + run + for run in runs + if run.get("external_id") == external_id + and run["app"].get("slug") == "github-actions" + ] + if own and max(own, key=lambda run: run["id"])["status"] == "completed": + return True + check = register_check(api, repository, number, head, sequence) + if current_check(api, repository, number, head, check): + api.request( + "PATCH", + f"/repos/{repository}/check-runs/{check['id']}", + { + "status": "completed", + "conclusion": "failure", + "output": { + "title": "Evaluation interrupted", + "summary": "Evaluation interrupted; dispatch a new disposition check.", + }, + }, + ) + return True + + +def run_parallel(targets, operation): + """Bound API concurrency and keep processing after any target fails.""" + ok = True + with ThreadPoolExecutor(max_workers=4) as pool: + futures = {pool.submit(operation, target): target for target in targets} + for future in as_completed(futures): + try: + ok = future.result() and ok + except Exception as error: + print( + f"Disposition target {futures[future]} failed ({type(error).__name__}); " + "check may remain in_progress; dispatch a new check.", + file=sys.stderr, + ) + ok = False + return ok + + +def cleanup_file(api, repository, path): + if not os.path.exists(path): + return True + with open(path, encoding="utf-8") as stream: + targets = { + (item["number"], item["head"], tuple(item["sequence"])) + for line in stream + if line.strip() + for item in [json.loads(line)] + } + return run_parallel(targets, lambda target: finish_pending(api, repository, *target)) + + +def recover_run(api, repository, run_id): + """Default-branch recovery also covers failures before Check registration.""" + run = api.request("GET", f"/repos/{repository}/actions/runs/{run_id}") + if run["path"] != ".github/workflows/ai-review-disposition.yml": + raise ValueError("Recovery requires the documented caller workflow") + if run["status"] != "completed" or run["conclusion"] not in { + "failure", + "cancelled", + "timed_out", + "action_required", + "startup_failure", + }: + return True + title = run["display_title"] + if title == "all-open-prs": + prs = api.pages(f"/repos/{repository}/pulls?state=open") + elif re.fullmatch(r"[1-9][0-9]*", title): + prs = [api.request("GET", f"/repos/{repository}/pulls/{title}")] + else: + raise ValueError("Recovery requires a PR number or all-open-prs run-name") + sequence = (run["run_number"], run["run_attempt"]) + targets = [ + (pr["number"], pr["head"]["sha"], sequence) for pr in prs if pr["state"] == "open" + ] + return run_parallel(targets, lambda target: finish_pending(api, repository, *target)) + + +def check_pr(api, repository, number, bots, registered=None): + if registered is None: + pr = api.request("GET", f"/repos/{repository}/pulls/{number}") + if pr["state"] != "open": + return True + head = pr["head"]["sha"] + check = register_check(api, repository, number, head) + else: + head, check = registered @cache def authorized(login, author): @@ -446,21 +631,32 @@ def tracking_valid(value): report = ( f"PR #{number}: evaluation failed ({type(error).__name__}); rerun required." ) - if not current_check(api, repository, number, head, check): - return True - api.request( - "PATCH", - f"/repos/{repository}/check-runs/{check['id']}", - { - "status": "completed", - "conclusion": "success" if ok else "failure", - "output": {"title": "Passed" if ok else "Failed", "summary": report[:60000]}, - }, - ) + try: + if not current_check(api, repository, number, head, check): + return True + api.request( + "PATCH", + f"/repos/{repository}/check-runs/{check['id']}", + { + "status": "completed", + "conclusion": "success" if ok else "failure", + "output": {"title": "Passed" if ok else "Failed", "summary": report[:60000]}, + }, + ) + except Exception as error: + print( + f"PR #{number}: could not publish Check #{check['id']} " + f"({type(error).__name__}); check may remain in_progress; dispatch a new check.", + file=sys.stderr, + ) + return False # PR comment text is never emitted, including Actions workflow command sequences. print(report) if os.environ.get("GITHUB_STEP_SUMMARY"): - with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: + with ( + JOURNAL_LOCK, + open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream, + ): stream.write(report + "\n\n") return ok @@ -473,37 +669,63 @@ def main(): target.add_argument( "--all-open-prs", action="store_true", help="Explicitly recheck every open PR" ) + target.add_argument( + "--cleanup-file", help="Finish interrupted Checks from a trusted local journal" + ) + target.add_argument( + "--recover-run", type=int, help="Recover an interrupted caller run" + ) parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) args = parser.parse_args() bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + evaluating = not (args.cleanup_file or args.recover_run) if ( - not bots - or any(not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots) + ( + evaluating + and ( + not bots + or any(not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots) + ) + ) or not args.repository or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository) or (args.pr_number is not None and args.pr_number <= 0) + or (args.recover_run is not None and args.recover_run <= 0) or not token ): parser.error( "Valid repository, bot logins, token and a positive PR or explicit sweep required" ) api = GitHub(token) + if args.cleanup_file: + return 0 if cleanup_file(api, args.repository, args.cleanup_file) else 1 + if args.recover_run: + return 0 if recover_run(api, args.repository, args.recover_run) else 1 if args.all_open_prs: - numbers = sorted({ - pr["number"] for pr in api.pages(f"/repos/{args.repository}/pulls?state=open") - }) + prs = { + pr["number"]: pr for pr in api.pages(f"/repos/{args.repository}/pulls?state=open") + } + registered = {} ok = True - for number in numbers: + # Block every target before any expensive review/Issue/permission reads. + for number, pr in sorted(prs.items()): try: - ok = check_pr(api, args.repository, number, bots) and ok + head = pr["head"]["sha"] + check = register_check(api, args.repository, number, head) + if current_check(api, args.repository, number, head, check): + registered[number] = (head, check) except Exception as error: print( f"PR #{number}: check failed ({type(error).__name__}); rerun required.", file=sys.stderr, ) ok = False - return 0 if ok else 1 + evaluated = run_parallel( + registered, + lambda number: check_pr(api, args.repository, number, bots, registered[number]), + ) + return 0 if evaluated and ok else 1 ok = check_pr(api, args.repository, args.pr_number, bots) return 0 if ok else 1 diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 959371d..8a7a944 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -1196,13 +1196,19 @@ def run_main(self, *arguments, passed=True, numbers=None, results=None): sys, "argv", ["checker", "--repository", "org/repo", "--bots", BOT, *arguments] ), patch("scripts.check_ai_review_disposition.GitHub") as client, + patch( + "scripts.check_ai_review_disposition.register_check", return_value={"id": 99} + ), + patch("scripts.check_ai_review_disposition.current_check", return_value=True), patch( "scripts.check_ai_review_disposition.check_pr", return_value=passed ) as check, patch("sys.stderr", new_callable=io.StringIO), ): if numbers is not None: - client.return_value.pages.return_value = [{"number": n} for n in numbers] + client.return_value.pages.return_value = [ + {"number": n, "head": {"sha": HEAD}} for n in numbers + ] if results is not None: check.side_effect = results return main(), client, check @@ -1212,7 +1218,7 @@ def test_explicit_sweep_checks_all_open_prs_even_after_failure(self): "--all-open-prs", passed=False, numbers=[24, 7, 24] ) self.assertEqual(code, 1) - self.assertEqual([c.args[2] for c in check.call_args_list], [7, 24]) + self.assertEqual(sorted(c.args[2] for c in check.call_args_list), [7, 24]) client.return_value.pages.assert_called_once_with( "/repos/org/repo/pulls?state=open" ) @@ -1222,7 +1228,7 @@ def test_sweep_continues_after_a_pr_api_error(self): "--all-open-prs", numbers=[1, 2, 3], results=[RuntimeError("failed"), True, True] ) self.assertEqual(code, 1) - self.assertEqual([c.args[2] for c in check.call_args_list], [1, 2, 3]) + self.assertEqual(sorted(c.args[2] for c in check.call_args_list), [1, 2, 3]) def test_empty_open_pr_sweep_does_not_publish_checks(self): code, _, check = self.run_main("--all-open-prs", numbers=[]) diff --git a/scripts/tests/test_ai_review_reliability.py b/scripts/tests/test_ai_review_reliability.py new file mode 100644 index 0000000..9a68164 --- /dev/null +++ b/scripts/tests/test_ai_review_reliability.py @@ -0,0 +1,463 @@ +import copy +import io +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch +from urllib.error import HTTPError, URLError + +from scripts import check_ai_review_disposition as checker +from scripts.tests import test_ai_review_disposition as fixtures + + +class RetryTests(unittest.TestCase): + def request(self, responses, method="GET", path="/resource", body=None): + api = checker.GitHub("test-token") + with ( + patch.object(checker, "urlopen", side_effect=responses) as request, + patch.object(checker.time, "sleep") as sleep, + ): + value = api.request(method, path, body) + return value, request, sleep + + def error(self, status, headers=None): + return HTTPError("https://api.github.com/resource", status, "error", headers, None) + + def test_read_recovers_from_transient_errors(self): + for error in (self.error(500), self.error(502), URLError("connection reset")): + with self.subTest(error=type(error).__name__): + value, request, sleep = self.request([error, io.BytesIO(b'{"ok": true}')]) + self.assertEqual(value, {"ok": True}) + self.assertEqual(request.call_count, 2) + sleep.assert_called_once_with(1) + + def test_rate_limit_honors_retry_after(self): + for status in (403, 429): + with self.subTest(status=status): + _, _, sleep = self.request([ + self.error(status, {"Retry-After": "3"}), + io.BytesIO(b"{}"), + ]) + sleep.assert_called_once_with(3) + + def test_long_retry_after_does_not_retry_early(self): + with ( + patch.object( + checker, "urlopen", side_effect=self.error(429, {"Retry-After": "120"}) + ) as request, + patch.object(checker.time, "sleep") as sleep, + self.assertRaises(HTTPError), + ): + checker.GitHub("test-token").request("GET", "/resource") + self.assertEqual(request.call_count, 1) + sleep.assert_not_called() + + def test_retries_are_bounded_and_authorization_errors_are_not_retried(self): + for status, expected in ((403, 1), (404, 1), (503, 3)): + with ( + self.subTest(status=status), + patch.object(checker, "urlopen", side_effect=self.error(status)) as request, + patch.object(checker.time, "sleep"), + self.assertRaises(HTTPError), + ): + checker.GitHub("test-token").request("GET", "/resource") + self.assertEqual(request.call_count, expected) + + def test_check_writes_and_graphql_mutations_are_never_blindly_retried(self): + for method, path, body in ( + ("POST", "/repos/org/repo/check-runs", {"name": "check"}), + ("PATCH", "/repos/org/repo/check-runs/1", {"conclusion": "success"}), + ("POST", "/graphql", {"query": "mutation { example }"}), + ): + with ( + self.subTest(method=method, path=path), + patch.object(checker, "urlopen", side_effect=self.error(503)) as request, + patch.object(checker.time, "sleep") as sleep, + self.assertRaises(HTTPError), + ): + checker.GitHub("test-token").request(method, path, body) + self.assertEqual(request.call_count, 1) + sleep.assert_not_called() + + def test_read_only_graphql_is_retried(self): + _, request, _ = self.request( + [self.error(504), io.BytesIO(b'{"data": {}}')], + "POST", + "/graphql", + {"query": "\nquery { viewer { login } }"}, + ) + self.assertEqual(request.call_count, 2) + + +class EditorTests(unittest.TestCase): + def test_bot_or_unknown_editor_cannot_borrow_human_authorship(self): + for editor in ( + {"login": "reviewer", "__typename": "Bot"}, + {"login": "stranger", "__typename": "User"}, + None, + ): + with self.subTest(editor=editor): + data = fixtures.fixture("Disposition: Invalid\nReason: Old decision") + reply = fixtures.comment("Disposition: Rejected\nReason: Changed decision") + reply.update( + editor=editor, + lastEditedAt="2026-10-10T01:00:00Z", + updatedAt="2026-10-10T01:00:00Z", + ) + data["threads"][0]["comments"].append(reply) + result = fixtures.result(data) + self.assertFalse(checker.passed(result)) + self.assertIn("editor", result["findings"][0]["error"]) + + def test_authorized_human_editor_is_allowed(self): + data = fixtures.fixture("Disposition: Invalid\nReason: Updated by maintainer") + data["threads"][0]["comments"][-1].update( + editor={"login": "maintainer", "__typename": "User"}, + lastEditedAt="2026-10-10T01:00:00Z", + ) + self.assertTrue(checker.passed(fixtures.result(data))) + + def test_configured_user_bot_cannot_edit_a_human_disposition(self): + data = fixtures.fixture( + "Disposition: Invalid\nReason: Test", reviewer="infiscale-bot" + ) + data["reviews"][0]["author"] = {"login": "infiscale-bot", "__typename": "User"} + data["threads"][0]["comments"][-1].update( + editor={"login": "infiscale-bot", "__typename": "User"}, + lastEditedAt="2026-10-10T01:00:00Z", + ) + self.assertFalse(checker.passed(fixtures.result(data, {"infiscale-bot"}))) + + def test_tampered_codex_summary_blocks_old_evidence_until_new_completion(self): + data = fixtures.fixture() + data["reviews"][0]["author"] = {"login": fixtures.CODEX} + summary = fixtures.comment(fixtures.CODEX_SUMMARY, fixtures.CODEX) + summary.update( + editor={"login": "contributor", "__typename": "User"}, + lastEditedAt="2026-10-15T00:00:00Z", + ) + data["comments"] = [summary] + self.assertFalse(checker.review_complete(data, fixtures.CODEX)) + fresh = fixtures.comment( + fixtures.CODEX_SUMMARY.replace("2026-10-14", "2026-10-16"), fixtures.CODEX + ) + data["comments"].append(fresh) + self.assertTrue(checker.review_complete(data, fixtures.CODEX)) + + def test_tampered_infiscale_completion_cannot_complete_a_round(self): + data = fixtures.fixture() + completed = fixtures.comment(fixtures.INFISCALE_COMPLETE, "infiscale-bot") + completed.update( + editor={"login": "contributor", "__typename": "User"}, + lastEditedAt="2026-10-10T00:00:00Z", + ) + data.update(reviews=[], comments=[completed]) + self.assertFalse(checker.review_complete(data, "infiscale-bot")) + + def test_review_after_running_or_failed_codex_summary_still_waits(self): + for status in ("🔄 **Running** since", "⚠️ **Failed**"): + with self.subTest(status=status): + data = fixtures.fixture() + data["reviews"][0].update( + author={"login": fixtures.CODEX}, submittedAt="2026-10-15T00:00:00Z" + ) + summary = fixtures.comment( + fixtures.CODEX_SUMMARY.replace("✅ **Completed**", status), fixtures.CODEX + ) + data["comments"] = [summary] + self.assertFalse(checker.review_complete(data, fixtures.CODEX)) + summary["body"] = fixtures.CODEX_SUMMARY + self.assertTrue(checker.review_complete(data, fixtures.CODEX)) + + +class LargeCommitTests(unittest.TestCase): + def load(self, count=301, complete=True): + ids = [f"{n:040x}" for n in range(count - 1)] + [fixtures.HEAD] + pr = fixtures.pr_metadata(commits=count, base={"ref": "main", "sha": fixtures.FIX}) + api = checker.GitHub("test-token") + with ( + patch.object(api, "request", return_value=pr), + patch.object( + api, + "connection", + side_effect=[[], [], [], [{"commit": {"oid": oid}} for oid in ids[:250]]], + ), + patch.object( + api, + "pages", + return_value=[{"sha": oid} for oid in (ids if complete else ids[:250])], + ) as pages, + ): + data = checker.snapshot(api, "org/repo", 128) + return data, ids, pages + + def test_valid_fix_beyond_graphql_limit_is_accepted(self): + data, ids, pages = self.load() + self.assertEqual(data["commits"], ids) + pages.assert_called_once_with( + f"/repos/org/repo/compare/{fixtures.FIX}...{fixtures.HEAD}", "commits" + ) + finding = fixtures.fixture(f"Disposition: Accepted\nReason: Fixed\nFix: {ids[275]}") + finding["commits"] = data["commits"] + self.assertTrue(checker.passed(fixtures.result(finding))) + finding["commits"].remove(ids[275]) + self.assertFalse(checker.passed(fixtures.result(finding))) + + def test_truncated_compare_never_silently_accepts_partial_membership(self): + with self.assertRaisesRegex(RuntimeError, "Incomplete PR commit comparison"): + self.load(complete=False) + + def test_small_pr_keeps_the_existing_graphql_fast_path(self): + data, ids, pages = self.load(count=3) + self.assertEqual(data["commits"], ids) + pages.assert_not_called() + + def test_compare_explicitly_paginates_beyond_250(self): + api = checker.GitHub("test-token") + replies = [ + {"commits": [{"sha": str(n)} for n in range(start, end)]} + for start, end in ((0, 100), (100, 200), (200, 300), (300, 301)) + ] + with patch.object(api, "request", side_effect=replies) as request: + self.assertEqual( + len(api.pages("/repos/org/repo/compare/base...head", "commits")), 301 + ) + self.assertEqual(request.call_count, 4) + self.assertIn("per_page=100&page=4", request.call_args.args[1]) + + +class RecoveryStore(fixtures.CheckStore): + def __init__(self): + super().__init__() + self.source = { + "path": ".github/workflows/ai-review-disposition.yml", + "status": "completed", + "conclusion": "failure", + "display_title": "128", + "run_number": 2, + "run_attempt": 1, + } + + def add(self, *args, **kwargs): + check = super().add(*args, **kwargs) + self.checks[check["id"]]["app"]["slug"] = "github-actions" + return copy.deepcopy(self.checks[check["id"]]) + + def request(self, method, path, body=None): + if method == "GET" and "/actions/runs/" in path: + return copy.deepcopy(self.source) + if method == "GET" and "/pulls/" in path: + return {"number": 128, "state": "open", "head": {"sha": fixtures.HEAD}} + return super().request(method, path, body) + + +class RecoveryTests(unittest.TestCase): + def setUp(self): + self.environment = patch.dict( + os.environ, {"AI_REVIEW_CHECKS_FILE": "", "GITHUB_STEP_SUMMARY": ""} + ) + self.environment.start() + self.addCleanup(self.environment.stop) + + def test_first_metadata_read_failure_is_fenced_by_default_branch_recovery(self): + api = RecoveryStore() + old = api.add(1) + api.checks[old["id"]].update(status="completed", conclusion="success") + with ( + patch.object(api, "request", side_effect=RuntimeError("read failed")), + self.assertRaises(RuntimeError), + ): + checker.check_pr(api, "org/repo", 128, {fixtures.BOT}) + self.assertTrue(checker.recover_run(api, "org/repo", 999)) + self.assertEqual(len(api.gate()), 1) + self.assertEqual(api.gate()[0]["conclusion"], "failure") + self.assertEqual(api.gate()[0]["external_id"], "ai-review-disposition:128:2:1") + + def test_timeout_fences_late_success_with_a_different_check_id(self): + api = RecoveryStore() + old = api.add(2) + self.assertTrue(checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1))) + api.request( + "PATCH", + f"/repos/org/repo/check-runs/{old['id']}", + {"status": "completed", "conclusion": "success"}, + ) + self.assertNotEqual(api.gate()[0]["id"], old["id"]) + self.assertEqual(api.gate()[0]["conclusion"], "failure") + + def test_old_recovery_cannot_replace_newer_success_or_pending(self): + for status in ("completed", "in_progress"): + with self.subTest(status=status): + api = RecoveryStore() + newest = api.add(3) + api.checks[newest["id"]].update( + status=status, conclusion="success" if status == "completed" else None + ) + checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) + self.assertEqual([c["id"] for c in api.gate()], [newest["id"]]) + self.assertEqual(api.gate()[0]["status"], status) + + def test_completed_target_is_preserved_and_recovery_is_idempotent(self): + api = RecoveryStore() + own = api.add(2) + api.checks[own["id"]].update(status="completed", conclusion="success") + before = copy.deepcopy(api.checks) + checker.recover_run(api, "org/repo", 999) + self.assertEqual(api.checks, before) + api.checks[own["id"]]["status"] = "in_progress" + checker.recover_run(api, "org/repo", 999) + count = len(api.checks) + checker.recover_run(api, "org/repo", 999) + self.assertEqual(len(api.checks), count) + + def test_recovery_uses_source_attempt_not_its_own_workflow_generation(self): + api = RecoveryStore() + api.source["run_attempt"] = 2 + with patch.dict( + os.environ, {"GITHUB_RUN_NUMBER": "999", "GITHUB_RUN_ATTEMPT": "7"} + ): + checker.recover_run(api, "org/repo", 999) + self.assertEqual(api.gate()[0]["external_id"], "ai-review-disposition:128:2:2") + + def test_recovery_rejects_unrelated_workflows_and_invalid_routing(self): + for field, value in ( + ("path", ".github/workflows/untrusted.yml"), + ("display_title", "a PR title"), + ): + api = RecoveryStore() + api.source[field] = value + with self.subTest(field=field), self.assertRaises(ValueError): + checker.recover_run(api, "org/repo", 999) + self.assertEqual(api.checks, {}) + + def test_running_rerun_or_success_is_not_marked_failed(self): + for changes in ({"status": "in_progress"}, {"conclusion": "success"}): + api = RecoveryStore() + api.source.update(changes) + self.assertTrue(checker.recover_run(api, "org/repo", 999)) + self.assertEqual(api.checks, {}) + + def test_recovery_is_not_blocked_by_invalid_bot_configuration(self): + with ( + patch.dict( + os.environ, {"GH_TOKEN": "test-token", "AI_REVIEW_BOTS": "invalid+bot"} + ), + patch.object( + sys, "argv", ["checker", "--repository", "org/repo", "--recover-run", "999"] + ), + patch.object(checker, "recover_run", return_value=True) as recover, + ): + self.assertEqual(checker.main(), 0) + self.assertEqual(recover.call_args.args[1:], ("org/repo", 999)) + + def test_sweep_recovery_visits_all_targets_and_preserves_completed_results(self): + api = RecoveryStore() + api.source["display_title"] = "all-open-prs" + prs = [ + {"number": n, "head": {"sha": fixtures.HEAD}, "state": "open"} + for n in range(1, 5) + ] + visited = [] + + def finish(client, repository, number, head, sequence): + visited.append(number) + if number == 1: + raise RuntimeError("one target is unreadable") + return True + + with ( + patch.object(api, "pages", return_value=prs), + patch.object(checker, "finish_pending", side_effect=finish), + patch("sys.stderr", new_callable=io.StringIO), + ): + self.assertFalse(checker.recover_run(api, "org/repo", 999)) + self.assertEqual(sorted(visited), [1, 2, 3, 4]) + + def test_local_journal_cleanup_closes_interrupted_checks(self): + api = RecoveryStore() + with tempfile.TemporaryDirectory() as directory: + path = str(Path(directory) / "checks.jsonl") + with patch.dict( + os.environ, {"AI_REVIEW_CHECKS_FILE": path, "GITHUB_RUN_NUMBER": "2"} + ): + checker.register_check(api, "org/repo", 128, fixtures.HEAD) + self.assertTrue(checker.cleanup_file(api, "org/repo", path)) + self.assertEqual(api.gate()[0]["conclusion"], "failure") + + def test_final_check_list_or_patch_failure_reports_recovery_instead_of_success(self): + for fail_list in (False, True): + api = RecoveryStore() + request = api.request + + def fail_publish(method, path, body=None, request=request): + if method == "PATCH" and (body or {}).get("conclusion") == "success": + raise RuntimeError("write failed") + return request(method, path, body) + + with ( + self.subTest(fail_list=fail_list), + patch.object(api, "request", side_effect=fail_publish), + patch.object( + checker, + "snapshot", + return_value=fixtures.fixture("Disposition: Invalid\nReason: Test"), + ), + patch.object( + checker, + "current_check", + side_effect=[True, RuntimeError("list failed")] + if fail_list + else [True, True], + ), + patch("sys.stderr", new_callable=io.StringIO) as stderr, + ): + self.assertFalse(checker.check_pr(api, "org/repo", 128, {fixtures.BOT})) + self.assertIn("in_progress", stderr.getvalue()) + self.assertIn("dispatch", stderr.getvalue()) + self.assertEqual(api.gate()[0]["status"], "in_progress") + + def test_sweep_registers_every_pr_before_evaluation(self): + prs = [{"number": n, "head": {"sha": fixtures.HEAD}} for n in range(1, 9)] + registered = [] + evaluated = [] + + def register(api, repository, number, head): + registered.append(number) + return {"id": number} + + def evaluate(api, repository, number, bots, prepared): + self.assertEqual(len(registered), 8) + self.assertEqual(prepared, (fixtures.HEAD, {"id": number})) + evaluated.append(number) + if number == 2: + raise RuntimeError("one PR fails") + return True + + with ( + patch.dict(os.environ, {"GH_TOKEN": "test-token"}), + patch.object( + sys, + "argv", + [ + "checker", + "--repository", + "org/repo", + "--bots", + fixtures.BOT, + "--all-open-prs", + ], + ), + patch.object(checker.GitHub, "pages", return_value=prs), + patch.object(checker, "register_check", side_effect=register), + patch.object(checker, "current_check", return_value=True), + patch.object(checker, "check_pr", side_effect=evaluate), + patch("sys.stderr", new_callable=io.StringIO), + ): + self.assertEqual(checker.main(), 1) + self.assertEqual(sorted(evaluated), list(range(1, 9))) + + +if __name__ == "__main__": + unittest.main() From 850c68a5a448433b8aa5041408053e541b60cef9 Mon Sep 17 00:00:00 2001 From: xiaoyu <2455995107@qq.com> Date: Wed, 28 Oct 2026 16:33:12 +0800 Subject: [PATCH 17/21] fix[ci]: reuse AI review disposition checks Problem: - Repeated evaluations create superseded Checks on the same PR head. - Single-PR, sweep and recovery writers can overlap. Solution: - Reopen and update one managed Check ID per PR head without renaming history. - Route every entry point through the same serialized per-PR worker queue. - Keep different PRs parallel and re-evaluate live state during recovery. Test: - Python 3.11: 124 unit tests passed, including 20 evaluations reusing one Check. - Ruff lint/format, actionlint and git diff --check passed. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 76 ++++-- docs/AI_REVIEW_DISPOSITION.md | 14 +- scripts/check_ai_review_disposition.py | 227 +++++++++--------- scripts/tests/test_ai_review_disposition.py | 227 +++++++++--------- scripts/tests/test_ai_review_reliability.py | 215 +++++++++-------- 5 files changed, 403 insertions(+), 356 deletions(-) diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index 8bbd7f4..d64bf85 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -18,7 +18,7 @@ on: type: boolean default: false recover-run-id: - description: 'Interrupted caller run to recover; uses that run generation' + description: 'Interrupted caller run whose PRs need a fresh evaluation' required: false type: number default: 0 @@ -36,14 +36,60 @@ permissions: checks: write jobs: + targets: + name: Route AI Review Dispositions + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + actions: read + pull-requests: read + outputs: + matrix: ${{ steps.route.outputs.matrix }} + has-targets: ${{ steps.route.outputs.has-targets }} + steps: + - name: Checkout trusted shared scripts + uses: actions/checkout@v4 + with: + repository: IS-Model-Framework/.github + ref: ${{ inputs.shared-ref }} + path: .ci-shared + persist-credentials: false + sparse-checkout: scripts + - uses: actions/setup-python@v7 + with: + python-version: '3.11' + - name: Route to per-PR workers without writing Checks + id: route + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr-number }} + ALL_OPEN_PRS: ${{ inputs.all-open-prs }} + RECOVER_RUN_ID: ${{ inputs.recover-run-id }} + run: | + if [[ "$RECOVER_RUN_ID" != "0" ]]; then + python .ci-shared/scripts/check_ai_review_disposition.py --prepare-targets --recover-run "$RECOVER_RUN_ID" + elif [[ "$ALL_OPEN_PRS" == "true" ]]; then + python .ci-shared/scripts/check_ai_review_disposition.py --prepare-targets --all-open-prs + else + python .ci-shared/scripts/check_ai_review_disposition.py --prepare-targets --pr-number "$PR_NUMBER" + fi + disposition: - name: Evaluate AI Review Dispositions + name: Evaluate AI Review Dispositions (${{ matrix.number }}) + needs: targets + if: ${{ needs.targets.outputs.has-targets == 'true' }} + strategy: + fail-fast: false + max-parallel: 4 + matrix: ${{ fromJSON(needs.targets.outputs.matrix) }} runs-on: ubuntu-latest - timeout-minutes: ${{ (inputs.all-open-prs || inputs.recover-run-id != 0) && 360 || 15 }} - # Sweeps must make progress; generation checks still reject older results. + timeout-minutes: 15 + # Single checks, sweeps and recovery all acquire the same per-PR writer slot. + # Keep the active writer; newer pending work coalesces duplicate events. concurrency: - group: ai-review-disposition-${{ github.repository }}-${{ inputs.recover-run-id && format('recover-{0}', inputs.recover-run-id) || (inputs.all-open-prs && 'all-open-prs' || inputs.pr-number) }} - cancel-in-progress: ${{ !inputs.all-open-prs && inputs.recover-run-id == 0 }} + group: ai-review-disposition-${{ github.repository }}-${{ matrix.number }} + cancel-in-progress: false env: GH_TOKEN: ${{ github.token }} AI_REVIEW_BOTS: ${{ inputs.bot-logins }} @@ -64,22 +110,12 @@ jobs: - name: Publish check on the target PR head commit env: - GH_TOKEN: ${{ github.token }} - AI_REVIEW_BOTS: ${{ inputs.bot-logins }} - PR_NUMBER: ${{ inputs.pr-number }} - ALL_OPEN_PRS: ${{ inputs.all-open-prs }} - RECOVER_RUN_ID: ${{ inputs.recover-run-id }} + PR_NUMBER: ${{ matrix.number }} + HEAD_SHA: ${{ matrix.head }} AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-checks.jsonl - run: | - if [[ "$RECOVER_RUN_ID" != "0" ]]; then - python .ci-shared/scripts/check_ai_review_disposition.py --recover-run "$RECOVER_RUN_ID" - elif [[ "$ALL_OPEN_PRS" == "true" ]]; then - python .ci-shared/scripts/check_ai_review_disposition.py --all-open-prs - else - python .ci-shared/scripts/check_ai_review_disposition.py --pr-number "$PR_NUMBER" - fi + run: python .ci-shared/scripts/check_ai_review_disposition.py --pr-number "$PR_NUMBER" --head-sha "$HEAD_SHA" - - name: Close interrupted checks registered by this job + - name: Close interrupted checks before releasing the writer slot if: ${{ always() && hashFiles('.ci-shared/scripts/check_ai_review_disposition.py') != '' }} env: AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-checks.jsonl diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index d89e4a2..a6135e4 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -43,7 +43,7 @@ Fix: <当前 PR 中的完整 40 位 commit SHA> PR opened/reopened/synchronize、目标分支及 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限收集器,再由默认分支的 workflow_run 启动可信检查器。收集器的 run-name 保持 PR 编号,不传入代码或审查结论。 -本仓库 Issue closed/reopened/deleted/transferred 时复查全部开放 PR,不维护 Issue → PR 反向关联。先为全部目标登记阻断 Check,再最多并行评估 4 个 PR;一个 PR 失败不会跳过后续 PR。全仓扫描最长 360 分钟,后续 Issue 事件不取消正在推进的扫描,等待中的扫描由最新事件合并替代。新建普通 Issue 不触发。 +本仓库 Issue closed/reopened/deleted/transferred 时复查全部开放 PR,不维护 Issue → PR 反向关联。路由 job 只读取开放 PR 元数据,输出 worker matrix,不直接写 Check;单 PR、全仓复查和失败恢复均进入相同的按 PR 编号分组的 worker。每个运行最多并行评估 4 个 PR,一个 PR 失败不会取消其他目标;单 worker 最长 15 分钟。Actions matrix 单次最多支持 256 个目标,超限明确失败。排队中的目标在 worker 开始登记前仍可能显示旧结果。新建普通 Issue 不触发。 ### 自动化修改 Issue @@ -54,19 +54,23 @@ gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ --ref "$DEFAULT_BRANCH" -f all-open-prs=true ``` -DEFAULT_BRANCH 为仓库默认分支,负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 另需 `issues: write`。无需额外 Token;其他自动化发布 Review / 评论后同样须主动复查。不要由另一工作流直接运行正式检查脚本,结果顺序依赖同一 caller 的运行编号。 +DEFAULT_BRANCH 为仓库默认分支,负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 另需 `issues: write`。无需额外 Token;其他自动化发布 Review / 评论后同样须主动复查。不要由另一工作流或本地 CLI 绕过共享 worker 直接写正式 Check。检查器使用 GITHUB_RUN_ID/run_attempt 标识运行,caller 和恢复工作流的局部 run_number 不再相互比较。 手动检查填写正整数 pr-number;全仓复查勾选 all-open-prs、保持编号 0。默认不会隐式全仓扫描。CI 始终实时读取 PR 并将 Check 写入最新 head;通过前再次读取数据,清缓存复核权限和 Issue 状态。只读 REST/GraphQL 请求遇瞬时网络错误、429、500/502/503/504 或带 Retry-After 的 403 时最多尝试 3 次;遵守 Retry-After,等待超过 60 秒则中止并报告失败,不提前重试。创建/修改 Check 不盲重试。数据变化或读取失败不发布成功,Issue 的 404/410 会给出具体 Tracking 提示。 -同一 PR 的新运行取消旧运行;全仓复查有独立并发组。B 登记后只认 B,运行中、失败或取消均不回退 A 的成功;旧 Check 改名保留,迟到结果不能恢复旧门禁名称。补查使用 Run workflow,重跑旧编号不能覆盖更新编号。 +同一 PR 的全部 worker 共用一个 concurrency group,cancel-in-progress=false;正在运行的 worker 保持执行,等待中的重复触发由最新任务合并替代。不同 PR 可并行。worker 开始后重新读取当前 head;同一仓库、PR、head 和 GitHub Actions App 复用同一 Check ID,重新设为 in_progress,再更新结果。新 head 单独创建 Check;不会再创建或改名出 superseded 项,既有历史记录不整理。重跑旧 run ID/attempt 不能接管更新运行。 -普通退出由 always 收尾读取本机登记日志,将未完成 Check 以新的 Check ID 标记 failure;硬超时、取消、检出/初始化失败由默认分支的 workflow_run 恢复入口补做。恢复使用失败 caller 原来的 run_number/run_attempt,不使用恢复工作流自己的编号;保留已完成目标,不能覆盖较新运行。仅读取可信脚本写出的本机日志或实时 API,不下载或执行来源工作流的 artifact。最终发布失败会记录 Check ID 和重新 dispatch 的提示。 +此方案无需外部服务。GitHub 自动产生的路由、评估及事件收集 job Check 仍可能出现在 PR 页面;唯一业务门禁是 AI Review / Disposition Check,不能据此承诺整页仅一项。实验工作流发布的 Integration Test 也不属于正式检查器管理范围。 + +普通退出由 always 收尾在释放同一个 PR 并发槽前读取本机登记日志,仅将仍由自己持有的未完成 Check 原地标记 failure。硬超时、取消、检出/初始化失败由默认分支的 workflow_run 恢复入口定位目标,再进入同一个 worker 队列重新检查实时数据;恢复不直接写 Check,也不会创建替代 Check。恢复重新评估可能得到正常的 success 或业务 failure。仅读取可信脚本写出的本机日志或实时 API,不下载或执行来源工作流的 artifact。最终发布失败会记录 Check ID 和重新 dispatch 的提示。 + +Checks API 的 ownership 校验与 PATCH 不是原子操作。并发槽约束正常运行的 Actions writer;人为硬取消时已经送出的 HTTP 写入仍有极短的竞态,复用单一 Check ID 无法提供旧方案不同 ID 的隔离保证。不要另行直接调用 Checks API 写这个门禁;发生中断或 API 异常后应等待恢复并检查最新结果。 恢复是异步的:事件发生到新 Check 登记、或失败到恢复运行之间存在窗口。若首次读取、枚举或登记失败,旧 success 可能在恢复前仍可见;GitHub API 完全不可读写、恢复入口未安装或自身失败时,脚本无法保证立即撤销它。必须监控 caller/恢复运行失败并重新 dispatch;要求这个窗口内也绝不允许合并时,需额外的 GitHub 侧合并门禁,不能仅依赖本异步检查。登记后的遗留 in_progress 会继续阻断。 ## 验证与边界 -运行 `python -m unittest discover -s scripts/tests -v`。测试包含 AI 轮次、编辑者授权、第二人工账号权限/撤权、超过 250 条提交、限流重试、初始化/发布失败、批量预登记和恢复后迟到写入模拟,无需真实账号或 Token。接入时另验收 caller 与恢复入口的 run-name、取消/超时和初始化失败路由。真实 Bot 接入仍须现场验证;不能把模拟当成实际授权已生效。 +运行 `python -m unittest discover -s scripts/tests -v`。测试包含 AI 轮次、编辑者授权、第二人工账号权限/撤权、超过 250 条提交、限流重试、初始化/发布失败、20 次检查复用同一 ID、旧运行接管拦截和全仓/恢复路由,无需真实账号或 Token。接入时另验收 caller 与恢复入口的 run-name、取消/超时和初始化失败路由。真实 Bot 接入仍须现场验证;不能把模拟当成实际授权已生效。 自动关 Issue 的 [触发工作流](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306714886) 和 [后续复查](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306733764) 已在隔离仓库实测。一次性实验、规则配置和历史结果保留在[测试仓库](https://github.com/liaoxiang0304/VR_DexCopilot),不作为生产接入文件。 diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 93b9b2b..6fe3f5f 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -7,7 +7,6 @@ import re import sys import time -from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import UTC, datetime from email.utils import parsedate_to_datetime from functools import cache @@ -402,65 +401,63 @@ def summary(number, head, result): def current_check(api, repository, number, head, check): - """Only one fixed-name gate remains; late writes cannot rename it back.""" - path = f"/repos/{repository}/commits/{head}/check-runs" - runs = api.pages( - f"{path}?check_name={quote(CHECK_NAME, safe='')}&filter=all", "check_runs" - ) - prefix = f"ai-review-disposition:{number}:" - runs = [ - run - for run in runs - if run["app"]["id"] == check["app"]["id"] - and (not run.get("external_id") or run["external_id"].startswith(prefix)) - ] - runs = {run["id"]: run for run in [*runs, check]}.values() - - def order(run): - key = re.fullmatch( - re.escape(prefix) + r"([0-9]+):([0-9]+)", run.get("external_id") or "" - ) - return (int(key[1]), int(key[2]), run["id"]) if key and int(key[1]) else None - - managed = [run for run in runs if order(run)] - newest = max(managed, key=order) if managed else check - # An explicit local CLI check is ordered by registration, not an Actions sequence. - newest = max( - [newest, *(run for run in runs if not order(run))], key=lambda run: run["id"] + """Verify ownership; the shared per-PR Actions queue serializes all writers.""" + live = api.request("GET", f"/repos/{repository}/check-runs/{check['id']}") + return ( + live["name"] == CHECK_NAME + and live["head_sha"] == head + and live.get("external_id") == check["external_id"] + and live["app"]["id"] == check["app"]["id"] ) - for run in runs: - if run["id"] != newest["id"]: - api.request( - "PATCH", - f"/repos/{repository}/check-runs/{run['id']}", - { - "name": f"{CHECK_NAME} (superseded #{run['id']})", - "status": "completed", - "conclusion": "cancelled", - }, - ) - return newest["id"] == check["id"] def generation(): return ( - int(os.environ.get("GITHUB_RUN_NUMBER", "0")), + # Run IDs are comparable across caller and recovery workflows; run numbers are not. + int(os.environ.get("GITHUB_RUN_ID", os.environ.get("GITHUB_RUN_NUMBER", "0"))), int(os.environ.get("GITHUB_RUN_ATTEMPT", "1")), ) def register_check(api, repository, number, head, sequence=None): + """Get or reopen one managed Check. Call only inside the per-PR writer queue.""" run, attempt = sequence if sequence is not None else generation() - check = api.request( - "POST", - f"/repos/{repository}/check-runs", - { - "name": CHECK_NAME, - "head_sha": head, - "status": "in_progress", - "external_id": f"ai-review-disposition:{number}:{run}:{attempt}", - }, + prefix = f"ai-review-disposition:{number}:" + runs = api.pages( + f"/repos/{repository}/commits/{head}/check-runs" + f"?check_name={quote(CHECK_NAME, safe='')}&filter=all", + "check_runs", ) + runs = [ + check + for check in runs + if check["app"].get("slug") == "github-actions" + and (not check.get("external_id") or check["external_id"].startswith(prefix)) + ] + + def order(check): + match = re.fullmatch( + re.escape(prefix) + r"([0-9]+):([0-9]+)", check.get("external_id") or "" + ) + return (int(match[1]), int(match[2]), check["id"]) if match else (0, 0, check["id"]) + + previous = max(runs, key=order) if runs else None + if previous and run and order(previous)[:2] > (run, attempt): + return None + body = { + "name": CHECK_NAME, + "status": "in_progress", + "external_id": f"{prefix}{run}:{attempt}", + "output": {"title": "Checking", "summary": f"Evaluating PR #{number} at {head}."}, + } + if previous: + check = api.request( + "PATCH", f"/repos/{repository}/check-runs/{previous['id']}", body + ) + else: + check = api.request( + "POST", f"/repos/{repository}/check-runs", {"head_sha": head, **body} + ) journal = os.environ.get("AI_REVIEW_CHECKS_FILE") if journal: with JOURNAL_LOCK, open(journal, "a", encoding="utf-8") as stream: @@ -471,7 +468,7 @@ def register_check(api, repository, number, head, sequence=None): def finish_pending(api, repository, number, head, sequence): - """Fence a failed run with a new Check ID so a late success cannot resurrect it.""" + """Close this job's unfinished Check before releasing its per-PR writer queue.""" external_id = f"ai-review-disposition:{number}:{sequence[0]}:{sequence[1]}" runs = api.pages( f"/repos/{repository}/commits/{head}/check-runs" @@ -484,9 +481,11 @@ def finish_pending(api, repository, number, head, sequence): if run.get("external_id") == external_id and run["app"].get("slug") == "github-actions" ] - if own and max(own, key=lambda run: run["id"])["status"] == "completed": + if not own: + return True + check = max(own, key=lambda run: run["id"]) + if check["status"] == "completed": return True - check = register_check(api, repository, number, head, sequence) if current_check(api, repository, number, head, check): api.request( "PATCH", @@ -503,24 +502,6 @@ def finish_pending(api, repository, number, head, sequence): return True -def run_parallel(targets, operation): - """Bound API concurrency and keep processing after any target fails.""" - ok = True - with ThreadPoolExecutor(max_workers=4) as pool: - futures = {pool.submit(operation, target): target for target in targets} - for future in as_completed(futures): - try: - ok = future.result() and ok - except Exception as error: - print( - f"Disposition target {futures[future]} failed ({type(error).__name__}); " - "check may remain in_progress; dispatch a new check.", - file=sys.stderr, - ) - ok = False - return ok - - def cleanup_file(api, repository, path): if not os.path.exists(path): return True @@ -531,11 +512,14 @@ def cleanup_file(api, repository, path): if line.strip() for item in [json.loads(line)] } - return run_parallel(targets, lambda target: finish_pending(api, repository, *target)) + ok = True + for target in sorted(targets): + ok = finish_pending(api, repository, *target) and ok + return ok -def recover_run(api, repository, run_id): - """Default-branch recovery also covers failures before Check registration.""" +def recovery_targets(api, repository, run_id): + """Route recovery to the same per-PR workers; this function never writes Checks.""" run = api.request("GET", f"/repos/{repository}/actions/runs/{run_id}") if run["path"] != ".github/workflows/ai-review-disposition.yml": raise ValueError("Recovery requires the documented caller workflow") @@ -546,7 +530,7 @@ def recover_run(api, repository, run_id): "action_required", "startup_failure", }: - return True + return [] title = run["display_title"] if title == "all-open-prs": prs = api.pages(f"/repos/{repository}/pulls?state=open") @@ -554,22 +538,41 @@ def recover_run(api, repository, run_id): prs = [api.request("GET", f"/repos/{repository}/pulls/{title}")] else: raise ValueError("Recovery requires a PR number or all-open-prs run-name") - sequence = (run["run_number"], run["run_attempt"]) - targets = [ - (pr["number"], pr["head"]["sha"], sequence) for pr in prs if pr["state"] == "open" - ] - return run_parallel(targets, lambda target: finish_pending(api, repository, *target)) + return prs -def check_pr(api, repository, number, bots, registered=None): - if registered is None: +def prepare_targets(api, repository, number=None, all_open=False, recover=None): + """Enumerate trusted metadata for an Actions matrix, without publishing Checks.""" + if recover: + prs = recovery_targets(api, repository, recover) + elif all_open: + prs = api.pages(f"/repos/{repository}/pulls?state=open") + else: + prs = [api.request("GET", f"/repos/{repository}/pulls/{number}")] + targets = { + pr["number"]: {"number": pr["number"], "head": pr["head"]["sha"]} + for pr in prs + if pr["state"] == "open" + } + if len(targets) > 256: + raise ValueError("Actions matrix supports at most 256 open PRs per sweep") + return [targets[number] for number in sorted(targets)] + + +def check_pr(api, repository, number, bots, head=None): + try: pr = api.request("GET", f"/repos/{repository}/pulls/{number}") if pr["state"] != "open": return True head = pr["head"]["sha"] - check = register_check(api, repository, number, head) - else: - head, check = registered + except Exception: + # A trusted routing snapshot lets registration revoke old success even if + # this metadata read fails. The evaluation must still obtain live PR data. + if head is None: + raise + check = register_check(api, repository, number, head) + if check is None: + return True @cache def authorized(login, author): @@ -673,13 +676,22 @@ def main(): "--cleanup-file", help="Finish interrupted Checks from a trusted local journal" ) target.add_argument( - "--recover-run", type=int, help="Recover an interrupted caller run" + "--recover-run", type=int, help="Route an interrupted caller run to PR workers" + ) + parser.add_argument( + "--prepare-targets", + action="store_true", + help="Output the worker matrix; never write Checks", + ) + parser.add_argument( + "--head-sha", + help="Trusted head from the routing job; register before reading PR data", ) parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) args = parser.parse_args() bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") - evaluating = not (args.cleanup_file or args.recover_run) + evaluating = not (args.cleanup_file or args.prepare_targets) if ( ( evaluating @@ -692,6 +704,12 @@ def main(): or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository) or (args.pr_number is not None and args.pr_number <= 0) or (args.recover_run is not None and args.recover_run <= 0) + or ((args.recover_run or args.all_open_prs) and not args.prepare_targets) + or (args.prepare_targets and args.cleanup_file) + or ( + args.head_sha is not None + and (not args.pr_number or not re.fullmatch(r"[0-9a-f]{40}", args.head_sha)) + ) or not token ): parser.error( @@ -700,33 +718,20 @@ def main(): api = GitHub(token) if args.cleanup_file: return 0 if cleanup_file(api, args.repository, args.cleanup_file) else 1 - if args.recover_run: - return 0 if recover_run(api, args.repository, args.recover_run) else 1 - if args.all_open_prs: - prs = { - pr["number"]: pr for pr in api.pages(f"/repos/{args.repository}/pulls?state=open") - } - registered = {} - ok = True - # Block every target before any expensive review/Issue/permission reads. - for number, pr in sorted(prs.items()): - try: - head = pr["head"]["sha"] - check = register_check(api, args.repository, number, head) - if current_check(api, args.repository, number, head, check): - registered[number] = (head, check) - except Exception as error: - print( - f"PR #{number}: check failed ({type(error).__name__}); rerun required.", - file=sys.stderr, - ) - ok = False - evaluated = run_parallel( - registered, - lambda number: check_pr(api, args.repository, number, bots, registered[number]), + if args.prepare_targets: + targets = prepare_targets( + api, args.repository, args.pr_number, args.all_open_prs, args.recover_run ) - return 0 if evaluated and ok else 1 - ok = check_pr(api, args.repository, args.pr_number, bots) + matrix = json.dumps({"include": targets}, separators=(",", ":")) + print(matrix) + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.write(f"matrix={matrix}\nhas-targets={'true' if targets else 'false'}\n") + return 0 + if args.head_sha: + ok = check_pr(api, args.repository, args.pr_number, bots, args.head_sha) + else: + ok = check_pr(api, args.repository, args.pr_number, bots) return 0 if ok else 1 diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 8a7a944..d182f7b 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -12,6 +12,8 @@ GitHub, check_pr, current_check, + register_check, + prepare_targets, evaluate, main, parse_disposition, @@ -729,6 +731,7 @@ def graphql(query, variables, states=states): api, "request", side_effect=[pr, {"id": 99}, pr, pr, pr, pr, {}] ) as request, patch.object(api, "graphql", side_effect=graphql), + patch.object(api, "pages", return_value=[]), patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), patch("builtins.print"), ): @@ -1026,6 +1029,7 @@ def respond(method, path, body=None): with ( patch.object(api, "request", side_effect=respond) as request, + patch.object(api, "pages", return_value=[]), patch("scripts.check_ai_review_disposition.current_check", return_value=True), patch("scripts.check_ai_review_disposition.snapshot", side_effect=snapshots), patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), @@ -1048,7 +1052,7 @@ def add(self, run, attempt=1, app=1, number=128): "name": CHECK_NAME, "head_sha": HEAD, "status": "in_progress", - "app": {"id": app}, + "app": {"id": app, "slug": "github-actions" if app == 1 else "other"}, "external_id": f"ai-review-disposition:{number}:{run}:{attempt}", } self.checks[check["id"]] = check @@ -1061,14 +1065,22 @@ def request(self, method, path, body=None): check = self.add(0) self.checks[check["id"]].update(copy.deepcopy(body)) return copy.deepcopy(self.checks[check["id"]]) + if method == "GET" and "/check-runs/" in path: + return copy.deepcopy(self.checks[int(path.rsplit("/", 1)[1])]) if method == "GET": query = parse_qs(urlsplit(path).query) - runs = [c for c in self.checks.values() if c["name"] == query["check_name"][0]] + runs = [ + c + for c in self.checks.values() + if c["name"] == query["check_name"][0] and c["head_sha"] in path + ] start = (int(query["page"][0]) - 1) * 100 return {"check_runs": copy.deepcopy(runs[start : start + 100])} if method == "PATCH": check = self.checks[int(path.rsplit("/", 1)[1])] check.update(copy.deepcopy(body)) + if body.get("status") == "in_progress": + check["conclusion"] = None return copy.deepcopy(check) raise AssertionError(f"Unexpected API call: {method} {path}") @@ -1077,115 +1089,104 @@ def gate(self): class LatestCheckTests(unittest.TestCase): - def claim(self, api, check): - return current_check(api, "org/repo", 128, HEAD, check) - - def test_late_old_result_cannot_override_new_failure_or_success(self): - for new_passes in (False, True): - with self.subTest(new_passes=new_passes): - api = CheckStore() - ready = fixture("Disposition: Invalid\nReason: Test") - missing = fixture() - old_data, new_data = (missing, ready) if new_passes else (ready, missing) - started = False - - def old_snapshot( - *args, api=api, new_data=new_data, new_passes=new_passes, old_data=old_data - ): - nonlocal started - if not started: - started = True - with ( - patch.dict("os.environ", {"GITHUB_RUN_NUMBER": "2"}), - patch( - "scripts.check_ai_review_disposition.snapshot", return_value=new_data - ), - ): - self.assertEqual(check_pr(api, "org/repo", 128, {BOT}), new_passes) - return old_data - + def test_twenty_serial_evaluations_reuse_one_check_and_publish_latest_result(self): + api = CheckStore() + ready = fixture("Disposition: Invalid\nReason: Test") + with patch("builtins.print"), patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}): + for run in range(1, 21): + ok = run % 2 == 0 with ( patch.dict( - "os.environ", - { - "GITHUB_RUN_NUMBER": "1", - "GITHUB_RUN_ATTEMPT": "1", - "GITHUB_STEP_SUMMARY": "", - }, + "os.environ", {"GITHUB_RUN_ID": str(run), "GITHUB_RUN_ATTEMPT": "1"} ), patch( - "scripts.check_ai_review_disposition.snapshot", side_effect=old_snapshot + "scripts.check_ai_review_disposition.snapshot", + return_value=ready if ok else fixture(), ), - patch("builtins.print"), ): - self.assertTrue(check_pr(api, "org/repo", 128, {BOT})) - # Even an already-sent result that arrives late never restores the gate name. - api.request( - "PATCH", - "/repos/org/repo/check-runs/1", - {"status": "completed", "conclusion": "success"}, - ) - self.assertEqual(len(api.gate()), 1) - self.assertEqual(api.gate()[0]["id"], 2) - self.assertEqual( - api.gate()[0]["conclusion"], "success" if new_passes else "failure" - ) + self.assertEqual(check_pr(api, "org/repo", 128, {BOT}), ok) + self.assertEqual(len(api.checks), 1) + self.assertEqual(api.checks[1]["conclusion"], "success" if ok else "failure") + self.assertEqual(api.checks[1]["external_id"], "ai-review-disposition:128:20:1") - def test_new_pending_or_cancelled_run_never_falls_back_to_old_success(self): + def test_reopening_a_success_blocks_without_creating_history(self): api = CheckStore() - old = api.add(1) - api.checks[old["id"]].update(status="completed", conclusion="success") - new = api.add(2) - self.assertTrue(self.claim(api, new)) - self.assertEqual(api.gate()[0]["status"], "in_progress") - api.checks[new["id"]].update(status="completed", conclusion="cancelled") - self.assertFalse(self.claim(api, old)) - self.assertEqual(api.gate()[0]["conclusion"], "cancelled") - - def test_a_delayed_older_registration_does_not_take_over(self): + check = register_check(api, "org/repo", 128, HEAD, (1, 1)) + api.checks[check["id"]].update(status="completed", conclusion="success") + newer = register_check(api, "org/repo", 128, HEAD, (2, 1)) + self.assertEqual(check["id"], newer["id"]) + self.assertEqual(newer["status"], "in_progress") + self.assertIsNone(newer["conclusion"]) + self.assertFalse(current_check(api, "org/repo", 128, HEAD, check)) + self.assertTrue(current_check(api, "org/repo", 128, HEAD, newer)) + + def test_delayed_old_registration_and_rerun_cannot_take_over(self): api = CheckStore() - new = api.add(2) - old = api.add(1) - self.assertFalse(self.claim(api, old)) - self.assertEqual([c["id"] for c in api.gate()], [new["id"]]) - - def test_rerun_of_latest_generation_replaces_its_previous_attempt(self): + check = register_check(api, "org/repo", 128, HEAD, (20, 1)) + self.assertIsNone(register_check(api, "org/repo", 128, HEAD, (19, 99))) + newer = register_check(api, "org/repo", 128, HEAD, (20, 2)) + self.assertEqual(newer["id"], check["id"]) + self.assertFalse(current_check(api, "org/repo", 128, HEAD, check)) + self.assertIsNone(register_check(api, "org/repo", 128, HEAD, (20, 1))) + self.assertEqual(len(api.checks), 1) + + def test_recovery_workflow_uses_global_run_id_instead_of_local_run_number(self): api = CheckStore() - old = api.add(2) - new = api.add(2, attempt=2) - self.assertTrue(self.claim(api, new)) - self.assertFalse(self.claim(api, old)) + register_check(api, "org/repo", 128, HEAD, (100, 1)) + with patch.dict( + "os.environ", + {"GITHUB_RUN_ID": "101", "GITHUB_RUN_NUMBER": "1", "GITHUB_RUN_ATTEMPT": "1"}, + ): + newer = register_check(api, "org/repo", 128, HEAD) + self.assertEqual(newer["external_id"], "ai-review-disposition:128:101:1") + self.assertEqual(len(api.checks), 1) - def test_check_history_is_paginated_and_other_apps_or_prs_are_untouched(self): + def test_existing_history_other_apps_prs_and_ci_are_untouched(self): api = CheckStore() for run in range(1, 102): newest = api.add(run) - other_app = api.add(999, app=2) - other_pr = api.add(999, number=129) - self.assertTrue(self.claim(api, newest)) - self.assertEqual(api.checks[1]["conclusion"], "cancelled") - self.assertEqual(api.checks[newest["id"]]["name"], CHECK_NAME) - for check in (other_app, other_pr): - self.assertEqual(api.checks[check["id"]], check) - - def test_manual_cli_check_does_not_permanently_fence_out_future_actions(self): + api.add(999, app=2) + api.add(999, number=129) + ci = api.add(999) + api.checks[ci["id"]]["name"] = "Unrelated CI" + old = api.add(0) + api.checks[old["id"]]["name"] += " (superseded #104)" + before = copy.deepcopy(api.checks) + check = register_check(api, "org/repo", 128, HEAD, (102, 1)) + self.assertEqual(check["id"], newest["id"]) + self.assertEqual(len(api.checks), len(before)) + for key in before: + if key != newest["id"]: + self.assertEqual(api.checks[key], before[key]) + + def test_new_head_gets_its_own_check(self): api = CheckStore() - api.add(1) - manual = api.add(0) - self.assertTrue(self.claim(api, manual)) - future = api.add(2) - self.assertTrue(self.claim(api, future)) - self.assertFalse(self.claim(api, manual)) - - def test_legacy_check_without_external_id_is_replaced(self): - for external_id in (None, ""): - with self.subTest(external_id=external_id): - api = CheckStore() - old = api.add(0) - api.checks[old["id"]]["external_id"] = external_id - new = api.add(1) - self.assertTrue(self.claim(api, new)) - self.assertEqual([c["id"] for c in api.gate()], [new["id"]]) + first = register_check(api, "org/repo", 128, HEAD, (1, 1)) + other_head = "c" * 40 + second = register_check(api, "org/repo", 128, other_head, (2, 1)) + self.assertNotEqual(first["id"], second["id"]) + self.assertEqual(len(api.checks), 2) + self.assertEqual( + register_check(api, "org/repo", 128, other_head, (3, 1))["id"], second["id"] + ) + + def test_legacy_check_without_external_id_is_reused(self): + api = CheckStore() + old = api.add(0) + api.checks[old["id"]]["external_id"] = "" + self.assertEqual( + register_check(api, "org/repo", 128, HEAD, (1, 1))["id"], old["id"] + ) + self.assertEqual(len(api.checks), 1) + + def test_queued_worker_uses_live_head_instead_of_router_snapshot(self): + api = CheckStore() + with ( + patch("scripts.check_ai_review_disposition.snapshot", return_value=fixture()), + patch("builtins.print"), + ): + self.assertFalse(check_pr(api, "org/repo", 128, {BOT}, "c" * 40)) + self.assertEqual(api.gate()[0]["head_sha"], HEAD) class MainTests(unittest.TestCase): @@ -1213,27 +1214,23 @@ def run_main(self, *arguments, passed=True, numbers=None, results=None): check.side_effect = results return main(), client, check - def test_explicit_sweep_checks_all_open_prs_even_after_failure(self): - code, client, check = self.run_main( - "--all-open-prs", passed=False, numbers=[24, 7, 24] - ) - self.assertEqual(code, 1) - self.assertEqual(sorted(c.args[2] for c in check.call_args_list), [7, 24]) - client.return_value.pages.assert_called_once_with( - "/repos/org/repo/pulls?state=open" - ) + def test_sweep_only_routes_all_targets_without_writing_checks(self): + api = CheckStore() + prs = [{"number": n, "state": "open", "head": {"sha": HEAD}} for n in [24, 7, 24]] + with patch.object(api, "pages", return_value=prs): + self.assertEqual( + prepare_targets(api, "org/repo", all_open=True), + [{"number": n, "head": HEAD} for n in [7, 24]], + ) + self.assertEqual(api.checks, {}) - def test_sweep_continues_after_a_pr_api_error(self): - code, _, check = self.run_main( - "--all-open-prs", numbers=[1, 2, 3], results=[RuntimeError("failed"), True, True] - ) - self.assertEqual(code, 1) - self.assertEqual(sorted(c.args[2] for c in check.call_args_list), [1, 2, 3]) + def test_empty_sweep_routes_no_workers(self): + with patch.object(GitHub, "pages", return_value=[]): + self.assertEqual(prepare_targets(GitHub("token"), "org/repo", all_open=True), []) - def test_empty_open_pr_sweep_does_not_publish_checks(self): - code, _, check = self.run_main("--all-open-prs", numbers=[]) - self.assertEqual(code, 0) - check.assert_not_called() + def test_direct_sweep_is_rejected_to_prevent_bypassing_worker_queue(self): + with self.assertRaises(SystemExit): + self.run_main("--all-open-prs") def test_open_pr_enumeration_reads_all_pages_without_issue_backlinks(self): api = GitHub("test-token") diff --git a/scripts/tests/test_ai_review_reliability.py b/scripts/tests/test_ai_review_reliability.py index 9a68164..96b9d1b 100644 --- a/scripts/tests/test_ai_review_reliability.py +++ b/scripts/tests/test_ai_review_reliability.py @@ -261,65 +261,60 @@ def setUp(self): self.environment.start() self.addCleanup(self.environment.stop) - def test_first_metadata_read_failure_is_fenced_by_default_branch_recovery(self): + def test_first_metadata_read_failure_revokes_old_success_using_trusted_head(self): api = RecoveryStore() old = api.add(1) api.checks[old["id"]].update(status="completed", conclusion="success") + request = api.request + + def fail_metadata(method, path, body=None): + if "/pulls/" in path: + raise RuntimeError("read failed") + return request(method, path, body) + with ( - patch.object(api, "request", side_effect=RuntimeError("read failed")), - self.assertRaises(RuntimeError), + patch.object(api, "request", side_effect=fail_metadata), + patch.object(checker, "snapshot", side_effect=RuntimeError("read failed")), + patch.dict(os.environ, {"GITHUB_RUN_ID": "2", "GITHUB_RUN_ATTEMPT": "1"}), + patch("builtins.print"), ): - checker.check_pr(api, "org/repo", 128, {fixtures.BOT}) - self.assertTrue(checker.recover_run(api, "org/repo", 999)) - self.assertEqual(len(api.gate()), 1) + self.assertFalse( + checker.check_pr(api, "org/repo", 128, {fixtures.BOT}, fixtures.HEAD) + ) + self.assertEqual(len(api.checks), 1) self.assertEqual(api.gate()[0]["conclusion"], "failure") - self.assertEqual(api.gate()[0]["external_id"], "ai-review-disposition:128:2:1") - def test_timeout_fences_late_success_with_a_different_check_id(self): + def test_cleanup_marks_same_check_failed_without_new_history(self): api = RecoveryStore() old = api.add(2) self.assertTrue(checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1))) - api.request( - "PATCH", - f"/repos/org/repo/check-runs/{old['id']}", - {"status": "completed", "conclusion": "success"}, - ) - self.assertNotEqual(api.gate()[0]["id"], old["id"]) + self.assertEqual(len(api.checks), 1) + self.assertEqual(api.gate()[0]["id"], old["id"]) self.assertEqual(api.gate()[0]["conclusion"], "failure") + before = copy.deepcopy(api.checks) + checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) + self.assertEqual(api.checks, before) - def test_old_recovery_cannot_replace_newer_success_or_pending(self): + def test_old_cleanup_cannot_replace_newer_success_or_pending(self): for status in ("completed", "in_progress"): - with self.subTest(status=status): - api = RecoveryStore() - newest = api.add(3) - api.checks[newest["id"]].update( - status=status, conclusion="success" if status == "completed" else None - ) - checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) - self.assertEqual([c["id"] for c in api.gate()], [newest["id"]]) - self.assertEqual(api.gate()[0]["status"], status) + api = RecoveryStore() + newest = api.add(3) + api.checks[newest["id"]].update( + status=status, conclusion="success" if status == "completed" else None + ) + before = copy.deepcopy(api.checks) + checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) + self.assertEqual(api.checks, before) - def test_completed_target_is_preserved_and_recovery_is_idempotent(self): + def test_recovery_routes_to_workers_without_writing_checks(self): api = RecoveryStore() - own = api.add(2) - api.checks[own["id"]].update(status="completed", conclusion="success") + api.add(1) before = copy.deepcopy(api.checks) - checker.recover_run(api, "org/repo", 999) + self.assertEqual( + checker.prepare_targets(api, "org/repo", recover=999), + [{"number": 128, "head": fixtures.HEAD}], + ) self.assertEqual(api.checks, before) - api.checks[own["id"]]["status"] = "in_progress" - checker.recover_run(api, "org/repo", 999) - count = len(api.checks) - checker.recover_run(api, "org/repo", 999) - self.assertEqual(len(api.checks), count) - - def test_recovery_uses_source_attempt_not_its_own_workflow_generation(self): - api = RecoveryStore() - api.source["run_attempt"] = 2 - with patch.dict( - os.environ, {"GITHUB_RUN_NUMBER": "999", "GITHUB_RUN_ATTEMPT": "7"} - ): - checker.recover_run(api, "org/repo", 999) - self.assertEqual(api.gate()[0]["external_id"], "ai-review-disposition:128:2:2") def test_recovery_rejects_unrelated_workflows_and_invalid_routing(self): for field, value in ( @@ -329,51 +324,54 @@ def test_recovery_rejects_unrelated_workflows_and_invalid_routing(self): api = RecoveryStore() api.source[field] = value with self.subTest(field=field), self.assertRaises(ValueError): - checker.recover_run(api, "org/repo", 999) + checker.recovery_targets(api, "org/repo", 999) self.assertEqual(api.checks, {}) - def test_running_rerun_or_success_is_not_marked_failed(self): + def test_running_rerun_or_success_routes_no_recovery(self): for changes in ({"status": "in_progress"}, {"conclusion": "success"}): api = RecoveryStore() api.source.update(changes) - self.assertTrue(checker.recover_run(api, "org/repo", 999)) + self.assertEqual(checker.recovery_targets(api, "org/repo", 999), []) self.assertEqual(api.checks, {}) - def test_recovery_is_not_blocked_by_invalid_bot_configuration(self): + def test_routing_does_not_need_bot_configuration(self): with ( patch.dict( - os.environ, {"GH_TOKEN": "test-token", "AI_REVIEW_BOTS": "invalid+bot"} + os.environ, + { + "GH_TOKEN": "test-token", + "AI_REVIEW_BOTS": "invalid+bot", + "GITHUB_OUTPUT": "", + }, ), patch.object( - sys, "argv", ["checker", "--repository", "org/repo", "--recover-run", "999"] + sys, + "argv", + [ + "checker", + "--repository", + "org/repo", + "--prepare-targets", + "--recover-run", + "999", + ], ), - patch.object(checker, "recover_run", return_value=True) as recover, + patch.object(checker, "prepare_targets", return_value=[]) as route, + patch("builtins.print"), ): self.assertEqual(checker.main(), 0) - self.assertEqual(recover.call_args.args[1:], ("org/repo", 999)) + self.assertEqual(route.call_args.args[1:], ("org/repo", None, False, 999)) - def test_sweep_recovery_visits_all_targets_and_preserves_completed_results(self): + def test_sweep_recovery_routes_all_open_targets(self): api = RecoveryStore() api.source["display_title"] = "all-open-prs" prs = [ {"number": n, "head": {"sha": fixtures.HEAD}, "state": "open"} for n in range(1, 5) ] - visited = [] - - def finish(client, repository, number, head, sequence): - visited.append(number) - if number == 1: - raise RuntimeError("one target is unreadable") - return True - - with ( - patch.object(api, "pages", return_value=prs), - patch.object(checker, "finish_pending", side_effect=finish), - patch("sys.stderr", new_callable=io.StringIO), - ): - self.assertFalse(checker.recover_run(api, "org/repo", 999)) - self.assertEqual(sorted(visited), [1, 2, 3, 4]) + with patch.object(api, "pages", return_value=prs): + self.assertEqual(len(checker.prepare_targets(api, "org/repo", recover=999)), 4) + self.assertEqual(api.checks, {}) def test_local_journal_cleanup_closes_interrupted_checks(self): api = RecoveryStore() @@ -418,45 +416,52 @@ def fail_publish(method, path, body=None, request=request): self.assertIn("dispatch", stderr.getvalue()) self.assertEqual(api.gate()[0]["status"], "in_progress") - def test_sweep_registers_every_pr_before_evaluation(self): - prs = [{"number": n, "head": {"sha": fixtures.HEAD}} for n in range(1, 9)] - registered = [] - evaluated = [] - - def register(api, repository, number, head): - registered.append(number) - return {"id": number} - - def evaluate(api, repository, number, bots, prepared): - self.assertEqual(len(registered), 8) - self.assertEqual(prepared, (fixtures.HEAD, {"id": number})) - evaluated.append(number) - if number == 2: - raise RuntimeError("one PR fails") - return True - - with ( - patch.dict(os.environ, {"GH_TOKEN": "test-token"}), - patch.object( - sys, - "argv", - [ - "checker", - "--repository", - "org/repo", - "--bots", - fixtures.BOT, - "--all-open-prs", - ], - ), - patch.object(checker.GitHub, "pages", return_value=prs), - patch.object(checker, "register_check", side_effect=register), - patch.object(checker, "current_check", return_value=True), - patch.object(checker, "check_pr", side_effect=evaluate), - patch("sys.stderr", new_callable=io.StringIO), - ): - self.assertEqual(checker.main(), 1) - self.assertEqual(sorted(evaluated), list(range(1, 9))) + def test_routing_outputs_matrix_for_worker_queue_without_check_writes(self): + api = RecoveryStore() + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "outputs" + with ( + patch.dict( + os.environ, {"GH_TOKEN": "test-token", "GITHUB_OUTPUT": str(output)} + ), + patch.object( + sys, + "argv", + [ + "checker", + "--repository", + "org/repo", + "--prepare-targets", + "--pr-number", + "128", + ], + ), + patch.object(checker, "GitHub", return_value=api), + patch("builtins.print"), + ): + self.assertEqual(checker.main(), 0) + self.assertIn('"include":[{"number":128,"head":', output.read_text()) + self.assertIn("has-targets=true", output.read_text()) + self.assertEqual(api.checks, {}) + + def test_shared_workflow_uses_one_worker_queue_for_all_entry_points(self): + workflow = ( + Path(__file__).resolve().parents[2] + / ".github/workflows/reusable-ai-review-disposition.yml" + ).read_text() + self.assertIn( + "group: ai-review-disposition-${{ github.repository }}-${{ matrix.number }}", + workflow, + ) + self.assertIn("cancel-in-progress: false", workflow) + self.assertIn("fail-fast: false", workflow) + self.assertIn("max-parallel: 4", workflow) + self.assertIn("--prepare-targets --all-open-prs", workflow) + self.assertIn("--prepare-targets --recover-run", workflow) + self.assertNotIn( + '--recover-run "$RECOVER_RUN_ID"\n elif', + workflow.split(" disposition:")[1], + ) if __name__ == "__main__": From 0d6ca9cebfae75380c9588ba6decfc0b9fdcafa3 Mon Sep 17 00:00:00 2001 From: xiaoyu <2455995107@qq.com> Date: Wed, 28 Oct 2026 16:48:50 +0800 Subject: [PATCH 18/21] fix[ci]: revoke old success while reusing a Check Problem: - GitHub retains a completed Check's conclusion when only its status changes. - A reused Check can otherwise remain successful while evaluation is running. Solution: - Publish a temporary failure with a Checking title before re-evaluation. - Reuse the same ID for interruption cleanup and refresh completion timestamps. - Document the live REST and GraphQL reset limitations. Test: - Python 3.11: 126 unit tests passed; Ruff lint/format and diff checks passed. - Real sandbox probes confirmed status-only and null resets do not revoke success. JIRA: PDIST-770 --- docs/AI_REVIEW_DISPOSITION.md | 6 ++-- scripts/check_ai_review_disposition.py | 16 +++++++-- scripts/tests/test_ai_review_disposition.py | 11 +++--- scripts/tests/test_ai_review_reliability.py | 37 +++++++++++++++++++++ 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index a6135e4..6719c7c 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -58,15 +58,15 @@ DEFAULT_BRANCH 为仓库默认分支,负责 dispatch 的 job 需要 `actions: 手动检查填写正整数 pr-number;全仓复查勾选 all-open-prs、保持编号 0。默认不会隐式全仓扫描。CI 始终实时读取 PR 并将 Check 写入最新 head;通过前再次读取数据,清缓存复核权限和 Issue 状态。只读 REST/GraphQL 请求遇瞬时网络错误、429、500/502/503/504 或带 Retry-After 的 403 时最多尝试 3 次;遵守 Retry-After,等待超过 60 秒则中止并报告失败,不提前重试。创建/修改 Check 不盲重试。数据变化或读取失败不发布成功,Issue 的 404/410 会给出具体 Tracking 提示。 -同一 PR 的全部 worker 共用一个 concurrency group,cancel-in-progress=false;正在运行的 worker 保持执行,等待中的重复触发由最新任务合并替代。不同 PR 可并行。worker 开始后重新读取当前 head;同一仓库、PR、head 和 GitHub Actions App 复用同一 Check ID,重新设为 in_progress,再更新结果。新 head 单独创建 Check;不会再创建或改名出 superseded 项,既有历史记录不整理。重跑旧 run ID/attempt 不能接管更新运行。 +同一 PR 的全部 worker 共用一个 concurrency group,cancel-in-progress=false;正在运行的 worker 保持执行,等待中的重复触发由最新任务合并替代。不同 PR 可并行。worker 开始后重新读取当前 head;同一仓库、PR、head 和 GitHub Actions App 复用同一 Check ID,再更新结果。GitHub 对已完成 Check 的 status-only PATCH 会保留旧 conclusion,REST 不接受 null conclusion/completed_at,GraphQL 显式 null 也未重置;因此复查开始时原地发布临时 failure,标题 Checking,确保旧 success 立即失效,结束后再发布真实结论。首次创建仍使用 in_progress;Actions worker 显示执行进度。每次最终发布刷新 completed_at。新 head 单独创建 Check;不会再创建或改名出 superseded 项,既有历史记录不整理。重跑旧 run ID/attempt 不能接管更新运行。 此方案无需外部服务。GitHub 自动产生的路由、评估及事件收集 job Check 仍可能出现在 PR 页面;唯一业务门禁是 AI Review / Disposition Check,不能据此承诺整页仅一项。实验工作流发布的 Integration Test 也不属于正式检查器管理范围。 -普通退出由 always 收尾在释放同一个 PR 并发槽前读取本机登记日志,仅将仍由自己持有的未完成 Check 原地标记 failure。硬超时、取消、检出/初始化失败由默认分支的 workflow_run 恢复入口定位目标,再进入同一个 worker 队列重新检查实时数据;恢复不直接写 Check,也不会创建替代 Check。恢复重新评估可能得到正常的 success 或业务 failure。仅读取可信脚本写出的本机日志或实时 API,不下载或执行来源工作流的 artifact。最终发布失败会记录 Check ID 和重新 dispatch 的提示。 +普通退出由 always 收尾在释放同一个 PR 并发槽前读取本机登记日志,仅将仍由自己持有的 in_progress 或临时 Checking 结果原地标记中断 failure。硬超时、取消、检出/初始化失败由默认分支的 workflow_run 恢复入口定位目标,再进入同一个 worker 队列重新检查实时数据;恢复不直接写 Check,也不会创建替代 Check。恢复重新评估可能得到正常的 success 或业务 failure。仅读取可信脚本写出的本机日志或实时 API,不下载或执行来源工作流的 artifact。最终发布失败会记录 Check ID 和重新 dispatch 的提示。 Checks API 的 ownership 校验与 PATCH 不是原子操作。并发槽约束正常运行的 Actions writer;人为硬取消时已经送出的 HTTP 写入仍有极短的竞态,复用单一 Check ID 无法提供旧方案不同 ID 的隔离保证。不要另行直接调用 Checks API 写这个门禁;发生中断或 API 异常后应等待恢复并检查最新结果。 -恢复是异步的:事件发生到新 Check 登记、或失败到恢复运行之间存在窗口。若首次读取、枚举或登记失败,旧 success 可能在恢复前仍可见;GitHub API 完全不可读写、恢复入口未安装或自身失败时,脚本无法保证立即撤销它。必须监控 caller/恢复运行失败并重新 dispatch;要求这个窗口内也绝不允许合并时,需额外的 GitHub 侧合并门禁,不能仅依赖本异步检查。登记后的遗留 in_progress 会继续阻断。 +恢复是异步的:事件发生到新 Check 登记、或失败到恢复运行之间存在窗口。若首次读取、枚举或登记失败,旧 success 可能在恢复前仍可见;GitHub API 完全不可读写、恢复入口未安装或自身失败时,脚本无法保证立即撤销它。必须监控 caller/恢复运行失败并重新 dispatch;要求这个窗口内也绝不允许合并时,需额外的 GitHub 侧合并门禁,不能仅依赖本异步检查。登记后的遗留 in_progress 或临时 Checking failure 会继续阻断。 ## 验证与边界 diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 6fe3f5f..1a57d6e 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -451,6 +451,13 @@ def order(check): "output": {"title": "Checking", "summary": f"Evaluating PR #{number} at {head}."}, } if previous: + # Completed Checks cannot reliably return to in_progress. Revoke old + # success explicitly while keeping the same ID and showing progress in output. + body.update( + status="completed", + conclusion="failure", + completed_at=datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), + ) check = api.request( "PATCH", f"/repos/{repository}/check-runs/{previous['id']}", body ) @@ -484,7 +491,10 @@ def finish_pending(api, repository, number, head, sequence): if not own: return True check = max(own, key=lambda run: run["id"]) - if check["status"] == "completed": + if ( + check["status"] == "completed" + and check.get("output", {}).get("title") != "Checking" + ): return True if current_check(api, repository, number, head, check): api.request( @@ -493,6 +503,7 @@ def finish_pending(api, repository, number, head, sequence): { "status": "completed", "conclusion": "failure", + "completed_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), "output": { "title": "Evaluation interrupted", "summary": "Evaluation interrupted; dispatch a new disposition check.", @@ -643,6 +654,7 @@ def tracking_valid(value): { "status": "completed", "conclusion": "success" if ok else "failure", + "completed_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), "output": {"title": "Passed" if ok else "Failed", "summary": report[:60000]}, }, ) @@ -685,7 +697,7 @@ def main(): ) parser.add_argument( "--head-sha", - help="Trusted head from the routing job; register before reading PR data", + help="Trusted head from routing; register even if the first live PR read fails", ) parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) args = parser.parse_args() diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index d182f7b..74bc09c 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -1079,8 +1079,9 @@ def request(self, method, path, body=None): if method == "PATCH": check = self.checks[int(path.rsplit("/", 1)[1])] check.update(copy.deepcopy(body)) - if body.get("status") == "in_progress": - check["conclusion"] = None + # GitHub retains a stored conclusion unless it is explicitly cleared. + if check.get("conclusion") is not None: + check["status"] = "completed" return copy.deepcopy(check) raise AssertionError(f"Unexpected API call: {method} {path}") @@ -1115,8 +1116,10 @@ def test_reopening_a_success_blocks_without_creating_history(self): api.checks[check["id"]].update(status="completed", conclusion="success") newer = register_check(api, "org/repo", 128, HEAD, (2, 1)) self.assertEqual(check["id"], newer["id"]) - self.assertEqual(newer["status"], "in_progress") - self.assertIsNone(newer["conclusion"]) + self.assertEqual(newer["status"], "completed") + self.assertEqual(newer["conclusion"], "failure") + self.assertEqual(newer["output"]["title"], "Checking") + self.assertRegex(newer["completed_at"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") self.assertFalse(current_check(api, "org/repo", 128, HEAD, check)) self.assertTrue(current_check(api, "org/repo", 128, HEAD, newer)) diff --git a/scripts/tests/test_ai_review_reliability.py b/scripts/tests/test_ai_review_reliability.py index 96b9d1b..7690800 100644 --- a/scripts/tests/test_ai_review_reliability.py +++ b/scripts/tests/test_ai_review_reliability.py @@ -295,6 +295,43 @@ def test_cleanup_marks_same_check_failed_without_new_history(self): checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) self.assertEqual(api.checks, before) + def test_cleanup_closes_temporary_failure_when_reusing_completed_check(self): + api = RecoveryStore() + old = api.add(1) + api.checks[old["id"]].update(status="completed", conclusion="success") + check = checker.register_check(api, "org/repo", 128, fixtures.HEAD, (2, 1)) + self.assertEqual(check["conclusion"], "failure") + self.assertEqual(check["output"]["title"], "Checking") + checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) + self.assertEqual(len(api.checks), 1) + self.assertEqual(api.gate()[0]["output"]["title"], "Evaluation interrupted") + + def test_reused_check_stays_blocked_when_final_publication_fails(self): + api = RecoveryStore() + old = api.add(1) + api.checks[old["id"]].update(status="completed", conclusion="success") + request = api.request + + def fail_success(method, path, body=None): + if method == "PATCH" and (body or {}).get("conclusion") == "success": + raise RuntimeError("write failed") + return request(method, path, body) + + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "2", "GITHUB_RUN_ATTEMPT": "1"}), + patch.object(api, "request", side_effect=fail_success), + patch.object( + checker, + "snapshot", + return_value=fixtures.fixture("Disposition: Invalid\nReason: Test"), + ), + patch("sys.stderr", new_callable=io.StringIO), + ): + self.assertFalse(checker.check_pr(api, "org/repo", 128, {fixtures.BOT})) + self.assertEqual(len(api.checks), 1) + self.assertEqual(api.gate()[0]["conclusion"], "failure") + self.assertEqual(api.gate()[0]["output"]["title"], "Checking") + def test_old_cleanup_cannot_replace_newer_success_or_pending(self): for status in ("completed", "in_progress"): api = RecoveryStore() From e25288f0fb578c02a9f2fae22192a8896440b11b Mon Sep 17 00:00:00 2001 From: xiaoyu <2455995107@qq.com> Date: Wed, 28 Oct 2026 19:51:27 +0800 Subject: [PATCH 19/21] fix[ci]: publish one AI disposition status Problem: - AI disposition exposed helper checks and could not reset completed results to pending. Solution: - Publish one fixed commit status through a serialized background worker. - Preserve review policies and revalidate live evidence before passing. - Replace PR event collectors with background triggers and five-minute scans. - Skip unchanged scans and block before exhausting the status update quota. - Document the caller migration required for a single visible PR check. Test: - 141 unit tests passed, including repeated pending/success/failure transitions. - Ruff lint/format, actionlint, and git diff --check passed. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 97 ++--- docs/AI_REVIEW_DISPOSITION.md | 73 +++- docs/examples/ai-review-close-issue.yml | 2 +- docs/examples/ai-review-disposition.yml | 39 +- docs/examples/ai-review-events.yml | 19 - docs/examples/ai-review-recovery.yml | 3 +- scripts/check_ai_review_disposition.py | 368 ++++++++++++------ scripts/tests/test_ai_review_disposition.py | 328 ++++++++-------- scripts/tests/test_ai_review_reliability.py | 107 +++-- scripts/tests/test_ai_review_status.py | 202 ++++++++++ 10 files changed, 772 insertions(+), 466 deletions(-) delete mode 100644 docs/examples/ai-review-events.yml create mode 100644 scripts/tests/test_ai_review_status.py diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index d64bf85..5c67aff 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -13,7 +13,7 @@ on: type: number default: 0 all-open-prs: - description: 'Explicitly recheck every open PR after an issue changes' + description: 'Explicitly recheck every open PR' required: false type: boolean default: false @@ -22,6 +22,11 @@ on: required: false type: number default: 0 + only-changed: + description: 'Poll live evidence without rewriting unchanged terminal results' + required: false + type: boolean + default: false shared-ref: description: 'Revision of the shared CI scripts; defaults to main' required: false @@ -33,62 +38,22 @@ permissions: contents: read pull-requests: read issues: read - checks: write + statuses: write jobs: - targets: - name: Route AI Review Dispositions - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - contents: read - actions: read - pull-requests: read - outputs: - matrix: ${{ steps.route.outputs.matrix }} - has-targets: ${{ steps.route.outputs.has-targets }} - steps: - - name: Checkout trusted shared scripts - uses: actions/checkout@v4 - with: - repository: IS-Model-Framework/.github - ref: ${{ inputs.shared-ref }} - path: .ci-shared - persist-credentials: false - sparse-checkout: scripts - - uses: actions/setup-python@v7 - with: - python-version: '3.11' - - name: Route to per-PR workers without writing Checks - id: route - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ inputs.pr-number }} - ALL_OPEN_PRS: ${{ inputs.all-open-prs }} - RECOVER_RUN_ID: ${{ inputs.recover-run-id }} - run: | - if [[ "$RECOVER_RUN_ID" != "0" ]]; then - python .ci-shared/scripts/check_ai_review_disposition.py --prepare-targets --recover-run "$RECOVER_RUN_ID" - elif [[ "$ALL_OPEN_PRS" == "true" ]]; then - python .ci-shared/scripts/check_ai_review_disposition.py --prepare-targets --all-open-prs - else - python .ci-shared/scripts/check_ai_review_disposition.py --prepare-targets --pr-number "$PR_NUMBER" - fi - disposition: - name: Evaluate AI Review Dispositions (${{ matrix.number }}) - needs: targets - if: ${{ needs.targets.outputs.has-targets == 'true' }} - strategy: - fail-fast: false - max-parallel: 4 - matrix: ${{ fromJSON(needs.targets.outputs.matrix) }} + name: AI Review Disposition Worker + # PR-associated events generate additional native job Checks. Only trusted + # default-branch background events are supported by the single-row caller. + if: >- + ${{ contains(fromJSON('["schedule","workflow_dispatch","workflow_run","issue_comment","issues"]'), github.event_name) + && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} runs-on: ubuntu-latest - timeout-minutes: 15 - # Single checks, sweeps and recovery all acquire the same per-PR writer slot. - # Keep the active writer; newer pending work coalesces duplicate events. + timeout-minutes: 30 + # All entry points share one writer queue. Scheduled sweeps revisit every PR + # when GitHub coalesces pending duplicate events. concurrency: - group: ai-review-disposition-${{ github.repository }}-${{ matrix.number }} + group: ai-review-disposition-${{ github.repository }} cancel-in-progress: false env: GH_TOKEN: ${{ github.token }} @@ -108,15 +73,29 @@ jobs: with: python-version: '3.11' - - name: Publish check on the target PR head commit + - name: Route, validate and publish the single disposition status env: - PR_NUMBER: ${{ matrix.number }} - HEAD_SHA: ${{ matrix.head }} - AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-checks.jsonl - run: python .ci-shared/scripts/check_ai_review_disposition.py --pr-number "$PR_NUMBER" --head-sha "$HEAD_SHA" + AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-statuses.jsonl + PR_NUMBER: ${{ inputs.pr-number }} + ALL_OPEN_PRS: ${{ inputs.all-open-prs }} + RECOVER_RUN_ID: ${{ inputs.recover-run-id }} + ONLY_CHANGED: ${{ inputs.only-changed }} + run: | + args=() + if [[ "$ONLY_CHANGED" == "true" ]]; then + args+=(--only-changed) + fi + if [[ "$RECOVER_RUN_ID" != "0" ]]; then + args+=(--recover-run "$RECOVER_RUN_ID") + elif [[ "$ALL_OPEN_PRS" == "true" ]]; then + args+=(--all-open-prs) + else + args+=(--pr-number "$PR_NUMBER") + fi + python .ci-shared/scripts/check_ai_review_disposition.py "${args[@]}" - - name: Close interrupted checks before releasing the writer slot + - name: Fail interrupted pending statuses before releasing the writer slot if: ${{ always() && hashFiles('.ci-shared/scripts/check_ai_review_disposition.py') != '' }} env: - AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-checks.jsonl + AI_REVIEW_CHECKS_FILE: ${{ runner.temp }}/ai-review-statuses.jsonl run: python3 .ci-shared/scripts/check_ai_review_disposition.py --cleanup-file "$AI_REVIEW_CHECKS_FILE" diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 6719c7c..9ea5986 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -32,46 +32,77 @@ Fix: <当前 PR 中的完整 40 位 commit SHA> 不适用的 Fix / Tracking 可省略或填 `N/A`。只接受 `https://github.com/owner/repo/commit/`、`https://github.com/owner/repo/issues/<正整数>`,不接受查询参数、锚点或跨仓库链接。转移重定向不能绕过仓库限制。PR commits 连接截断时,使用固定 base/head SHA 的分页 Compare API 补全,并校验提交总数;超过 250 条的 PR 无需改填其他 Fix。force-push 移除修复提交、Issue 关闭或删除均使相应回复失效;作者需更新为有效回复。检查器不判断理由是否充分、commit 是否真正修复或延期是否合理。 -## 接入 +## 单一检查的显示与状态 -1. 将 [caller](examples/ai-review-disposition.yml)、[事件收集器](examples/ai-review-events.yml) 和 [失败恢复入口](examples/ai-review-recovery.yml) 复制到目标仓库 `.github/workflows/`,合入默认分支。caller 文件名保持 `ai-review-disposition.yml`,run-name 保持 PR 编号或 `all-open-prs`,供初始化失败时恢复路由。 -2. 设置 Variable `AI_REVIEW_BOTS`,例如 `chatgpt-codex-connector[bot],infiscale-bot`。caller 和恢复入口需要 `actions: read`、`contents: read`、`pull-requests: read`、`issues: read`、`checks: write`。 -3. 首次运行后,将脚本发布的 **AI Review / Disposition Check** 设为 Required Status Check,来源 GitHub Actions;不要选择 Actions job 的状态,其 SHA 不一定是 PR head。 -4. 同时启用 **Require conversation resolution before merging** 并保留人工 approval。Resolve/Unresolve 由 GitHub 原生规则处理,不需额外运行本检查。 +PR Checks 列表只发布一个固定名称 **AI Review / Disposition Check**。底层使用 Commit Status,同一 head SHA 和 context 只展示最新状态;不再创建自定义 Check Run、superseded 项、通知 job 或路由 job 的 PR 检查。GitHub 仍保留状态写入历史和后台 Actions 运行日志,这不等于 PR 列表新增条目。 -升级时先合入共享实现,再同步更新目标仓库 caller 和恢复入口;旧 caller 缺少上述 run-name 时,恢复入口无法自动定位初始化失败的目标。 +显式复查先将此名称发布为真正的 `pending`,再读取并校验机器人完成记录、人工回复、Fix / Tracking 和最终实时证据,结束后发布 `success` 或 `failure`。失败的必要步骤不会放行。点击 Details 查看该次后台运行的日志和 Summary。已完成的 Check Run 不能可靠地重置为待检查,因此不再使用临时 failure / Checking 代替 pending。 -PR opened/reopened/synchronize、目标分支及 PR 顶层评论变化触发单 PR 检查;不监听 ready_for_review。Review submitted/dismissed、行内评论 created/edited/deleted 先运行无权限收集器,再由默认分支的 workflow_run 启动可信检查器。收集器的 run-name 保持 PR 编号,不传入代码或审查结论。 +| 变化 | PR 中这一行的结果 | +| --- | --- | +| 全部机器人完成,全部意见处理有效 | success | +| 显式复查开始,或自动扫描发现证据变化 | pending | +| 缺少完成记录、有效回复或证据 | failure | +| 再次复查并满足全部条件 | pending → success | + +每个新 head 单独拥有这一名称的状态,旧提交的结果不能替代新 head 的检查。已有的其他 CI 检查仍分别保留。 + +## 接入与升级 + +1. 合入共享实现后,将 [caller](examples/ai-review-disposition.yml) 和 [失败恢复入口](examples/ai-review-recovery.yml) 放入目标仓库默认分支的 `.github/workflows/`。caller 文件名保持 `ai-review-disposition.yml`,run-name 保持 PR 编号或 `all-open-prs`,供初始化失败时恢复定位。 +2. 删除旧的 `AI Review Events` 事件收集器,替换旧 caller / recovery,停用其他直接调用旧实现的工作流。只升级共享脚本不能消除下游旧工作流产生的原生 job Check。 +3. 设置 Variable `AI_REVIEW_BOTS`,例如 `chatgpt-codex-connector[bot],infiscale-bot`。两个入口均需 `actions: read`、`contents: read`、`pull-requests: read`、`issues: read`、`statuses: write`,不再需要 `checks: write`。 +4. 将 caller 的 `workflow_run.workflows: [CI]` 改为目标仓库**现有**代码 CI 的准确 workflow 名称;没有此工作流时删除这个加速入口,保留定时扫描。不要为接收 review 新增 PR 事件收集工作流。 +5. 首次生成状态后,将 **AI Review / Disposition Check** 设置为 Required Status Check,来源匹配实际发布者 GitHub Actions。不要选择后台 worker 的 job 名称。同时启用 **Require conversation resolution before merging**,保留人工 approval。 +6. 从旧版迁移的现存 PR,升级接入文件后需推送一个新提交,使当前 head 不再带旧 Check Run。GitHub 同名 Check Run 和 Commit Status 同时存在时会同时判定,旧 job / superseded 历史也不会被新状态隐藏。本实现不删除或重命名历史。新 head 才作为单行显示的验收对象。 + +本次实现无需外部服务。共享仓库的代码与示例更新不会自动修改消费者仓库的工作流、变量或 ruleset;必须完成上述接入才生效。 + +## 默认分支后台入口 + +所有功能运行均从目标仓库默认分支启动,只检出可信共享脚本并实时读取 API,不检出或执行 PR 代码。可复用工作流只有一个 worker,把目标选择、规则校验、结果发布和中断收尾放在同一个 job 内。 -本仓库 Issue closed/reopened/deleted/transferred 时复查全部开放 PR,不维护 Issue → PR 反向关联。路由 job 只读取开放 PR 元数据,输出 worker matrix,不直接写 Check;单 PR、全仓复查和失败恢复均进入相同的按 PR 编号分组的 worker。每个运行最多并行评估 4 个 PR,一个 PR 失败不会取消其他目标;单 worker 最长 15 分钟。Actions matrix 单次最多支持 256 个目标,超限明确失败。排队中的目标在 worker 开始登记前仍可能显示旧结果。新建普通 Issue 不触发。 +- 已有 `CI` workflow 完成:后台复查所有开放 PR,为打开 / 推送 PR 提供加速入口,不依赖来源运行提供的 artifact 或结论。 +- PR 顶层评论 created / edited / deleted:显式复查对应 PR。 +- 本仓库 Issue closed / reopened / deleted / transferred:显式复查所有开放 PR。 +- 每五分钟定时扫描:检测 review submitted / dismissed、行内回复增删改、新 head、权限和 Tracking Issue 变化;cron 使用第 3、8、13…58 分钟,避开整点。GitHub 可能延迟或丢弃 schedule,五分钟是计划频率而非最大延迟保证。 +- 手动 `workflow_dispatch`:填写正整数 `pr-number`;全仓复查勾选 `all-open-prs` 并保持编号 0。首次启用后建议立即手动全仓复查。 -### 自动化修改 Issue +不直接监听 `push`、`pull_request*` 或部署事件;这些事件会让 GitHub 为工作流 job 额外发布 PR 检查。后台入口使用 `workflow_run`、`issue_comment`、`issues`、`schedule` 和 `workflow_dispatch`,原生 job 留在 Actions 运行记录中。消费者需要沿用该事件模型,不能另行把此可复用工作流挂到 PR 事件上。 -GitHub 不会因 `GITHUB_TOKEN` 修改 Issue 自动启动后续 Actions。使用 [关闭 Issue 并复查的示例](examples/ai-review-close-issue.yml),或在已有自动化修改后 dispatch **同一份 caller**: +排队及扫描有延迟:事件发生到下一次扫描 / worker 处理前,旧状态可能仍可见;执行器登记新一轮评估时才写入 pending。尚未发布状态的新 head 由 Required Status Check 保持等待。需要快速复查时,从默认分支手动 dispatch,不能要求纯异步方案在事件发生瞬间撤销旧成功。 + +### 无变化扫描与状态写入上限 + +定时扫描及已有 CI 完成后的扫描使用 `only-changed: true`。每次仍读取当前 PR、机器人和回复,并重新查询实际使用的人工权限与 Tracking Issue;只有完整证据指纹、机器人配置和判定结果都未变化时才保留已有终态,不发布新的 pending / success。发现任何变化、上次中断、读取异常或无有效指纹时重新发布 pending 并评估。显式手动复查和评论 / Issue 事件不跳过 pending。 + +GitHub 对同一 SHA、同一 status context 最多接收 1000 次状态写入,因此不能承诺无限次更新。未变化扫描不消耗此额度;接近上限时预留写入将状态固定为 failure,并提示推送新提交,避免留下无法撤销的 success。不要由其他工作流、App 或本地 CLI 写这个正式 context;它们会破坏序号、指纹、发布者校验和额度计数。 + +### 自动化修改 Issue / review + +GitHub 不会因 `GITHUB_TOKEN` 修改 Issue 或评论自动触发后续 Actions。定时扫描会检测变化;如需立即排队,使用 [关闭 Issue 并复查的示例](examples/ai-review-close-issue.yml),或在自动化后 dispatch **同一份 caller**: ```bash gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ --ref "$DEFAULT_BRANCH" -f all-open-prs=true ``` -DEFAULT_BRANCH 为仓库默认分支,负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 另需 `issues: write`。无需额外 Token;其他自动化发布 Review / 评论后同样须主动复查。不要由另一工作流或本地 CLI 绕过共享 worker 直接写正式 Check。检查器使用 GITHUB_RUN_ID/run_attempt 标识运行,caller 和恢复工作流的局部 run_number 不再相互比较。 - -手动检查填写正整数 pr-number;全仓复查勾选 all-open-prs、保持编号 0。默认不会隐式全仓扫描。CI 始终实时读取 PR 并将 Check 写入最新 head;通过前再次读取数据,清缓存复核权限和 Issue 状态。只读 REST/GraphQL 请求遇瞬时网络错误、429、500/502/503/504 或带 Retry-After 的 403 时最多尝试 3 次;遵守 Retry-After,等待超过 60 秒则中止并报告失败,不提前重试。创建/修改 Check 不盲重试。数据变化或读取失败不发布成功,Issue 的 404/410 会给出具体 Tracking 提示。 +负责 dispatch 的 job 需要 `actions: write`,关闭 Issue 另需 `issues: write`。不需要额外 Token,不另建对 PR 显示的通知 job。 -同一 PR 的全部 worker 共用一个 concurrency group,cancel-in-progress=false;正在运行的 worker 保持执行,等待中的重复触发由最新任务合并替代。不同 PR 可并行。worker 开始后重新读取当前 head;同一仓库、PR、head 和 GitHub Actions App 复用同一 Check ID,再更新结果。GitHub 对已完成 Check 的 status-only PATCH 会保留旧 conclusion,REST 不接受 null conclusion/completed_at,GraphQL 显式 null 也未重置;因此复查开始时原地发布临时 failure,标题 Checking,确保旧 success 立即失效,结束后再发布真实结论。首次创建仍使用 in_progress;Actions worker 显示执行进度。每次最终发布刷新 completed_at。新 head 单独创建 Check;不会再创建或改名出 superseded 项,既有历史记录不整理。重跑旧 run ID/attempt 不能接管更新运行。 +## 并发、最终复核与失败恢复 -此方案无需外部服务。GitHub 自动产生的路由、评估及事件收集 job Check 仍可能出现在 PR 页面;唯一业务门禁是 AI Review / Disposition Check,不能据此承诺整页仅一项。实验工作流发布的 Integration Test 也不属于正式检查器管理范围。 +所有单 PR、全仓和恢复运行共用仓库级 concurrency group,`cancel-in-progress=false`,避免两个入口同时写相同 context。等待中的重复触发可能被最新任务替代,后续定时扫描会重新覆盖全部开放 PR。单次运行串行处理目标,一个 PR 失败后仍继续其余 PR;worker 最长 30 分钟,目标过多时需关注超时和 API 配额。 -普通退出由 always 收尾在释放同一个 PR 并发槽前读取本机登记日志,仅将仍由自己持有的 in_progress 或临时 Checking 结果原地标记中断 failure。硬超时、取消、检出/初始化失败由默认分支的 workflow_run 恢复入口定位目标,再进入同一个 worker 队列重新检查实时数据;恢复不直接写 Check,也不会创建替代 Check。恢复重新评估可能得到正常的 success 或业务 failure。仅读取可信脚本写出的本机日志或实时 API,不下载或执行来源工作流的 artifact。最终发布失败会记录 Check ID 和重新 dispatch 的提示。 +显式检查在获取当前 head 后先发布 pending。通过前再次读取完整 PR 快照,清缓存复核人工权限和 Issue 状态,确认结果仍有效。只读 REST / GraphQL 请求的瞬时网络错误、429、500/502/503/504 或带 Retry-After 的 403 最多重试三次;不早于 Retry-After 重试,等待超过 60 秒则中止。状态写入不盲重试。 -Checks API 的 ownership 校验与 PATCH 不是原子操作。并发槽约束正常运行的 Actions writer;人为硬取消时已经送出的 HTTP 写入仍有极短的竞态,复用单一 Check ID 无法提供旧方案不同 ID 的隔离保证。不要另行直接调用 Checks API 写这个门禁;发生中断或 API 异常后应等待恢复并检查最新结果。 +状态 Details URL 关联实际 run ID / attempt,并携带受控的 PR、写入计数和证据指纹。旧 run 的重跑不能覆盖已登记的新 run;最终发布和 cleanup 先检查当前状态 ID 是否仍属于自己。普通退出通过本机登记日志将自己遗留的 pending 标记为中断 failure;最终写入失败时保留 pending 阻断。取消、硬超时或初始化失败由独立的默认分支恢复入口定位原目标,经过同一个 worker 队列实时重查;恢复不直接写旁路结果。定时扫描也会重试遗留 pending / failure。 -恢复是异步的:事件发生到新 Check 登记、或失败到恢复运行之间存在窗口。若首次读取、枚举或登记失败,旧 success 可能在恢复前仍可见;GitHub API 完全不可读写、恢复入口未安装或自身失败时,脚本无法保证立即撤销它。必须监控 caller/恢复运行失败并重新 dispatch;要求这个窗口内也绝不允许合并时,需额外的 GitHub 侧合并门禁,不能仅依赖本异步检查。登记后的遗留 in_progress 或临时 Checking failure 会继续阻断。 +所有权读取与状态 POST 不是原子操作,硬取消时已发送的 HTTP 写入仍存在短暂竞态。API 不可读写、首次读取 / 初始化失败或恢复入口自身失败时,也无法保证立即撤销旧成功;必须监控后台 Actions 的异常并重新 dispatch。严禁绕过共享队列并发写正式状态。 ## 验证与边界 -运行 `python -m unittest discover -s scripts/tests -v`。测试包含 AI 轮次、编辑者授权、第二人工账号权限/撤权、超过 250 条提交、限流重试、初始化/发布失败、20 次检查复用同一 ID、旧运行接管拦截和全仓/恢复路由,无需真实账号或 Token。接入时另验收 caller 与恢复入口的 run-name、取消/超时和初始化失败路由。真实 Bot 接入仍须现场验证;不能把模拟当成实际授权已生效。 +运行 `python -m unittest discover -s scripts/tests -v`。测试覆盖原有审查规则、权限和分页,以及同名状态的反复 pending / success / failure、无变化扫描去重、Issue 关闭 / 权限撤销、新轮次、中断收尾、旧运行防覆盖和状态额度耗尽时的阻断。工作流另用 actionlint 验证。 -自动关 Issue 的 [触发工作流](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306714886) 和 [后续复查](https://github.com/liaoxiang0304/VR_DexCopilot/actions/runs/40306733764) 已在隔离仓库实测。一次性实验、规则配置和历史结果保留在[测试仓库](https://github.com/liaoxiang0304/VR_DexCopilot),不作为生产接入文件。 +单行契约是当前 PR Checks 列表中的一个 status context,不是 GitHub 不保留底层记录。旧提交、旧工作流和旧 Check Run 历史不清理。只支持 GitHub.com 同仓库 PR / Issue;同一 head 被多个开放 PR 共用时无法分别表达各 PR 的不同审查结果,应推送不同 head。fork 和 merge queue 尚未验收。模拟 / API 状态生命周期测试不能证明真实机器人已经完成审查或实际权限已生效。 -仅支持 GitHub.com、同仓库 PR/Issue;fork PR、Issue 转移不作为本次验收前提。多 PR 共用同一 head 存在 GitHub 门禁关联限制,各 PR 应使用独立 head。不支持 merge queue 合成 SHA 或不可删改的历史审计。 +GitHub 机制参考:[Commit Status 与 1000 次上限](https://docs.github.com/en/rest/commits/statuses)、[工作流原生检查的事件关联及同名检查冲突](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks)。 diff --git a/docs/examples/ai-review-close-issue.yml b/docs/examples/ai-review-close-issue.yml index 41c1342..a07a23b 100644 --- a/docs/examples/ai-review-close-issue.yml +++ b/docs/examples/ai-review-close-issue.yml @@ -37,6 +37,6 @@ jobs: gh api "repos/$GITHUB_REPOSITORY/issues/$ISSUE_NUMBER" \ --method PATCH -f state=closed > /dev/null # Issue events from GITHUB_TOKEN do not start Actions; dispatch does. - # Reuse the SAME caller so its run numbers still order newer results. + # Reuse the same caller and its repository-wide writer queue. gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ --ref "$DEFAULT_BRANCH" -f all-open-prs=true diff --git a/docs/examples/ai-review-disposition.yml b/docs/examples/ai-review-disposition.yml index bc7d079..7eebcd9 100644 --- a/docs/examples/ai-review-disposition.yml +++ b/docs/examples/ai-review-disposition.yml @@ -1,18 +1,21 @@ # Copy to each project's .github/workflows/ai-review-disposition.yml. -# Both this file and the event collector must exist on the default branch. +# Install on the default branch; remove the old AI Review Events collector. name: AI Review Disposition -# Recovery reads this routing value if the run fails before publishing a Check. +# Recovery reads this routing value if the run fails before publishing a status. run-name: >- - ${{ (github.event_name == 'issues' || inputs.all-open-prs) && 'all-open-prs' - || github.event.pull_request.number + ${{ (github.event_name == 'issues' || github.event_name == 'schedule' + || github.event_name == 'workflow_run' || inputs.all-open-prs) && 'all-open-prs' || (github.event_name == 'issue_comment' && github.event.issue.number) - || inputs.pr-number || github.event.workflow_run.display_title || '0' }} + || inputs.pr-number || '0' }} on: - pull_request_target: - types: [opened, reopened, synchronize, edited] + # Reviews, inline replies and PR head changes are detected by background polls. + # Direct PR/review triggers would add native job Checks to the PR page. + schedule: + - cron: '3-58/5 * * * *' workflow_run: - workflows: [AI Review Events] + # Match the repository's EXISTING CI workflow name; do not add a collector. + workflows: [CI] types: [completed] issue_comment: types: [created, edited, deleted] @@ -26,7 +29,7 @@ on: type: number default: 0 all-open-prs: - description: 'Explicitly recheck all open PRs after automated Issue changes' + description: 'Explicitly recheck all open PRs' required: false type: boolean default: false @@ -36,25 +39,21 @@ permissions: contents: read pull-requests: read issues: read - checks: write + statuses: write jobs: disposition: if: >- - ${{ (github.event_name != 'issue_comment' || github.event.issue.pull_request) - && (github.event_name != 'pull_request_target' - || github.event.action != 'edited' || github.event.changes.base) }} + ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + && (github.event_name != 'issue_comment' || github.event.issue.pull_request) }} uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main with: all-open-prs: >- - ${{ github.event_name == 'issues' + ${{ contains(fromJSON('["issues","schedule","workflow_run"]'), github.event_name) || (github.event_name == 'workflow_dispatch' && inputs.all-open-prs) }} - # Collector run-name is the PR number, even when workflow_run.pull_requests is empty. pr-number: >- - ${{ github.event.pull_request.number - || (github.event_name == 'issue_comment' && github.event.issue.number) - || fromJSON(inputs.pr-number || '0') - || fromJSON(github.event.workflow_run.display_title || '0') }} - # Set this repository/organization variable to exact bot logins. + ${{ (github.event_name == 'issue_comment' && github.event.issue.number) + || fromJSON(inputs.pr-number || '0') }} + only-changed: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_run' }} bot-logins: ${{ vars.AI_REVIEW_BOTS }} shared-ref: main diff --git a/docs/examples/ai-review-events.yml b/docs/examples/ai-review-events.yml deleted file mode 100644 index 55c74d1..0000000 --- a/docs/examples/ai-review-events.yml +++ /dev/null @@ -1,19 +0,0 @@ -# Copy to each project's .github/workflows/ai-review-events.yml. -# This unprivileged collector never checks out or executes PR code. -name: AI Review Events -# Pass the PR number through workflow_run.display_title; do not use the PR title. -run-name: ${{ github.event.pull_request.number }} - -on: - pull_request_review: - types: [submitted, dismissed] - pull_request_review_comment: - types: [created, edited, deleted] - -permissions: {} - -jobs: - notify: - runs-on: ubuntu-latest - steps: - - run: echo "AI review state changed; trusted evaluator will read live API state" diff --git a/docs/examples/ai-review-recovery.yml b/docs/examples/ai-review-recovery.yml index d9e5071..6f745f6 100644 --- a/docs/examples/ai-review-recovery.yml +++ b/docs/examples/ai-review-recovery.yml @@ -12,7 +12,7 @@ permissions: contents: read pull-requests: read issues: read - checks: write + statuses: write jobs: recover: @@ -22,5 +22,6 @@ jobs: uses: IS-Model-Framework/.github/.github/workflows/reusable-ai-review-disposition.yml@main with: recover-run-id: ${{ github.event.workflow_run.id }} + only-changed: true bot-logins: ${{ vars.AI_REVIEW_BOTS }} shared-ref: main diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 1a57d6e..f475731 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -2,6 +2,7 @@ """Check AI review rounds and dispositions without running PR code.""" import argparse +import hashlib import json import os import re @@ -400,15 +401,33 @@ def summary(number, head, result): return "\n".join(lines) -def current_check(api, repository, number, head, check): - """Verify ownership; the shared per-PR Actions queue serializes all writers.""" - live = api.request("GET", f"/repos/{repository}/check-runs/{check['id']}") - return ( - live["name"] == CHECK_NAME - and live["head_sha"] == head - and live.get("external_id") == check["external_id"] - and live["app"]["id"] == check["app"]["id"] +def latest_status(api, repository, head): + """The combined endpoint returns one latest status per context, not its history.""" + statuses = api.pages(f"/repos/{repository}/commits/{head}/status", "statuses") + return next( + (item for item in statuses if item["context"].lower() == CHECK_NAME.lower()), None + ) + + +def status_identity(status, repository): + match = re.fullmatch( + rf"https://github\.com/{re.escape(repository)}/actions/runs/([0-9]+)" + r"/attempts/([0-9]+)#ai-disposition:([1-9][0-9]*):([1-9][0-9]*):([0-9a-f]{64}|none)", + status.get("target_url") or "", ) + if ( + not match + or status.get("creator", {}).get("login", "").lower() != "github-actions[bot]" + ): + raise ValueError("Disposition context is owned by an unknown writer") + run, attempt, number, writes, digest = match.groups() + return int(run), int(attempt), int(number), int(writes), digest + + +def current_status(api, repository, number, head, status): + """The repository-wide worker queue serializes all entry points.""" + live = latest_status(api, repository, head) + return live is not None and live["id"] == status["id"] def generation(): @@ -419,96 +438,105 @@ def generation(): ) -def register_check(api, repository, number, head, sequence=None): - """Get or reopen one managed Check. Call only inside the per-PR writer queue.""" +def publish_status( + api, + repository, + number, + head, + state, + description, + previous=None, + sequence=None, + digest="none", +): run, attempt = sequence if sequence is not None else generation() - prefix = f"ai-review-disposition:{number}:" - runs = api.pages( - f"/repos/{repository}/commits/{head}/check-runs" - f"?check_name={quote(CHECK_NAME, safe='')}&filter=all", - "check_runs", + writes = status_identity(previous, repository)[3] if previous else 0 + if writes >= 1000: + raise RuntimeError("Status update limit reached; push a new commit") + # Reserve the last writes for a blocking result, never an irreversible success. + if writes >= 998: + state, description, digest = ( + "failure", + "Status update limit reached; push a new commit", + "none", + ) + url = ( + f"https://github.com/{repository}/actions/runs/{run}/attempts/{attempt}" + f"#ai-disposition:{number}:{writes + 1}:{digest}" + ) + return api.request( + "POST", + f"/repos/{repository}/statuses/{head}", + { + "context": CHECK_NAME, + "state": state, + "description": description[:140], + "target_url": url, + }, ) - runs = [ - check - for check in runs - if check["app"].get("slug") == "github-actions" - and (not check.get("external_id") or check["external_id"].startswith(prefix)) - ] - def order(check): - match = re.fullmatch( - re.escape(prefix) + r"([0-9]+):([0-9]+)", check.get("external_id") or "" - ) - return (int(match[1]), int(match[2]), check["id"]) if match else (0, 0, check["id"]) - previous = max(runs, key=order) if runs else None - if previous and run and order(previous)[:2] > (run, attempt): - return None - body = { - "name": CHECK_NAME, - "status": "in_progress", - "external_id": f"{prefix}{run}:{attempt}", - "output": {"title": "Checking", "summary": f"Evaluating PR #{number} at {head}."}, - } +def register_status(api, repository, number, head, sequence=None): + """Revoke a previous success with real pending in the same visible context.""" + sequence = sequence if sequence is not None else generation() + previous = latest_status(api, repository, head) if previous: - # Completed Checks cannot reliably return to in_progress. Revoke old - # success explicitly while keeping the same ID and showing progress in output. - body.update( - status="completed", - conclusion="failure", - completed_at=datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), - ) - check = api.request( - "PATCH", f"/repos/{repository}/check-runs/{previous['id']}", body - ) - else: - check = api.request( - "POST", f"/repos/{repository}/check-runs", {"head_sha": head, **body} - ) + old = status_identity(previous, repository) + if old[:2] > sequence: + return None + if old[2] != number: + publish_status( + api, + repository, + number, + head, + "failure", + "Multiple PRs share this head; push distinct head commits", + previous, + sequence, + ) + raise ValueError("Multiple PRs share this head; use distinct head commits") + if old[3] >= 998: + if old[3] < 1000: + publish_status(api, repository, number, head, "failure", "", previous, sequence) + raise RuntimeError("Status update limit reached; push a new commit") + status = publish_status( + api, + repository, + number, + head, + "pending", + f"Checking PR #{number}", + previous, + sequence, + ) journal = os.environ.get("AI_REVIEW_CHECKS_FILE") if journal: with JOURNAL_LOCK, open(journal, "a", encoding="utf-8") as stream: stream.write( - json.dumps({"number": number, "head": head, "sequence": [run, attempt]}) + "\n" + json.dumps({"number": number, "head": head, "sequence": list(sequence)}) + "\n" ) - return check + return status def finish_pending(api, repository, number, head, sequence): - """Close this job's unfinished Check before releasing its per-PR writer queue.""" - external_id = f"ai-review-disposition:{number}:{sequence[0]}:{sequence[1]}" - runs = api.pages( - f"/repos/{repository}/commits/{head}/check-runs" - f"?check_name={quote(CHECK_NAME, safe='')}&filter=all", - "check_runs", - ) - own = [ - run - for run in runs - if run.get("external_id") == external_id - and run["app"].get("slug") == "github-actions" - ] - if not own: + """Finish only this run's pending status, without adding a visible context.""" + status = latest_status(api, repository, head) + if status is None or status["state"] != "pending": return True - check = max(own, key=lambda run: run["id"]) - if ( - check["status"] == "completed" - and check.get("output", {}).get("title") != "Checking" - ): + identity = status_identity(status, repository) + if identity[:3] != (*sequence, number): return True - if current_check(api, repository, number, head, check): - api.request( - "PATCH", - f"/repos/{repository}/check-runs/{check['id']}", - { - "status": "completed", - "conclusion": "failure", - "completed_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), - "output": { - "title": "Evaluation interrupted", - "summary": "Evaluation interrupted; dispatch a new disposition check.", - }, - }, + if current_status(api, repository, number, head, status): + publish_status( + api, + repository, + number, + head, + "failure", + "Evaluation interrupted; dispatch a new disposition check", + status, + sequence, ) return True @@ -530,7 +558,7 @@ def cleanup_file(api, repository, path): def recovery_targets(api, repository, run_id): - """Route recovery to the same per-PR workers; this function never writes Checks.""" + """Find interrupted caller targets without writing statuses.""" run = api.request("GET", f"/repos/{repository}/actions/runs/{run_id}") if run["path"] != ".github/workflows/ai-review-disposition.yml": raise ValueError("Recovery requires the documented caller workflow") @@ -553,7 +581,7 @@ def recovery_targets(api, repository, run_id): def prepare_targets(api, repository, number=None, all_open=False, recover=None): - """Enumerate trusted metadata for an Actions matrix, without publishing Checks.""" + """Enumerate trusted PR metadata for the serialized background worker.""" if recover: prs = recovery_targets(api, repository, recover) elif all_open: @@ -565,12 +593,10 @@ def prepare_targets(api, repository, number=None, all_open=False, recover=None): for pr in prs if pr["state"] == "open" } - if len(targets) > 256: - raise ValueError("Actions matrix supports at most 256 open PRs per sweep") return [targets[number] for number in sorted(targets)] -def check_pr(api, repository, number, bots, head=None): +def check_pr(api, repository, number, bots, head=None, only_changed=False): try: pr = api.request("GET", f"/repos/{repository}/pulls/{number}") if pr["state"] != "open": @@ -581,9 +607,7 @@ def check_pr(api, repository, number, bots, head=None): # this metadata read fails. The evaluation must still obtain live PR data. if head is None: raise - check = register_check(api, repository, number, head) - if check is None: - return True + permissions, tracking = {}, {} @cache def authorized(login, author): @@ -593,11 +617,13 @@ def authorized(login, author): response = api.request( "GET", f"/repos/{repository}/collaborators/{quote(login, safe='')}/permission" ) - return response["permission"] in {"admin", "write"} + allowed = response["permission"] in {"admin", "write"} except HTTPError as error: if error.code != 404: raise - return False + allowed = False + permissions[login] = allowed + return allowed @cache def tracking_valid(value): @@ -609,7 +635,7 @@ def tracking_valid(value): return False try: item = api.request("GET", f"/repos/{repository}/issues/{match[2]}") - return ( + valid = ( item["state"] == "open" and "pull_request" not in item and item["repository_url"].lower() @@ -618,50 +644,120 @@ def tracking_valid(value): except HTTPError as error: if error.code not in {404, 410}: raise - return False - - try: - if not current_check(api, repository, number, head, check): - return True + valid = False + tracking[value] = valid + return valid + + def fingerprint(data, result): + return hashlib.sha256( + json.dumps( + { + "data": data, + "bots": sorted(bots), + "permissions": permissions, + "tracking": tracking, + "result": result, + }, + sort_keys=True, + separators=(",", ":"), + ).encode() + ).hexdigest() + + def read_evaluation(): + if not bots or any( + not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots + ): + raise ValueError("Valid bot configuration is required") data = snapshot(api, repository, number) if data["head"] != head or data["state"] != "open": raise RuntimeError("PR changed before evaluation; rerun required") - result = evaluate(data, bots, authorized, tracking_valid) + return data, evaluate(data, bots, authorized, tracking_valid) + + prepared, preparation_error = None, None + if only_changed: + # Polling validates live evidence but writes only changed results. Rewriting + # unchanged successes every five minutes would exhaust GitHub's status limit. + try: + previous = latest_status(api, repository, head) + if previous: + identity = status_identity(previous, repository) + if identity[:2] > generation(): + return True + if identity[2] != number: + raise ValueError("Multiple PRs share this head") + if previous["state"] in {"success", "failure"} and identity[4] != "none": + prepared = read_evaluation() + data, result = prepared + if ( + fingerprint(data, result) == identity[4] + and previous["state"] == ("success" if passed(result) else "failure") + and current_status(api, repository, number, head, previous) + ): + return passed(result) + except Exception as error: + preparation_error = error + status = register_status(api, repository, number, head) + if status is None: + return True + + digest = "none" + try: + if not current_status(api, repository, number, head, status): + return True + if preparation_error: + raise preparation_error + data, result = prepared if prepared is not None else read_evaluation() + stable = True if passed(result): # A second read catches comments/commits changed during pagination. if snapshot(api, repository, number) != data: + stable = False result["errors"].append( "PR review data changed during evaluation; rerun required" ) else: authorized.cache_clear() tracking_valid.cache_clear() + permissions.clear() + tracking.clear() result = evaluate(data, bots, authorized, tracking_valid) ok = passed(result) + if stable: + digest = fingerprint(data, result) report = summary(number, head, result) + blocked = sum(bool(finding["error"]) for finding in result["findings"]) + description = ( + f"{'Passed' if ok else 'Failed'}: {len(result['findings'])} findings, " + f"{blocked} blocked, " + f"{len(result['errors'])} review errors" + ) except Exception as error: ok = False # Avoid printing tokens, response bodies, or attacker-controlled exception text. report = ( f"PR #{number}: evaluation failed ({type(error).__name__}); rerun required." ) + description = f"Evaluation failed ({type(error).__name__}); rerun required" try: - if not current_check(api, repository, number, head, check): + if not current_status(api, repository, number, head, status): return True - api.request( - "PATCH", - f"/repos/{repository}/check-runs/{check['id']}", - { - "status": "completed", - "conclusion": "success" if ok else "failure", - "completed_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), - "output": {"title": "Passed" if ok else "Failed", "summary": report[:60000]}, - }, + final = publish_status( + api, + repository, + number, + head, + "success" if ok else "failure", + description, + status, + digest=digest, ) + if ok and final["state"] != "success": + report += "\n- Status update limit reached; push a new commit." + ok = False except Exception as error: print( - f"PR #{number}: could not publish Check #{check['id']} " - f"({type(error).__name__}); check may remain in_progress; dispatch a new check.", + f"PR #{number}: could not publish disposition status " + f"({type(error).__name__}); status may remain pending; dispatch a new check.", file=sys.stderr, ) return False @@ -685,38 +781,34 @@ def main(): "--all-open-prs", action="store_true", help="Explicitly recheck every open PR" ) target.add_argument( - "--cleanup-file", help="Finish interrupted Checks from a trusted local journal" + "--cleanup-file", help="Fail interrupted pending statuses from a local journal" ) target.add_argument( - "--recover-run", type=int, help="Route an interrupted caller run to PR workers" + "--recover-run", type=int, help="Recheck the PRs of an interrupted caller run" ) parser.add_argument( "--prepare-targets", action="store_true", - help="Output the worker matrix; never write Checks", + help="Print target metadata without publishing statuses (legacy dry-run output)", ) parser.add_argument( "--head-sha", help="Trusted head from routing; register even if the first live PR read fails", ) parser.add_argument("--bots", default=os.environ.get("AI_REVIEW_BOTS", "")) + parser.add_argument( + "--only-changed", + action="store_true", + help="Poll live evidence without rewriting unchanged terminal results", + ) args = parser.parse_args() bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") - evaluating = not (args.cleanup_file or args.prepare_targets) if ( - ( - evaluating - and ( - not bots - or any(not re.fullmatch(r"[a-z0-9-]+(?:\[bot\])?", bot) for bot in bots) - ) - ) - or not args.repository + not args.repository or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository) or (args.pr_number is not None and args.pr_number <= 0) or (args.recover_run is not None and args.recover_run <= 0) - or ((args.recover_run or args.all_open_prs) and not args.prepare_targets) or (args.prepare_targets and args.cleanup_file) or ( args.head_sha is not None @@ -740,10 +832,30 @@ def main(): with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: stream.write(f"matrix={matrix}\nhas-targets={'true' if targets else 'false'}\n") return 0 - if args.head_sha: - ok = check_pr(api, args.repository, args.pr_number, bots, args.head_sha) + options = {"only_changed": True} if args.only_changed else {} + if args.recover_run or args.all_open_prs: + targets = prepare_targets( + api, args.repository, args.pr_number, args.all_open_prs, args.recover_run + ) + ok = True + for target in targets: + try: + ok = ( + check_pr( + api, args.repository, target["number"], bots, target["head"], **options + ) + and ok + ) + except Exception as error: + print( + f"PR #{target['number']}: status update failed ({type(error).__name__})", + file=sys.stderr, + ) + ok = False + elif args.head_sha: + ok = check_pr(api, args.repository, args.pr_number, bots, args.head_sha, **options) else: - ok = check_pr(api, args.repository, args.pr_number, bots) + ok = check_pr(api, args.repository, args.pr_number, bots, **options) return 0 if ok else 1 diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 74bc09c..2d8661c 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -11,8 +11,8 @@ CHECK_NAME, GitHub, check_pr, - current_check, - register_check, + current_status, + register_status, prepare_targets, evaluate, main, @@ -697,9 +697,7 @@ def test_graphql_errors_reject_partial_data(self): api.graphql("query", {}) def test_resolution_changes_during_check_do_not_block(self): - api = GitHub("test-token") data = fixture("Disposition: Invalid\nReason: False positive") - pr = pr_metadata(user={"login": data["author"]}) for resolutions in ((False, True), (True, False)): with self.subTest(resolutions=resolutions): @@ -725,19 +723,11 @@ def graphql(query, variables, states=states): return {"node": {field: page(nodes)}} self.fail("Unexpected GraphQL query") - with ( - patch("scripts.check_ai_review_disposition.current_check", return_value=True), - patch.object( - api, "request", side_effect=[pr, {"id": 99}, pr, pr, pr, pr, {}] - ) as request, - patch.object(api, "graphql", side_effect=graphql), - patch.object(api, "pages", return_value=[]), - patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), - patch("builtins.print"), - ): + api = StatusStore() + with patch.object(api, "graphql", side_effect=graphql), patch("builtins.print"): self.assertTrue(check_pr(api, "org/repo", 128, {BOT})) self.assertEqual(list(states), []) - self.assertEqual(request.call_args.args[2]["conclusion"], "success") + self.assertEqual(api.gate()[0]["state"], "success") def test_snapshot_rejects_head_change_during_read(self): api = GitHub("test-token") @@ -807,15 +797,15 @@ def test_commit_link_does_not_add_api_requests(self): calls, ok = self.run_check([data, copy.deepcopy(data)]) self.assertTrue(ok) self.assertEqual(len(calls), 3) - self.assertEqual(calls[-1].args[2]["conclusion"], "success") + self.assertEqual(calls[-1].args[2]["state"], "success") def test_check_is_written_to_pr_head_not_event_sha(self): data = fixture("Disposition: Invalid\nReason: False positive") calls, ok = self.run_check([data, copy.deepcopy(data)]) self.assertTrue(ok) - self.assertEqual(calls[1].args[2]["head_sha"], HEAD) - self.assertEqual(calls[1].args[2]["name"], CHECK_NAME) - self.assertEqual(calls[-1].args[2]["conclusion"], "success") + self.assertEqual(calls[1].args[1].rsplit("/", 1)[-1], HEAD) + self.assertEqual(calls[1].args[2]["context"], CHECK_NAME) + self.assertEqual(calls[-1].args[2]["state"], "success") def test_new_finding_during_read_prevents_success(self): for reviewer in (BOT, "human-reviewer"): @@ -825,7 +815,7 @@ def test_new_finding_during_read_prevents_success(self): changed["threads"].append(fixture(reviewer=reviewer)["threads"][0]) calls, ok = self.run_check([data, changed]) self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_completion_comment_changed_during_read_prevents_success(self): data = fixture("Disposition: Invalid\nReason: Test") @@ -834,12 +824,12 @@ def test_completion_comment_changed_during_read_prevents_success(self): changed["comments"][0]["body"] = INFISCALE_START calls, ok = self.run_check([data, changed]) self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_api_failure_finishes_check_as_failure(self): calls, ok = self.run_check(RuntimeError("failed")) self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_closed_tracking_issue_or_pr_cannot_defer(self): for reviewer in (BOT, "human-reviewer"): @@ -852,7 +842,7 @@ def test_closed_tracking_issue_or_pr_cannot_defer(self): with self.subTest(reviewer=reviewer, item=item): calls, ok = self.run_check([data], item) self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_deferred_requires_a_successful_open_issue_lookup(self): for reviewer in (BOT, "human-reviewer"): @@ -865,7 +855,7 @@ def test_deferred_requires_a_successful_open_issue_lookup(self): calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) self.assertTrue(ok) self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) - self.assertEqual(calls[-1].args[2]["conclusion"], "success") + self.assertEqual(calls[-1].args[2]["state"], "success") def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): data = fixture( @@ -878,7 +868,7 @@ def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): calls, ok = self.run_check([data], error) self.assertFalse(ok) self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_deleted_issue_reports_invalid_tracking_instead_of_api_failure(self): data = fixture( @@ -886,9 +876,9 @@ def test_deleted_issue_reports_invalid_tracking_instead_of_api_failure(self): "Tracking: https://github.com/org/repo/issues/42" ) error = HTTPError("https://api.github.com/issue", 410, "Gone", {}, None) - calls, ok = self.run_check([data], error) + _, ok = self.run_check([data], error) self.assertFalse(ok) - report = calls[-1].args[2]["output"]["summary"] + report = self.report self.assertIn("[Deferred]", report) self.assertIn("deleted issues", report) self.assertNotIn("evaluation failed", report) @@ -911,7 +901,7 @@ def test_only_canonical_github_issue_urls_are_queried(self): self.assertFalse(ok) # Only PR metadata, Check creation, and Check completion; no issue request. self.assertEqual(len(calls), 3) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_multiple_findings_share_one_issue_lookup(self): data = fixture( @@ -948,7 +938,7 @@ def test_closed_issue_or_revoked_permission_during_final_verification_blocks(sel data["threads"][0]["comments"][-1]["author"]["login"] = login calls, ok = self.run_check([data, copy.deepcopy(data)], [first, second]) self.assertFalse(ok) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def test_cross_repository_links_are_rejected_without_reading_them(self): for repo in ("org/other", "other/repo"): @@ -1004,7 +994,7 @@ def test_permission_lookup_errors_block_and_encode_the_login(self): self.assertEqual( calls[2].args, ("GET", "/repos/org/repo/collaborators/user%2Fname/permission") ) - self.assertEqual(calls[-1].args[2]["conclusion"], "failure") + self.assertEqual(calls[-1].args[2]["state"], "failure") def run_check(self, snapshots, lookup=None): api = GitHub("test-token") @@ -1015,7 +1005,7 @@ def respond(method, path, body=None): if (method, path) == ("GET", "/repos/org/repo/pulls/128"): return pr if method == "POST": - return {"id": 99} + return {"id": 99, "creator": {"login": "github-actions[bot]"}, **body} if method == "PATCH": return {} value = next(lookups) if lookups else lookup @@ -1030,160 +1020,174 @@ def respond(method, path, body=None): with ( patch.object(api, "request", side_effect=respond) as request, patch.object(api, "pages", return_value=[]), - patch("scripts.check_ai_review_disposition.current_check", return_value=True), + patch("scripts.check_ai_review_disposition.current_status", return_value=True), patch("scripts.check_ai_review_disposition.snapshot", side_effect=snapshots), patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}), - patch("builtins.print"), + patch("sys.stdout", new_callable=io.StringIO) as stdout, ): ok = check_pr(api, "org/repo", 128, {BOT}) + self.report = stdout.getvalue() return request.call_args_list, ok -class CheckStore(GitHub): - """Exercise interleaved evaluations without writing to GitHub.""" +class StatusStore(GitHub): + """Model GitHub's append-only history and latest-per-context combined endpoint.""" def __init__(self): super().__init__("test-token") - self.checks = {} - - def add(self, run, attempt=1, app=1, number=128): - check = { - "id": len(self.checks) + 1, - "name": CHECK_NAME, - "head_sha": HEAD, - "status": "in_progress", - "app": {"id": app, "slug": "github-actions" if app == 1 else "other"}, - "external_id": f"ai-review-disposition:{number}:{run}:{attempt}", + self.statuses = [] + + def add( + self, + run, + attempt=1, + number=128, + head=HEAD, + state="pending", + context=CHECK_NAME, + digest="none", + writes=None, + actor="github-actions[bot]", + ): + writes = writes if writes is not None else len(self.statuses) + 1 + status = { + "id": len(self.statuses) + 1, + "context": context, + "state": state, + "head_sha": head, + "creator": {"login": actor}, + "target_url": f"https://github.com/org/repo/actions/runs/{run}/attempts/{attempt}" + f"#ai-disposition:{number}:{writes}:{digest}", + "description": "Fixture", } - self.checks[check["id"]] = check - return copy.deepcopy(check) + self.statuses.append(status) + return copy.deepcopy(status) def request(self, method, path, body=None): if method == "GET" and "/pulls/" in path: - return {"state": "open", "head": {"sha": HEAD}} - if method == "POST": - check = self.add(0) - self.checks[check["id"]].update(copy.deepcopy(body)) - return copy.deepcopy(self.checks[check["id"]]) - if method == "GET" and "/check-runs/" in path: - return copy.deepcopy(self.checks[int(path.rsplit("/", 1)[1])]) - if method == "GET": + return pr_metadata(number=128) + if method == "POST" and "/statuses/" in path: + assert set(body) == {"context", "state", "target_url", "description"} + status = { + "id": len(self.statuses) + 1, + "creator": {"login": "github-actions[bot]"}, + "head_sha": path.rsplit("/", 1)[-1], + **copy.deepcopy(body), + } + self.statuses.append(status) + return copy.deepcopy(status) + if method == "GET" and "/commits/" in path and "/status?" in path: + head = path.split("/commits/", 1)[1].split("/", 1)[0] + latest = {} + for status in reversed(self.statuses): + if status["head_sha"] == head: + latest.setdefault(status["context"].lower(), status) query = parse_qs(urlsplit(path).query) - runs = [ - c - for c in self.checks.values() - if c["name"] == query["check_name"][0] and c["head_sha"] in path - ] start = (int(query["page"][0]) - 1) * 100 - return {"check_runs": copy.deepcopy(runs[start : start + 100])} - if method == "PATCH": - check = self.checks[int(path.rsplit("/", 1)[1])] - check.update(copy.deepcopy(body)) - # GitHub retains a stored conclusion unless it is explicitly cleared. - if check.get("conclusion") is not None: - check["status"] = "completed" - return copy.deepcopy(check) + return {"statuses": copy.deepcopy(list(latest.values())[start : start + 100])} raise AssertionError(f"Unexpected API call: {method} {path}") - def gate(self): - return [c for c in self.checks.values() if c["name"] == CHECK_NAME] + def gate(self, head=HEAD): + return [ + status + for status in self.pages(f"/repos/org/repo/commits/{head}/status", "statuses") + if status["context"].lower() == CHECK_NAME.lower() + ] + +class LatestStatusTests(unittest.TestCase): + def setUp(self): + self.environment = patch.dict( + "os.environ", {"GITHUB_STEP_SUMMARY": "", "AI_REVIEW_CHECKS_FILE": ""} + ) + self.environment.start() + self.addCleanup(self.environment.stop) -class LatestCheckTests(unittest.TestCase): - def test_twenty_serial_evaluations_reuse_one_check_and_publish_latest_result(self): - api = CheckStore() + def test_twenty_evaluations_keep_one_context_and_enter_real_pending_every_time(self): + api = StatusStore() ready = fixture("Disposition: Invalid\nReason: Test") - with patch("builtins.print"), patch.dict("os.environ", {"GITHUB_STEP_SUMMARY": ""}): + with patch("builtins.print"): for run in range(1, 21): ok = run % 2 == 0 + + def read(api_arg, repository, number, ok=ok): + self.assertEqual(api.gate()[0]["state"], "pending") + return ready if ok else fixture() + with ( patch.dict( "os.environ", {"GITHUB_RUN_ID": str(run), "GITHUB_RUN_ATTEMPT": "1"} ), - patch( - "scripts.check_ai_review_disposition.snapshot", - return_value=ready if ok else fixture(), - ), + patch("scripts.check_ai_review_disposition.snapshot", side_effect=read), ): self.assertEqual(check_pr(api, "org/repo", 128, {BOT}), ok) - self.assertEqual(len(api.checks), 1) - self.assertEqual(api.checks[1]["conclusion"], "success" if ok else "failure") - self.assertEqual(api.checks[1]["external_id"], "ai-review-disposition:128:20:1") - - def test_reopening_a_success_blocks_without_creating_history(self): - api = CheckStore() - check = register_check(api, "org/repo", 128, HEAD, (1, 1)) - api.checks[check["id"]].update(status="completed", conclusion="success") - newer = register_check(api, "org/repo", 128, HEAD, (2, 1)) - self.assertEqual(check["id"], newer["id"]) - self.assertEqual(newer["status"], "completed") - self.assertEqual(newer["conclusion"], "failure") - self.assertEqual(newer["output"]["title"], "Checking") - self.assertRegex(newer["completed_at"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") - self.assertFalse(current_check(api, "org/repo", 128, HEAD, check)) - self.assertTrue(current_check(api, "org/repo", 128, HEAD, newer)) + self.assertEqual(len(api.gate()), 1) + self.assertEqual(api.gate()[0]["state"], "success" if ok else "failure") + self.assertEqual(len(api.statuses), 40) + self.assertEqual([item["state"] for item in api.statuses[::2]], ["pending"] * 20) + + def test_success_can_return_to_pending_without_a_new_visible_context(self): + api = StatusStore() + old = api.add(1, state="success") + newer = register_status(api, "org/repo", 128, HEAD, (2, 1)) + self.assertEqual(newer["state"], "pending") + self.assertEqual(len(api.gate()), 1) + self.assertFalse(current_status(api, "org/repo", 128, HEAD, old)) + self.assertTrue(current_status(api, "org/repo", 128, HEAD, newer)) def test_delayed_old_registration_and_rerun_cannot_take_over(self): - api = CheckStore() - check = register_check(api, "org/repo", 128, HEAD, (20, 1)) - self.assertIsNone(register_check(api, "org/repo", 128, HEAD, (19, 99))) - newer = register_check(api, "org/repo", 128, HEAD, (20, 2)) - self.assertEqual(newer["id"], check["id"]) - self.assertFalse(current_check(api, "org/repo", 128, HEAD, check)) - self.assertIsNone(register_check(api, "org/repo", 128, HEAD, (20, 1))) - self.assertEqual(len(api.checks), 1) - - def test_recovery_workflow_uses_global_run_id_instead_of_local_run_number(self): - api = CheckStore() - register_check(api, "org/repo", 128, HEAD, (100, 1)) + api = StatusStore() + old = register_status(api, "org/repo", 128, HEAD, (20, 1)) + self.assertIsNone(register_status(api, "org/repo", 128, HEAD, (19, 99))) + newer = register_status(api, "org/repo", 128, HEAD, (20, 2)) + self.assertFalse(current_status(api, "org/repo", 128, HEAD, old)) + self.assertTrue(current_status(api, "org/repo", 128, HEAD, newer)) + self.assertIsNone(register_status(api, "org/repo", 128, HEAD, (20, 1))) + self.assertEqual(len(api.statuses), 2) + + def test_recovery_uses_global_run_id_instead_of_local_run_number(self): + api = StatusStore() + api.add(100) with patch.dict( "os.environ", {"GITHUB_RUN_ID": "101", "GITHUB_RUN_NUMBER": "1", "GITHUB_RUN_ATTEMPT": "1"}, ): - newer = register_check(api, "org/repo", 128, HEAD) - self.assertEqual(newer["external_id"], "ai-review-disposition:128:101:1") - self.assertEqual(len(api.checks), 1) + newer = register_status(api, "org/repo", 128, HEAD) + self.assertIn("/runs/101/attempts/1", newer["target_url"]) + self.assertEqual(len(api.gate()), 1) - def test_existing_history_other_apps_prs_and_ci_are_untouched(self): - api = CheckStore() + def test_unrelated_contexts_and_existing_history_are_untouched(self): + api = StatusStore() for run in range(1, 102): - newest = api.add(run) - api.add(999, app=2) - api.add(999, number=129) - ci = api.add(999) - api.checks[ci["id"]]["name"] = "Unrelated CI" - old = api.add(0) - api.checks[old["id"]]["name"] += " (superseded #104)" - before = copy.deepcopy(api.checks) - check = register_check(api, "org/repo", 128, HEAD, (102, 1)) - self.assertEqual(check["id"], newest["id"]) - self.assertEqual(len(api.checks), len(before)) - for key in before: - if key != newest["id"]: - self.assertEqual(api.checks[key], before[key]) - - def test_new_head_gets_its_own_check(self): - api = CheckStore() - first = register_check(api, "org/repo", 128, HEAD, (1, 1)) + api.add(run) + api.add(999, context="Unrelated CI", actor="another-service") + before = copy.deepcopy(api.statuses) + register_status(api, "org/repo", 128, HEAD, (102, 1)) + self.assertEqual(api.statuses[:-1], before) + self.assertEqual(len(api.gate()), 1) + + def test_new_head_gets_one_independent_context(self): + api = StatusStore() + register_status(api, "org/repo", 128, HEAD, (1, 1)) other_head = "c" * 40 - second = register_check(api, "org/repo", 128, other_head, (2, 1)) - self.assertNotEqual(first["id"], second["id"]) - self.assertEqual(len(api.checks), 2) - self.assertEqual( - register_check(api, "org/repo", 128, other_head, (3, 1))["id"], second["id"] - ) - - def test_legacy_check_without_external_id_is_reused(self): - api = CheckStore() - old = api.add(0) - api.checks[old["id"]]["external_id"] = "" - self.assertEqual( - register_check(api, "org/repo", 128, HEAD, (1, 1))["id"], old["id"] - ) - self.assertEqual(len(api.checks), 1) - - def test_queued_worker_uses_live_head_instead_of_router_snapshot(self): - api = CheckStore() + register_status(api, "org/repo", 128, other_head, (2, 1)) + register_status(api, "org/repo", 128, other_head, (3, 1)) + self.assertEqual(len(api.gate()), 1) + self.assertEqual(len(api.gate(other_head)), 1) + + def test_unknown_writer_or_shared_pr_head_is_not_silently_adopted(self): + for options in ({"actor": "stranger"}, {"number": 129}): + api = StatusStore() + api.add(1, **options) + with self.subTest(options=options), self.assertRaises(ValueError): + register_status(api, "org/repo", 128, HEAD, (2, 1)) + if "number" in options: + self.assertEqual(api.gate()[0]["state"], "failure") + else: + self.assertEqual(len(api.statuses), 1) + + def test_queued_worker_uses_live_head_instead_of_routing_snapshot(self): + api = StatusStore() with ( patch("scripts.check_ai_review_disposition.snapshot", return_value=fixture()), patch("builtins.print"), @@ -1201,9 +1205,9 @@ def run_main(self, *arguments, passed=True, numbers=None, results=None): ), patch("scripts.check_ai_review_disposition.GitHub") as client, patch( - "scripts.check_ai_review_disposition.register_check", return_value={"id": 99} + "scripts.check_ai_review_disposition.register_status", return_value={"id": 99} ), - patch("scripts.check_ai_review_disposition.current_check", return_value=True), + patch("scripts.check_ai_review_disposition.current_status", return_value=True), patch( "scripts.check_ai_review_disposition.check_pr", return_value=passed ) as check, @@ -1211,29 +1215,32 @@ def run_main(self, *arguments, passed=True, numbers=None, results=None): ): if numbers is not None: client.return_value.pages.return_value = [ - {"number": n, "head": {"sha": HEAD}} for n in numbers + {"number": n, "state": "open", "head": {"sha": HEAD}} for n in numbers ] if results is not None: check.side_effect = results return main(), client, check def test_sweep_only_routes_all_targets_without_writing_checks(self): - api = CheckStore() + api = StatusStore() prs = [{"number": n, "state": "open", "head": {"sha": HEAD}} for n in [24, 7, 24]] with patch.object(api, "pages", return_value=prs): self.assertEqual( prepare_targets(api, "org/repo", all_open=True), [{"number": n, "head": HEAD} for n in [7, 24]], ) - self.assertEqual(api.checks, {}) + self.assertEqual(api.statuses, []) def test_empty_sweep_routes_no_workers(self): with patch.object(GitHub, "pages", return_value=[]): self.assertEqual(prepare_targets(GitHub("token"), "org/repo", all_open=True), []) - def test_direct_sweep_is_rejected_to_prevent_bypassing_worker_queue(self): - with self.assertRaises(SystemExit): - self.run_main("--all-open-prs") + def test_direct_sweep_checks_every_target_even_after_a_failure(self): + code, _, check = self.run_main( + "--all-open-prs", numbers=[1, 2], results=[False, True] + ) + self.assertEqual(code, 1) + self.assertEqual(check.call_count, 2) def test_open_pr_enumeration_reads_all_pages_without_issue_backlinks(self): api = GitHub("test-token") @@ -1270,11 +1277,12 @@ def test_missing_or_invalid_pr_never_defaults_to_a_repository_scan(self): self.run_main(*arguments) self.assertEqual(error.exception.code, 2) - def test_empty_or_invalid_bot_configuration_is_an_error(self): - for bots in ("", ",", "reviewer+bot"): - with self.subTest(bots=bots), self.assertRaises(SystemExit) as error: - self.run_main("--pr-number", "313", "--bots", bots) - self.assertEqual(error.exception.code, 2) + def test_invalid_bot_configuration_is_published_as_failure(self): + for bots in (set(), {"reviewer+bot"}): + api = StatusStore() + with self.subTest(bots=bots), patch("builtins.print"): + self.assertFalse(check_pr(api, "org/repo", 128, bots)) + self.assertEqual([item["state"] for item in api.statuses], ["pending", "failure"]) def test_closed_pr_does_not_create_a_check(self): api = GitHub("test-token") diff --git a/scripts/tests/test_ai_review_reliability.py b/scripts/tests/test_ai_review_reliability.py index 7690800..f71cd63 100644 --- a/scripts/tests/test_ai_review_reliability.py +++ b/scripts/tests/test_ai_review_reliability.py @@ -228,7 +228,7 @@ def test_compare_explicitly_paginates_beyond_250(self): self.assertIn("per_page=100&page=4", request.call_args.args[1]) -class RecoveryStore(fixtures.CheckStore): +class RecoveryStore(fixtures.StatusStore): def __init__(self): super().__init__() self.source = { @@ -240,11 +240,6 @@ def __init__(self): "run_attempt": 1, } - def add(self, *args, **kwargs): - check = super().add(*args, **kwargs) - self.checks[check["id"]]["app"]["slug"] = "github-actions" - return copy.deepcopy(self.checks[check["id"]]) - def request(self, method, path, body=None): if method == "GET" and "/actions/runs/" in path: return copy.deepcopy(self.source) @@ -256,7 +251,13 @@ def request(self, method, path, body=None): class RecoveryTests(unittest.TestCase): def setUp(self): self.environment = patch.dict( - os.environ, {"AI_REVIEW_CHECKS_FILE": "", "GITHUB_STEP_SUMMARY": ""} + os.environ, + { + "AI_REVIEW_CHECKS_FILE": "", + "GITHUB_STEP_SUMMARY": "", + "GITHUB_RUN_ID": "100", + "GITHUB_RUN_ATTEMPT": "1", + }, ) self.environment.start() self.addCleanup(self.environment.stop) @@ -264,7 +265,7 @@ def setUp(self): def test_first_metadata_read_failure_revokes_old_success_using_trusted_head(self): api = RecoveryStore() old = api.add(1) - api.checks[old["id"]].update(status="completed", conclusion="success") + api.statuses[old["id"] - 1].update(state="success") request = api.request def fail_metadata(method, path, body=None): @@ -281,39 +282,39 @@ def fail_metadata(method, path, body=None): self.assertFalse( checker.check_pr(api, "org/repo", 128, {fixtures.BOT}, fixtures.HEAD) ) - self.assertEqual(len(api.checks), 1) - self.assertEqual(api.gate()[0]["conclusion"], "failure") + self.assertEqual(len(api.gate()), 1) + self.assertEqual(api.gate()[0]["state"], "failure") def test_cleanup_marks_same_check_failed_without_new_history(self): api = RecoveryStore() old = api.add(2) self.assertTrue(checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1))) - self.assertEqual(len(api.checks), 1) - self.assertEqual(api.gate()[0]["id"], old["id"]) - self.assertEqual(api.gate()[0]["conclusion"], "failure") - before = copy.deepcopy(api.checks) + self.assertEqual(len(api.gate()), 1) + self.assertNotEqual(api.gate()[0]["id"], old["id"]) + self.assertEqual(api.gate()[0]["state"], "failure") + before = copy.deepcopy(api.statuses) checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) - self.assertEqual(api.checks, before) + self.assertEqual(api.statuses, before) def test_cleanup_closes_temporary_failure_when_reusing_completed_check(self): api = RecoveryStore() old = api.add(1) - api.checks[old["id"]].update(status="completed", conclusion="success") - check = checker.register_check(api, "org/repo", 128, fixtures.HEAD, (2, 1)) - self.assertEqual(check["conclusion"], "failure") - self.assertEqual(check["output"]["title"], "Checking") + api.statuses[old["id"] - 1].update(state="success") + check = checker.register_status(api, "org/repo", 128, fixtures.HEAD, (2, 1)) + self.assertEqual(check["state"], "pending") + self.assertEqual(check["description"], "Checking PR #128") checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) - self.assertEqual(len(api.checks), 1) - self.assertEqual(api.gate()[0]["output"]["title"], "Evaluation interrupted") + self.assertEqual(len(api.gate()), 1) + self.assertIn("Evaluation interrupted", api.gate()[0]["description"]) def test_reused_check_stays_blocked_when_final_publication_fails(self): api = RecoveryStore() old = api.add(1) - api.checks[old["id"]].update(status="completed", conclusion="success") + api.statuses[old["id"] - 1].update(state="success") request = api.request def fail_success(method, path, body=None): - if method == "PATCH" and (body or {}).get("conclusion") == "success": + if method == "POST" and (body or {}).get("state") == "success": raise RuntimeError("write failed") return request(method, path, body) @@ -328,30 +329,28 @@ def fail_success(method, path, body=None): patch("sys.stderr", new_callable=io.StringIO), ): self.assertFalse(checker.check_pr(api, "org/repo", 128, {fixtures.BOT})) - self.assertEqual(len(api.checks), 1) - self.assertEqual(api.gate()[0]["conclusion"], "failure") - self.assertEqual(api.gate()[0]["output"]["title"], "Checking") + self.assertEqual(len(api.gate()), 1) + self.assertEqual(api.gate()[0]["state"], "pending") + self.assertEqual(api.gate()[0]["description"], "Checking PR #128") def test_old_cleanup_cannot_replace_newer_success_or_pending(self): - for status in ("completed", "in_progress"): + for status in ("success", "pending"): api = RecoveryStore() newest = api.add(3) - api.checks[newest["id"]].update( - status=status, conclusion="success" if status == "completed" else None - ) - before = copy.deepcopy(api.checks) + api.statuses[newest["id"] - 1].update(state=status) + before = copy.deepcopy(api.statuses) checker.finish_pending(api, "org/repo", 128, fixtures.HEAD, (2, 1)) - self.assertEqual(api.checks, before) + self.assertEqual(api.statuses, before) def test_recovery_routes_to_workers_without_writing_checks(self): api = RecoveryStore() api.add(1) - before = copy.deepcopy(api.checks) + before = copy.deepcopy(api.statuses) self.assertEqual( checker.prepare_targets(api, "org/repo", recover=999), [{"number": 128, "head": fixtures.HEAD}], ) - self.assertEqual(api.checks, before) + self.assertEqual(api.statuses, before) def test_recovery_rejects_unrelated_workflows_and_invalid_routing(self): for field, value in ( @@ -362,14 +361,14 @@ def test_recovery_rejects_unrelated_workflows_and_invalid_routing(self): api.source[field] = value with self.subTest(field=field), self.assertRaises(ValueError): checker.recovery_targets(api, "org/repo", 999) - self.assertEqual(api.checks, {}) + self.assertEqual(api.statuses, []) def test_running_rerun_or_success_routes_no_recovery(self): for changes in ({"status": "in_progress"}, {"conclusion": "success"}): api = RecoveryStore() api.source.update(changes) self.assertEqual(checker.recovery_targets(api, "org/repo", 999), []) - self.assertEqual(api.checks, {}) + self.assertEqual(api.statuses, []) def test_routing_does_not_need_bot_configuration(self): with ( @@ -408,7 +407,7 @@ def test_sweep_recovery_routes_all_open_targets(self): ] with patch.object(api, "pages", return_value=prs): self.assertEqual(len(checker.prepare_targets(api, "org/repo", recover=999)), 4) - self.assertEqual(api.checks, {}) + self.assertEqual(api.statuses, []) def test_local_journal_cleanup_closes_interrupted_checks(self): api = RecoveryStore() @@ -417,9 +416,9 @@ def test_local_journal_cleanup_closes_interrupted_checks(self): with patch.dict( os.environ, {"AI_REVIEW_CHECKS_FILE": path, "GITHUB_RUN_NUMBER": "2"} ): - checker.register_check(api, "org/repo", 128, fixtures.HEAD) + checker.register_status(api, "org/repo", 128, fixtures.HEAD) self.assertTrue(checker.cleanup_file(api, "org/repo", path)) - self.assertEqual(api.gate()[0]["conclusion"], "failure") + self.assertEqual(api.gate()[0]["state"], "failure") def test_final_check_list_or_patch_failure_reports_recovery_instead_of_success(self): for fail_list in (False, True): @@ -427,7 +426,7 @@ def test_final_check_list_or_patch_failure_reports_recovery_instead_of_success(s request = api.request def fail_publish(method, path, body=None, request=request): - if method == "PATCH" and (body or {}).get("conclusion") == "success": + if method == "POST" and (body or {}).get("state") == "success": raise RuntimeError("write failed") return request(method, path, body) @@ -441,7 +440,7 @@ def fail_publish(method, path, body=None, request=request): ), patch.object( checker, - "current_check", + "current_status", side_effect=[True, RuntimeError("list failed")] if fail_list else [True, True], @@ -449,9 +448,9 @@ def fail_publish(method, path, body=None, request=request): patch("sys.stderr", new_callable=io.StringIO) as stderr, ): self.assertFalse(checker.check_pr(api, "org/repo", 128, {fixtures.BOT})) - self.assertIn("in_progress", stderr.getvalue()) + self.assertIn("pending", stderr.getvalue()) self.assertIn("dispatch", stderr.getvalue()) - self.assertEqual(api.gate()[0]["status"], "in_progress") + self.assertEqual(api.gate()[0]["state"], "pending") def test_routing_outputs_matrix_for_worker_queue_without_check_writes(self): api = RecoveryStore() @@ -479,26 +478,20 @@ def test_routing_outputs_matrix_for_worker_queue_without_check_writes(self): self.assertEqual(checker.main(), 0) self.assertIn('"include":[{"number":128,"head":', output.read_text()) self.assertIn("has-targets=true", output.read_text()) - self.assertEqual(api.checks, {}) + self.assertEqual(api.statuses, []) - def test_shared_workflow_uses_one_worker_queue_for_all_entry_points(self): + def test_shared_workflow_uses_one_background_worker_queue_for_all_entry_points(self): workflow = ( Path(__file__).resolve().parents[2] / ".github/workflows/reusable-ai-review-disposition.yml" ).read_text() - self.assertIn( - "group: ai-review-disposition-${{ github.repository }}-${{ matrix.number }}", - workflow, - ) + self.assertIn("group: ai-review-disposition-${{ github.repository }}", workflow) self.assertIn("cancel-in-progress: false", workflow) - self.assertIn("fail-fast: false", workflow) - self.assertIn("max-parallel: 4", workflow) - self.assertIn("--prepare-targets --all-open-prs", workflow) - self.assertIn("--prepare-targets --recover-run", workflow) - self.assertNotIn( - '--recover-run "$RECOVER_RUN_ID"\n elif', - workflow.split(" disposition:")[1], - ) + self.assertNotIn("matrix:", workflow) + self.assertIn("args+=(--all-open-prs)", workflow) + self.assertIn('args+=(--recover-run "$RECOVER_RUN_ID")', workflow) + self.assertIn("statuses: write", workflow) + self.assertNotIn("checks: write", workflow) if __name__ == "__main__": diff --git a/scripts/tests/test_ai_review_status.py b/scripts/tests/test_ai_review_status.py new file mode 100644 index 0000000..7d35ffd --- /dev/null +++ b/scripts/tests/test_ai_review_status.py @@ -0,0 +1,202 @@ +import copy +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +from scripts import check_ai_review_disposition as checker +from scripts.tests import test_ai_review_disposition as fixtures + + +class EvidenceStore(fixtures.StatusStore): + def __init__(self): + super().__init__() + self.issue = { + "state": "open", + "repository_url": "https://api.github.com/repos/org/repo", + } + self.permission = "write" + + def request(self, method, path, body=None): + if method == "GET" and "/issues/" in path: + return copy.deepcopy(self.issue) + if method == "GET" and "/collaborators/" in path: + return {"permission": self.permission} + return super().request(method, path, body) + + +class StatusPollingTests(unittest.TestCase): + def setUp(self): + self.api = EvidenceStore() + self.run = 0 + self.ready = fixtures.fixture("Disposition: Invalid\nReason: Covered upstream") + self.environment = patch.dict( + os.environ, + { + "AI_REVIEW_CHECKS_FILE": "", + "GITHUB_STEP_SUMMARY": "", + "GITHUB_RUN_ATTEMPT": "1", + }, + ) + self.environment.start() + self.addCleanup(self.environment.stop) + + def invoke(self, data=None, poll=False, bots=None): + self.run += 1 + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": str(self.run)}), + patch.object(checker, "snapshot", return_value=data or self.ready), + patch("builtins.print"), + ): + return checker.check_pr( + self.api, + "org/repo", + 128, + bots or {fixtures.BOT}, + only_changed=poll, + ) + + def assert_states(self, states): + self.assertEqual([item["state"] for item in self.api.statuses], states) + self.assertEqual(len(self.api.gate()), 1) + self.assertEqual(self.api.gate()[0]["context"], checker.CHECK_NAME) + + def test_unchanged_polls_do_not_consume_status_writes(self): + for data, expected in ((self.ready, True), (fixtures.fixture(), False)): + with self.subTest(expected=expected): + self.api = EvidenceStore() + self.assertEqual(self.invoke(data), expected) + for _ in range(20): + self.assertEqual(self.invoke(copy.deepcopy(data), poll=True), expected) + self.assert_states(["pending", "success" if expected else "failure"]) + + def test_explicit_rechecks_always_revoke_success_with_pending(self): + self.assertTrue(self.invoke()) + for _ in range(3): + self.assertTrue(self.invoke()) + self.assert_states(["pending", "success"] * 4) + + def test_new_finding_invalidates_the_same_visible_result(self): + self.assertTrue(self.invoke()) + changed = copy.deepcopy(self.ready) + changed["threads"].append(fixtures.fixture()["threads"][0]) + self.assertFalse(self.invoke(changed, poll=True)) + self.assert_states(["pending", "success", "pending", "failure"]) + + def test_tracking_issue_change_is_detected_without_a_pr_comment_change(self): + data = fixtures.fixture( + "Disposition: Deferred\nReason: Follow up\n" + "Tracking: https://github.com/org/repo/issues/42" + ) + self.assertTrue(self.invoke(data)) + self.api.issue["state"] = "closed" + self.assertFalse(self.invoke(data, poll=True)) + self.assertFalse(self.invoke(data, poll=True)) + self.assert_states(["pending", "success", "pending", "failure"]) + + def test_revoked_human_permission_invalidates_an_unchanged_reply(self): + data = copy.deepcopy(self.ready) + data["threads"][0]["comments"][-1]["author"]["login"] = "maintainer" + self.assertTrue(self.invoke(data)) + self.api.permission = "read" + self.assertFalse(self.invoke(data, poll=True)) + self.assert_states(["pending", "success", "pending", "failure"]) + + def test_requiring_another_bot_invalidates_old_success(self): + self.assertTrue(self.invoke()) + self.assertFalse(self.invoke(poll=True, bots={fixtures.BOT, "infiscale-bot"})) + self.assert_states(["pending", "success", "pending", "failure"]) + + def test_both_configured_bots_complete_then_a_new_round_blocks(self): + data = copy.deepcopy(self.ready) + data["comments"] = [fixtures.comment(fixtures.INFISCALE_COMPLETE, "infiscale-bot")] + bots = {fixtures.BOT, "infiscale-bot"} + self.assertTrue(self.invoke(data, bots=bots)) + data["comments"].append( + fixtures.comment( + fixtures.INFISCALE_START, + "infiscale-bot", + "2026-10-10T00:00:00Z", + ) + ) + self.assertFalse(self.invoke(data, poll=True, bots=bots)) + self.assert_states(["pending", "success", "pending", "failure"]) + + def test_poll_read_failure_revokes_success_instead_of_skipping(self): + self.assertTrue(self.invoke()) + with patch.object(checker, "snapshot", side_effect=RuntimeError("read failed")): + # invoke's snapshot patch is intentionally not used for this failing read. + with patch.dict(os.environ, {"GITHUB_RUN_ID": "2"}), patch("builtins.print"): + self.assertFalse( + checker.check_pr( + self.api, + "org/repo", + 128, + {fixtures.BOT}, + only_changed=True, + ) + ) + self.assert_states(["pending", "success", "pending", "failure"]) + + def test_interrupted_pending_result_is_retried_even_when_evidence_is_unchanged(self): + self.api.add(0) + self.assertTrue(self.invoke(poll=True)) + self.assert_states(["pending", "pending", "success"]) + + def test_retry_after_temporary_read_failure_can_pass(self): + self.api.add(0, state="failure") + self.assertTrue(self.invoke(poll=True)) + self.assert_states(["failure", "pending", "success"]) + + def test_status_limit_cannot_leave_an_irreversible_success(self): + self.api.add(0, state="success", writes=997) + self.assertFalse(self.invoke()) + self.assert_states(["success", "pending", "failure"]) + self.assertIn("push a new commit", self.api.gate()[0]["description"]) + + def test_approaching_limit_replaces_success_with_failure_before_refusing(self): + self.api.add(0, state="success", writes=998) + with self.assertRaises(RuntimeError): + self.invoke() + self.assert_states(["success", "failure"]) + self.assertIn("push a new commit", self.api.gate()[0]["description"]) + + def test_foreign_target_url_is_not_trusted_even_with_the_bot_login(self): + status = self.api.add(0, state="success") + status["target_url"] = "https://example.test/runs/1" + with self.assertRaises(ValueError): + checker.status_identity(status, "org/repo") + + def test_combined_context_read_paginates_without_scanning_status_history(self): + self.api.add(1) + for n in range(101): + self.api.add(2, context=f"other-{n}") + self.assertEqual( + checker.latest_status(self.api, "org/repo", fixtures.HEAD)["id"], 1 + ) + + +class SingleRowWorkflowTests(unittest.TestCase): + def test_caller_and_recovery_never_use_pr_associated_triggers(self): + root = Path(__file__).resolve().parents[2] + for filename in ("ai-review-disposition.yml", "ai-review-recovery.yml"): + with self.subTest(filename=filename): + workflow = (root / "docs/examples" / filename).read_text(encoding="utf-8") + triggers = workflow.split("\non:\n", 1)[1].split("\npermissions:\n", 1)[0] + self.assertNotRegex( + triggers, + r"(?m)^ (push|pull_request(?:_target|_review(?:_comment)?)?" + r"|deployment(?:_status)?):", + ) + self.assertIn("statuses: write", workflow) + self.assertNotIn("checks: write", workflow) + caller = (root / "docs/examples/ai-review-disposition.yml").read_text( + encoding="utf-8" + ) + self.assertIn("schedule:", caller) + self.assertIn("workflows: [CI]", caller) + self.assertFalse((root / "docs/examples/ai-review-events.yml").exists()) + + +if __name__ == "__main__": + unittest.main() From 74a428e5f87d732b5e8c509e14985e6feebe0692 Mon Sep 17 00:00:00 2001 From: xiaoyu <2455995107@qq.com> Date: Wed, 28 Oct 2026 19:57:57 +0800 Subject: [PATCH 20/21] fix[ci]: read complete status records for ownership checks Problem: - GitHub combined statuses omit creator, preventing repeated disposition updates. Solution: - Read newest-first full status records and stop at the latest matching context. - Model the distinct list and combined response schemas in the test fixture. Test: - Live Actions API probe reproduced the missing creator field. - 143 unit tests passed, including ownership and bounded history reads. - Ruff lint/format and git diff --check passed. JIRA: PDIST-770 --- scripts/check_ai_review_disposition.py | 17 ++++++++---- scripts/tests/test_ai_review_disposition.py | 29 ++++++++++++++------- scripts/tests/test_ai_review_status.py | 17 +++++++++++- 3 files changed, 48 insertions(+), 15 deletions(-) diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index f475731..73667c7 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -402,11 +402,18 @@ def summary(number, head, result): def latest_status(api, repository, head): - """The combined endpoint returns one latest status per context, not its history.""" - statuses = api.pages(f"/repos/{repository}/commits/{head}/status", "statuses") - return next( - (item for item in statuses if item["context"].lower() == CHECK_NAME.lower()), None - ) + """Read newest-first statuses, stopping at our context; combined omits creator.""" + page = 1 + while True: + statuses = api.request( + "GET", f"/repos/{repository}/commits/{head}/statuses?per_page=100&page={page}" + ) + for status in statuses: + if status["context"].lower() == CHECK_NAME.lower(): + return status + if len(statuses) < 100: + return None + page += 1 def status_identity(status, repository): diff --git a/scripts/tests/test_ai_review_disposition.py b/scripts/tests/test_ai_review_disposition.py index 2d8661c..049fa36 100644 --- a/scripts/tests/test_ai_review_disposition.py +++ b/scripts/tests/test_ai_review_disposition.py @@ -796,15 +796,15 @@ def test_commit_link_does_not_add_api_requests(self): ) calls, ok = self.run_check([data, copy.deepcopy(data)]) self.assertTrue(ok) - self.assertEqual(len(calls), 3) + self.assertEqual(len(calls), 4) self.assertEqual(calls[-1].args[2]["state"], "success") def test_check_is_written_to_pr_head_not_event_sha(self): data = fixture("Disposition: Invalid\nReason: False positive") calls, ok = self.run_check([data, copy.deepcopy(data)]) self.assertTrue(ok) - self.assertEqual(calls[1].args[1].rsplit("/", 1)[-1], HEAD) - self.assertEqual(calls[1].args[2]["context"], CHECK_NAME) + self.assertEqual(calls[2].args[1].rsplit("/", 1)[-1], HEAD) + self.assertEqual(calls[2].args[2]["context"], CHECK_NAME) self.assertEqual(calls[-1].args[2]["state"], "success") def test_new_finding_during_read_prevents_success(self): @@ -854,7 +854,7 @@ def test_deferred_requires_a_successful_open_issue_lookup(self): ) calls, ok = self.run_check([data, copy.deepcopy(data)], {"state": "open"}) self.assertTrue(ok) - self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) + self.assertEqual(calls[3].args, ("GET", "/repos/org/repo/issues/42")) self.assertEqual(calls[-1].args[2]["state"], "success") def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): @@ -867,7 +867,7 @@ def test_missing_unreadable_or_failed_issue_lookup_blocks_deferred(self): error = HTTPError("https://api.github.com/issue", status, "error", {}, None) calls, ok = self.run_check([data], error) self.assertFalse(ok) - self.assertEqual(calls[2].args, ("GET", "/repos/org/repo/issues/42")) + self.assertEqual(calls[3].args, ("GET", "/repos/org/repo/issues/42")) self.assertEqual(calls[-1].args[2]["state"], "failure") def test_deleted_issue_reports_invalid_tracking_instead_of_api_failure(self): @@ -899,8 +899,8 @@ def test_only_canonical_github_issue_urls_are_queried(self): data = fixture(f"Disposition: Deferred\nReason: Follow up\nTracking: {url}") calls, ok = self.run_check([data]) self.assertFalse(ok) - # Only PR metadata, Check creation, and Check completion; no issue request. - self.assertEqual(len(calls), 3) + # PR metadata, status lookup, pending and final publication; no Issue lookup. + self.assertEqual(len(calls), 4) self.assertEqual(calls[-1].args[2]["state"], "failure") def test_multiple_findings_share_one_issue_lookup(self): @@ -992,7 +992,7 @@ def test_permission_lookup_errors_block_and_encode_the_login(self): calls, ok = self.run_check([data], error) self.assertFalse(ok) self.assertEqual( - calls[2].args, ("GET", "/repos/org/repo/collaborators/user%2Fname/permission") + calls[3].args, ("GET", "/repos/org/repo/collaborators/user%2Fname/permission") ) self.assertEqual(calls[-1].args[2]["state"], "failure") @@ -1004,6 +1004,8 @@ def run_check(self, snapshots, lookup=None): def respond(method, path, body=None): if (method, path) == ("GET", "/repos/org/repo/pulls/128"): return pr + if method == "GET" and "/statuses?" in path: + return [] if method == "POST": return {"id": 99, "creator": {"login": "github-actions[bot]"}, **body} if method == "PATCH": @@ -1076,6 +1078,12 @@ def request(self, method, path, body=None): } self.statuses.append(status) return copy.deepcopy(status) + if method == "GET" and "/commits/" in path and "/statuses?" in path: + head = path.split("/commits/", 1)[1].split("/", 1)[0] + statuses = [item for item in reversed(self.statuses) if item["head_sha"] == head] + query = parse_qs(urlsplit(path).query) + start = (int(query["page"][0]) - 1) * 100 + return copy.deepcopy(statuses[start : start + 100]) if method == "GET" and "/commits/" in path and "/status?" in path: head = path.split("/commits/", 1)[1].split("/", 1)[0] latest = {} @@ -1084,7 +1092,10 @@ def request(self, method, path, body=None): latest.setdefault(status["context"].lower(), status) query = parse_qs(urlsplit(path).query) start = (int(query["page"][0]) - 1) * 100 - return {"statuses": copy.deepcopy(list(latest.values())[start : start + 100])} + statuses = copy.deepcopy(list(latest.values())[start : start + 100]) + for status in statuses: + status.pop("creator", None) + return {"statuses": statuses} raise AssertionError(f"Unexpected API call: {method} {path}") def gate(self, head=HEAD): diff --git a/scripts/tests/test_ai_review_status.py b/scripts/tests/test_ai_review_status.py index 7d35ffd..0c9556f 100644 --- a/scripts/tests/test_ai_review_status.py +++ b/scripts/tests/test_ai_review_status.py @@ -167,7 +167,7 @@ def test_foreign_target_url_is_not_trusted_even_with_the_bot_login(self): with self.assertRaises(ValueError): checker.status_identity(status, "org/repo") - def test_combined_context_read_paginates_without_scanning_status_history(self): + def test_status_lookup_paginates_past_other_contexts(self): self.api.add(1) for n in range(101): self.api.add(2, context=f"other-{n}") @@ -175,6 +175,21 @@ def test_combined_context_read_paginates_without_scanning_status_history(self): checker.latest_status(self.api, "org/repo", fixtures.HEAD)["id"], 1 ) + def test_ownership_uses_full_status_records_when_combined_omits_creator(self): + self.api.add(1, state="success") + self.assertNotIn("creator", self.api.gate()[0]) + status = checker.latest_status(self.api, "org/repo", fixtures.HEAD) + self.assertEqual(status["creator"]["login"], "github-actions[bot]") + self.assertEqual(checker.status_identity(status, "org/repo")[:3], (1, 1, 128)) + + def test_latest_context_stops_before_reading_older_history_pages(self): + for n in range(150): + self.api.add(n) + with patch.object(self.api, "request", wraps=self.api.request) as request: + status = checker.latest_status(self.api, "org/repo", fixtures.HEAD) + self.assertEqual(status["id"], 150) + self.assertEqual(request.call_count, 1) + class SingleRowWorkflowTests(unittest.TestCase): def test_caller_and_recovery_never_use_pr_associated_triggers(self): From e774814f6bbe9f520c3abb6e39d0b1b89e82dfa9 Mon Sep 17 00:00:00 2001 From: xiaoyu <2455995107@qq.com> Date: Wed, 28 Oct 2026 20:03:07 +0800 Subject: [PATCH 21/21] fix[ci]: recover execution errors without retrying business failures Problem: - Expected review blocks could cause an unnecessary recovery scan after every poll. Solution: - Report business failures through the single PR status while treating publication as successful execution. - Keep API errors, interrupted verification, and quota exhaustion eligible for recovery. Test: - 146 unit tests passed, including background blocking and execution error cases. - Ruff lint/format, actionlint, and git diff --check passed. - Live API verification of the status lifecycle passed on the prior publisher implementation. JIRA: PDIST-770 --- .../reusable-ai-review-disposition.yml | 2 +- docs/AI_REVIEW_DISPOSITION.md | 2 + scripts/check_ai_review_disposition.py | 17 ++++-- scripts/tests/test_ai_review_status.py | 54 +++++++++++++++++++ 4 files changed, 71 insertions(+), 4 deletions(-) diff --git a/.github/workflows/reusable-ai-review-disposition.yml b/.github/workflows/reusable-ai-review-disposition.yml index 5c67aff..14855c8 100644 --- a/.github/workflows/reusable-ai-review-disposition.yml +++ b/.github/workflows/reusable-ai-review-disposition.yml @@ -81,7 +81,7 @@ jobs: RECOVER_RUN_ID: ${{ inputs.recover-run-id }} ONLY_CHANGED: ${{ inputs.only-changed }} run: | - args=() + args=(--background) if [[ "$ONLY_CHANGED" == "true" ]]; then args+=(--only-changed) fi diff --git a/docs/AI_REVIEW_DISPOSITION.md b/docs/AI_REVIEW_DISPOSITION.md index 9ea5986..39be152 100644 --- a/docs/AI_REVIEW_DISPOSITION.md +++ b/docs/AI_REVIEW_DISPOSITION.md @@ -93,6 +93,8 @@ gh workflow run ai-review-disposition.yml --repo "$GITHUB_REPOSITORY" \ 所有单 PR、全仓和恢复运行共用仓库级 concurrency group,`cancel-in-progress=false`,避免两个入口同时写相同 context。等待中的重复触发可能被最新任务替代,后续定时扫描会重新覆盖全部开放 PR。单次运行串行处理目标,一个 PR 失败后仍继续其余 PR;worker 最长 30 分钟,目标过多时需关注超时和 API 配额。 +后台 worker 使用 `--background`:正常发布的业务 failure(例如等待机器人或缺少回复)由唯一 PR 状态表达,后台运行可成功,避免每次定时扫描又启动一次无意义恢复。读取 / 校验异常、结果发布失败或状态额度耗尽仍使 worker 失败并启动恢复;不能把后台 job 的成功当成 PR 门禁通过。直接运行 CLI 时不加该参数,业务 failure 仍返回非零退出码。 + 显式检查在获取当前 head 后先发布 pending。通过前再次读取完整 PR 快照,清缓存复核人工权限和 Issue 状态,确认结果仍有效。只读 REST / GraphQL 请求的瞬时网络错误、429、500/502/503/504 或带 Retry-After 的 403 最多重试三次;不早于 Retry-After 重试,等待超过 60 秒则中止。状态写入不盲重试。 状态 Details URL 关联实际 run ID / attempt,并携带受控的 PR、写入计数和证据指纹。旧 run 的重跑不能覆盖已登记的新 run;最终发布和 cleanup 先检查当前状态 ID 是否仍属于自己。普通退出通过本机登记日志将自己遗留的 pending 标记为中断 failure;最终写入失败时保留 pending 阻断。取消、硬超时或初始化失败由独立的默认分支恢复入口定位原目标,经过同一个 worker 队列实时重查;恢复不直接写旁路结果。定时扫描也会重试遗留 pending / failure。 diff --git a/scripts/check_ai_review_disposition.py b/scripts/check_ai_review_disposition.py index 73667c7..8f5ade1 100644 --- a/scripts/check_ai_review_disposition.py +++ b/scripts/check_ai_review_disposition.py @@ -603,7 +603,9 @@ def prepare_targets(api, repository, number=None, all_open=False, recover=None): return [targets[number] for number in sorted(targets)] -def check_pr(api, repository, number, bots, head=None, only_changed=False): +def check_pr( + api, repository, number, bots, head=None, only_changed=False, background=False +): try: pr = api.request("GET", f"/repos/{repository}/pulls/{number}") if pr["state"] != "open": @@ -700,7 +702,7 @@ def read_evaluation(): and previous["state"] == ("success" if passed(result) else "failure") and current_status(api, repository, number, head, previous) ): - return passed(result) + return passed(result) or background except Exception as error: preparation_error = error status = register_status(api, repository, number, head) @@ -776,7 +778,9 @@ def read_evaluation(): open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream, ): stream.write(report + "\n\n") - return ok + # A valid blocking business result belongs to the PR status. Only execution + # failures should activate the background workflow's recovery entry point. + return ok or (background and status_identity(final, repository)[4] != "none") def main(): @@ -808,6 +812,11 @@ def main(): action="store_true", help="Poll live evidence without rewriting unchanged terminal results", ) + parser.add_argument( + "--background", + action="store_true", + help="Recover execution errors, not valid blocking business results", + ) args = parser.parse_args() bots = {bot.strip().lower() for bot in args.bots.split(",") if bot.strip()} token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") @@ -840,6 +849,8 @@ def main(): stream.write(f"matrix={matrix}\nhas-targets={'true' if targets else 'false'}\n") return 0 options = {"only_changed": True} if args.only_changed else {} + if args.background: + options["background"] = True if args.recover_run or args.all_open_prs: targets = prepare_targets( api, args.repository, args.pr_number, args.all_open_prs, args.recover_run diff --git a/scripts/tests/test_ai_review_status.py b/scripts/tests/test_ai_review_status.py index 0c9556f..71bf843 100644 --- a/scripts/tests/test_ai_review_status.py +++ b/scripts/tests/test_ai_review_status.py @@ -190,6 +190,60 @@ def test_latest_context_stops_before_reading_older_history_pages(self): self.assertEqual(status["id"], 150) self.assertEqual(request.call_count, 1) + def test_background_business_failure_does_not_start_recovery(self): + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "1"}), + patch.object(checker, "snapshot", return_value=fixtures.fixture()), + patch("builtins.print"), + ): + self.assertTrue( + checker.check_pr( + self.api, + "org/repo", + 128, + {fixtures.BOT}, + background=True, + ) + ) + self.assert_states(["pending", "failure"]) + + def test_background_unchanged_blocking_result_does_not_start_recovery(self): + data = fixtures.fixture() + self.assertFalse(self.invoke(data)) + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "2"}), + patch.object(checker, "snapshot", return_value=data), + patch("builtins.print"), + ): + self.assertTrue( + checker.check_pr( + self.api, + "org/repo", + 128, + {fixtures.BOT}, + only_changed=True, + background=True, + ) + ) + self.assert_states(["pending", "failure"]) + + def test_background_execution_failure_still_starts_recovery(self): + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "1"}), + patch.object(checker, "snapshot", side_effect=RuntimeError("read failed")), + patch("builtins.print"), + ): + self.assertFalse( + checker.check_pr( + self.api, + "org/repo", + 128, + {fixtures.BOT}, + background=True, + ) + ) + self.assert_states(["pending", "failure"]) + class SingleRowWorkflowTests(unittest.TestCase): def test_caller_and_recovery_never_use_pr_associated_triggers(self):