From 2845db1661fef7f124d4a4788dbb85c51634eb87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sat, 31 Oct 2026 21:40:45 +0900 Subject: [PATCH 1/5] feat: add Project delivery synchronization --- .github/PROJECT_SYNC.md | 110 ++++ .github/workflows/project-sync-tests.yml | 36 ++ .github/workflows/project-sync.yml | 71 +++ scripts/sync_github_project.py | 642 +++++++++++++++++++++++ tests/test_project_delivery.py | 416 +++++++++++++++ tests/test_sync_github_project.py | 268 ++++++++++ 6 files changed, 1543 insertions(+) create mode 100644 .github/PROJECT_SYNC.md create mode 100644 .github/workflows/project-sync-tests.yml create mode 100644 .github/workflows/project-sync.yml create mode 100644 scripts/sync_github_project.py create mode 100644 tests/test_project_delivery.py create mode 100644 tests/test_sync_github_project.py diff --git a/.github/PROJECT_SYNC.md b/.github/PROJECT_SYNC.md new file mode 100644 index 00000000000..91d2a011533 --- /dev/null +++ b/.github/PROJECT_SYNC.md @@ -0,0 +1,110 @@ +# GitHub Project synchronization + +## Behavior + +This follows Peach's event-driven plus periodic reconciliation approach. Every run +builds a read-only snapshot and full diff first. Events and the six-hour schedule +apply changes; manual dispatch and local runs preview by default. Manual `apply` +must be explicitly selected. Sync never edits or deletes source Issues/PRs. + +- Required single-select `Status`: `Todo`, `In progress`, `Needs verification`, + `Done`, `Cancelled`, `Closed unmerged`. Required single-select `交付进度`: + `未关联实现`, `尚未合入`, `已合入待发布`, `已发布`. Required text fields: + `实现关联`, `发布版本`, `发布说明`. +- Open issues start Todo. Linked active PRs mean In progress; merge alone means + Needs verification, not acceptance. Closed issues are Done unless GitHub close + reason is NOT_PLANNED (Cancelled). Closed unmerged PRs are not Done. Reopened + terminal items return to Todo. Preserve manually selected nonterminal status + without implementation. Optional labels `status:needs-info` and + `status:needs-verification` override inferred open-issue progress. +- Associate same-repository issues using closing references or standalone + `Ref(s)`, `Fix(es/ed)`, `Close(d)`, or `Resolve(s/d)` lines. Incidental mentions, + code fences, and cross-repository references do not establish a link. +- Delivery requires every associated implementation PR to be merged, every merge + commit to be reachable from the trusted default branch, and every such commit + to be contained in the earliest published stable release. Drafts/prereleases do + not count. Populate PR links and actual release tag/URL, never guess a version. +- Scan all open issues and all PRs. Also reconcile tracked closed items, linked + closed issues, and the current event subject; do not import unrelated closed + history. Skip archived items and draft issues. +- Validate the Project schema/options and calculate all changes before writing; + skip unchanged values and clear stale text. Paginate every GraphQL connection, + reject stalled cursors, and serialize whole-project runs. +- Privileged jobs run trusted default-branch code only, use full Git history/tags, + and never execute PR code. PR tests use no Project secret. + +Run offline tests and checks: + +```sh +python -I tests/test_sync_github_project.py -v +python -I tests/test_project_delivery.py -v +uv run ruff format --check scripts/sync_github_project.py tests/test_sync_github_project.py tests/test_project_delivery.py +uv run ruff check scripts/sync_github_project.py +``` + +## Configuration + +Set these repository Actions variables: + +| Variable | Value | +| --- | --- | +| `ASTRBOT_PROJECT_ID` | Destination Projects v2 node ID (`PVT_...`); required to enable | +| `ASTRBOT_PROJECT_STATUS_OPEN` | Open-state option name; default `Todo` | +| `ASTRBOT_PROJECT_STATUS_DONE` | Closed/merged-state option name; default `Done` | +| `ASTRBOT_PROJECT_STATUS_MAP` | Optional JSON object mapping remaining canonical Status values to existing option labels | + +Example map when an existing Project uses translated Status labels: + +```json +{"In progress":"进行中","Needs verification":"待验证","Cancelled":"已取消","Closed unmerged":"已关闭未合入"} +``` + +Set the Actions secret `ASTRBOT_PROJECT_TOKEN` to a credential with project write +access and read access to this repository's issues and pull requests. +For example, use a classic personal access token with the `project` scope, +owned by an account that can edit the destination project. Honor any organization +SSO authorization and token restrictions. The repository `GITHUB_TOKEN` is not +used for project mutations. +The Project must contain all five fields and options listed above. Do not use this +credential in ordinary pull request test jobs. + +To resolve an organization project's node ID, replace `PROJECT_NUMBER` with the +number from its GitHub URL (not its node ID): + +```sh +gh auth refresh -s project +gh api graphql -f query='query($owner: String!, $number: Int!) { + organization(login: $owner) { projectV2(number: $number) { id } } +}' -f owner=AstrBotDevs -F number=PROJECT_NUMBER --jq '.data.organization.projectV2.id' +``` + +Merge to the default branch, configure the fields and secret, then preview with +manual dispatch before selecting `apply`. Verify an Issue→PR→merge→stable release +path plus a fork PR. A mutation can partially apply; rerunning or waiting for the +next schedule reconciles current state. Remove `ASTRBOT_PROJECT_ID` to disable. + +## Boundaries + +- Always: pass GraphQL variables separately, paginate connections, fail on API + errors, use timeouts, preview before manual writes, test without credentials. +- Ask first: cross-repository links, legacy backfill, additional tracking fields, + changing automatic Status rules, creating credentials or a Project. +- Never: commit secrets, check out PR head code in the privileged workflow, + modify issue/PR state, delete project items, commit or push without permission. + +Historical unrelated closed issues are intentionally not imported. Coordinate any +native Project automation that writes these same fields. GitHub Actions and live +API validation require maintainer configuration after merge. + +## API reference + +GitHub's official "Using the API to manage Projects" documentation describes +ProjectV2 field lookup, `addProjectV2ItemById` (including existing-item reuse), +and `updateProjectV2ItemFieldValue`: +https://docs.github.com/en/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects + +Peach reference: [Issue #268](https://github.com/peach-mitao/peach/issues/268), +[Project Board workflow](https://github.com/peach-mitao/peach/blob/master/.github/workflows/project-board.yml), +and [reconciler](https://github.com/peach-mitao/peach/blob/master/scripts/project_board.py). +This implementation adopts event/schedule/manual reconciliation and delivery +evidence, not Peach's unrelated migration/alias configuration. diff --git a/.github/workflows/project-sync-tests.yml b/.github/workflows/project-sync-tests.yml new file mode 100644 index 00000000000..d4b9906c6f4 --- /dev/null +++ b/.github/workflows/project-sync-tests.yml @@ -0,0 +1,36 @@ +name: Test GitHub Project Sync + +on: + pull_request: + paths: + - '.github/workflows/project-sync*.yml' + - 'scripts/sync_github_project.py' + - 'tests/test_sync_github_project.py' + - 'tests/test_project_delivery.py' + push: + branches: [master] + paths: + - '.github/workflows/project-sync*.yml' + - 'scripts/sync_github_project.py' + - 'tests/test_sync_github_project.py' + - 'tests/test_project_delivery.py' + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: '3.12' + - name: Run network-free regression tests + run: | + python -I tests/test_sync_github_project.py -v + python -I tests/test_project_delivery.py -v diff --git a/.github/workflows/project-sync.yml b/.github/workflows/project-sync.yml new file mode 100644 index 00000000000..c1f72e46619 --- /dev/null +++ b/.github/workflows/project-sync.yml @@ -0,0 +1,71 @@ +name: Sync GitHub Project + +on: + issues: + types: [opened, reopened, closed, labeled, unlabeled, edited] + pull_request_target: + types: [opened, reopened, closed, edited, synchronize, ready_for_review, converted_to_draft] + release: + types: [published, edited, deleted] + push: + branches: [master] + schedule: + - cron: '17 */6 * * *' + workflow_dispatch: + inputs: + apply: + description: 'Apply the change plan (false previews without writing)' + type: boolean + default: false + required: true + +permissions: + contents: read + +# Every run reconciles the whole project; serialize snapshots, not just items. +concurrency: + group: project-sync-${{ github.repository }} + cancel-in-progress: false + +jobs: + sync: + if: github.repository == 'AstrBotDevs/AstrBot' && vars.ASTRBOT_PROJECT_ID != '' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Validate manual branch + if: github.event_name == 'workflow_dispatch' && github.ref != format('refs/heads/{0}', github.event.repository.default_branch) + run: | + echo 'Manual sync must run from the default branch.' + exit 1 + # Never check out the PR head or a PR-controlled base branch with this token. + - name: Check out trusted default branch + uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch || github.ref_name }} + persist-credentials: false + fetch-depth: 0 + fetch-tags: true + sparse-checkout: scripts/sync_github_project.py + sparse-checkout-cone-mode: false + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + + - name: Synchronize current item state + env: + ASTRBOT_PROJECT_ID: ${{ vars.ASTRBOT_PROJECT_ID }} + ASTRBOT_PROJECT_STATUS_OPEN: ${{ vars.ASTRBOT_PROJECT_STATUS_OPEN }} + ASTRBOT_PROJECT_STATUS_DONE: ${{ vars.ASTRBOT_PROJECT_STATUS_DONE }} + ASTRBOT_PROJECT_STATUS_MAP: ${{ vars.ASTRBOT_PROJECT_STATUS_MAP }} + ASTRBOT_PROJECT_TOKEN: ${{ secrets.ASTRBOT_PROJECT_TOKEN }} + ASTRBOT_DEFAULT_BRANCH: ${{ github.event.repository.default_branch || github.ref_name }} + APPLY_CHANGES: ${{ github.event_name != 'workflow_dispatch' || inputs.apply }} + run: | + if [ "$APPLY_CHANGES" = 'true' ]; then + python -I scripts/sync_github_project.py --apply + else + python -I scripts/sync_github_project.py + fi diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py new file mode 100644 index 00000000000..3f314204bde --- /dev/null +++ b/scripts/sync_github_project.py @@ -0,0 +1,642 @@ +"""Synchronize issue and pull request lifecycle events to GitHub Projects v2.""" + +import argparse +import json +import os +import re +import subprocess +import urllib.error +import urllib.request +from functools import cache +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +STATUS_OPTIONS = ( + "Todo", + "In progress", + "Needs verification", + "Done", + "Cancelled", + "Closed unmerged", +) +DELIVERY_OPTIONS = ("未关联实现", "尚未合入", "已合入待发布", "已发布") + + +def connection(query, path, *, initial=None, **variables): + """Read every page and fail if the cursor stalls. + + Args: + query: GraphQL operation accepting a cursor variable. + path: Keys leading to a connection in the response. + initial: Optional first page already returned in a parent query. + **variables: Other operation variables. + + Returns: + All non-null connection nodes. + + Raises: + RuntimeError: A cursor does not advance or the connection is inaccessible. + """ + nodes, cursor, seen = [], None, set() + while True: + if initial is not None: + data, initial = initial, None + else: + data = graphql(query, {**variables, "cursor": cursor}) + for key in path: + data = (data or {}).get(key) + if not isinstance(data, dict): + raise RuntimeError("GitHub connection is inaccessible") + nodes.extend(node for node in data["nodes"] if node) + page = data["pageInfo"] + if not page["hasNextPage"]: + return nodes + cursor = page["endCursor"] + if not cursor or cursor in seen: + raise RuntimeError("GitHub pagination cursor did not advance") + seen.add(cursor) + + +def references(body, repository): + """Read explicit same-repository issue reference lines, excluding code fences. + + Args: + body: Pull request description. + repository: Allowed owner/name. + + Returns: + Referenced issue numbers. + """ + found, fence = set(), None + for line in (body or "").splitlines(): + marker = re.match(r"^\s{0,3}(`{3,}|~{3,})", line) + if marker: + token = marker[1] + if fence is None: + fence = token + elif token[0] == fence[0] and len(token) >= len(fence): + fence = None + continue + if fence or not re.match( + r"^\s*(?:refs?|close[sd]?|fix(?:es|ed)?|resolve[sd]?)\s*[::]?\s+", + line, + re.I, + ): + continue + # Match complete URLs first so foreign URL fragments cannot become local refs. + for match in re.finditer( + r"https?://[^\s,<>]+|(?[\w.-]+/[\w.-]+))?#(?P[0-9]+)", + line, + ): + if match["number"]: + repo, number = match["repo"] or repository, match["number"] + else: + url = re.fullmatch( + r"https://github\.com/([\w.-]+/[\w.-]+)/issues/([0-9]+)[.)]?", + match[0], + re.I, + ) + if not url: + continue + repo, number = url.groups() + if repo.casefold() == repository.casefold() and int(number) > 0: + found.add(int(number)) + return found + + +def decide(content, current, linked): + """Separate issue acceptance from implementation progress. + + Args: + content: Current issue or pull request data. + current: Existing Project field values. + linked: Active or merged implementation pull requests. + + Returns: + Desired Status value. + """ + state = content["state"] + status = current.get("Status", "Todo") + if content["__typename"] == "PullRequest": + status = {"OPEN": "In progress", "CLOSED": "Closed unmerged", "MERGED": "Done"}[ + state + ] + elif state == "CLOSED": + status = "Cancelled" if content.get("stateReason") == "NOT_PLANNED" else "Done" + elif "status:needs-verification" in content.get("labels", []): + status = "Needs verification" + elif "status:needs-info" in content.get("labels", []): + status = "Todo" + elif linked and all(pr["state"] == "MERGED" for pr in linked): + status = "Needs verification" + elif linked: + status = "In progress" + elif status not in STATUS_OPTIONS or status in { + "Done", + "Cancelled", + "Closed unmerged", + }: + status = "Todo" + return {"Status": status} + + +@cache +def ancestor(commit, ref): + """Check commit reachability without running user-controlled shell commands. + + Args: + commit: Full implementation commit OID. + ref: Trusted mainline OID or fully qualified release tag ref. + + Returns: + Whether the commit is contained in the ref. + + Raises: + ValueError: The commit or reference is invalid. + RuntimeError: Git history is incomplete or git fails. + """ + if not re.fullmatch(r"[0-9a-f]{40}", commit) or not ( + re.fullmatch(r"[0-9a-f]{40}", ref) or ref.startswith("refs/tags/") + ): + raise ValueError("Invalid implementation commit or release ref") + result = subprocess.run( + ["git", "merge-base", "--is-ancestor", commit, ref], + cwd=ROOT, + capture_output=True, + timeout=30, + check=False, + ) + if result.returncode not in (0, 1): + raise RuntimeError( + "Cannot verify release ancestry; fetch full history and tags" + ) + return result.returncode == 0 + + +def delivery(content, current, linked, releases, mainline): + """Calculate implementation links and the earliest proven stable release. + + Args: + content: Current source item. + current: Existing Project values. + linked: Associated active or merged pull requests. + releases: Published releases with flags and timestamps. + mainline: Trusted default-branch commit OID. + + Returns: + Desired values for all five managed fields. + """ + associated = [content] if content["__typename"] == "PullRequest" else linked + merged = [pr for pr in associated if pr["state"] == "MERGED"] + commits = {pr["mergeCommit"]["oid"] for pr in merged if pr.get("mergeCommit")} + integrated = {commit for commit in commits if ancestor(commit, mainline)} + all_merged = bool(associated) and len(merged) == len(associated) + all_integrated = ( + bool(merged) and len(commits) == len(merged) and integrated == commits + ) + published = None + for release in sorted( + ( + r + for r in releases + if not r["isDraft"] and not r["isPrerelease"] and r.get("publishedAt") + ), + key=lambda r: r["publishedAt"], + ): + if ( + all_merged + and all_integrated + and all( + ancestor(commit, f"refs/tags/{release['tagName']}") + for commit in integrated + ) + ): + published = release + break + progress = ( + "已发布" + if published + else "已合入待发布" + if all_merged and all_integrated + else "尚未合入" + if associated + else "未关联实现" + ) + return { + **decide(content, current, linked), + "交付进度": progress, + "实现关联": "\n".join( + sorted({pr["url"] for pr in associated if pr.get("url")}) + ), + "发布版本": published["tagName"] if published else "", + "发布说明": published["url"] if published else "", + } + + +def apply_plan(project, fields, plan, *, apply=False): + """Apply only precomputed differences; preview never issues mutations. + + Args: + project: Destination node ID. + fields: Validated field definitions. + plan: Source IDs, existing item IDs and changed values. + apply: Explicit permission to write. + """ + if not apply: + return + for entry in plan: + item = entry["item"] + if not item: + result = graphql( + """mutation($project: ID!, $content: ID!) { + addProjectV2ItemById(input: {projectId:$project, contentId:$content}) { item { id } } + }""", + {"project": project, "content": entry["content"]}, + ) + item = result["addProjectV2ItemById"]["item"]["id"] + for name, value in entry["changes"].items(): + field = fields[name] + variables = {"project": project, "item": item, "field": field["id"]} + if value == "": + graphql( + """mutation($project:ID!,$item:ID!,$field:ID!){ + clearProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field}){projectV2Item{id}} + }""", + variables, + ) + else: + variables["value"] = ( + { + "singleSelectOptionId": next( + o["id"] for o in field["options"] if o["name"] == value + ) + } + if "options" in field + else {"text": value} + ) + graphql( + """mutation($project:ID!,$item:ID!,$field:ID!,$value:ProjectV2FieldValue!){ + updateProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field,value:$value}){projectV2Item{id}} + }""", + variables, + ) + + +def graphql(query, variables): + """Execute a GitHub GraphQL request without exposing credentials in errors. + + Args: + query: GraphQL operation text. + variables: Separate operation variables. + + Returns: + The response data dictionary. + + Raises: + RuntimeError: The request fails or returns GraphQL errors. + """ + request = urllib.request.Request( + "https://api.github.com/graphql", + data=json.dumps({"query": query, "variables": variables}).encode(), + headers={ + "Authorization": f"Bearer {os.environ['ASTRBOT_PROJECT_TOKEN']}", + "Content-Type": "application/json", + "User-Agent": "AstrBot-Project-Sync", + }, + method="POST", + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + result = json.load(response) + except (urllib.error.URLError, TimeoutError, ValueError): + raise RuntimeError( + "GitHub GraphQL request failed; check connectivity and token permissions" + ) from None + if ( + not isinstance(result, dict) + or result.get("errors") + or not isinstance(result.get("data"), dict) + ): + raise RuntimeError( + "GitHub GraphQL returned errors; check project and repository access" + ) + return result["data"] + + +def reconcile(project, repository, *, subject=None, apply=False, status_names=None): + """Plan a complete snapshot before performing any Project mutations. + + Args: + project: Destination ProjectV2 node ID. + repository: Allowed source owner/name. + subject: Event item number to include even if closed. + apply: Explicit permission to write. + status_names: Canonical-to-configured Status names. + + Returns: + JSON-serializable change plan. + + Raises: + ValueError: Required fields, options or source states are invalid. + RuntimeError: GitHub reads or ancestry checks fail. + """ + status_names = status_names or dict(zip(STATUS_OPTIONS, STATUS_OPTIONS)) + definitions = connection( + """query($project:ID!,$cursor:String){node(id:$project){... on ProjectV2{ + fields(first:100,after:$cursor){nodes{ + ... on ProjectV2Field{id name dataType} + ... on ProjectV2SingleSelectField{id name options{id name}} + }pageInfo{hasNextPage endCursor}}}}}""", + ("node", "fields"), + project=project, + ) + fields = {} + for field in definitions: + if "name" not in field: + continue + if field["name"] in fields: + raise ValueError("Project field names must be unique") + fields[field["name"]] = field + for name, required in { + "Status": tuple(status_names.values()), + "交付进度": DELIVERY_OPTIONS, + }.items(): + field = fields.get(name, {}) + options = [o["name"] for o in field.get("options", [])] + if ( + not field.get("options") + or not set(required) <= set(options) + or len(options) != len(set(options)) + ): + raise ValueError( + f"Project {name} must be single-select with all required options" + ) + for name in ("实现关联", "发布版本", "发布说明"): + if fields.get(name, {}).get("dataType") != "TEXT": + raise ValueError(f"Project {name} must be a text field") + items = connection( + """query($project:ID!,$cursor:String){node(id:$project){... on ProjectV2{ + items(first:100,after:$cursor,archivedStates:[ARCHIVED,NOT_ARCHIVED]){nodes{ + id isArchived content{__typename ... on Issue{id} ... on PullRequest{id}} + fieldValues(first:100){nodes{ + ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} + ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} + }pageInfo{hasNextPage endCursor}} + }pageInfo{hasNextPage endCursor}}}}}""", + ("node", "items"), + project=project, + ) + tracked = { + item["content"]["id"]: item + for item in items + if item.get("content") + and item["content"]["__typename"] in {"Issue", "PullRequest"} + } + owner, name = repository.split("/") + variables = {"owner": owner, "name": name} + issues = connection( + """query($owner:String!,$name:String!,$states:[IssueState!],$cursor:String){repository(owner:$owner,name:$name){ + issues(first:100,after:$cursor,states:$states){nodes{__typename id number state stateReason + labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}}} + pageInfo{hasNextPage endCursor}}}}""", + ("repository", "issues"), + states=["OPEN", "CLOSED"], + **variables, + ) + prs = connection( + """query($owner:String!,$name:String!,$states:[PullRequestState!],$cursor:String){repository(owner:$owner,name:$name){ + pullRequests(first:100,after:$cursor,states:$states){nodes{__typename id number state body url + mergeCommit{oid} + closingIssuesReferences(first:100){nodes{number repository{nameWithOwner}} + pageInfo{hasNextPage endCursor}} + }pageInfo{hasNextPage endCursor}}}}""", + ("repository", "pullRequests"), + states=["OPEN", "CLOSED", "MERGED"], + **variables, + ) + linked = {} + for pr in prs: + if pr["state"] not in {"OPEN", "MERGED", "CLOSED"}: + raise ValueError("Unexpected pull request state") + if pr["state"] == "CLOSED": + continue + closing = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on PullRequest{ + closingIssuesReferences(first:100,after:$cursor){nodes{number repository{nameWithOwner}} + pageInfo{hasNextPage endCursor}}}}}""", + ("node", "closingIssuesReferences"), + initial=pr["closingIssuesReferences"], + id=pr["id"], + ) + numbers = { + issue["number"] + for issue in closing + if issue["repository"]["nameWithOwner"].casefold() == repository.casefold() + } + numbers |= references(pr.get("body"), repository) + for number in numbers: + linked.setdefault(number, []).append(pr) + candidates = [ + i + for i in issues + if i["state"] == "OPEN" + or i["id"] in tracked + or i["number"] == subject + or i["number"] in linked + ] + issue_numbers = {i["number"] for i in candidates} + associated_ids = { + pr["id"] for number in issue_numbers for pr in linked.get(number, []) + } + candidates.extend( + pr + for pr in prs + if pr["state"] == "OPEN" + or pr["id"] in tracked + or pr["number"] == subject + or pr["id"] in associated_ids + ) + releases = connection( + """query($owner:String!,$name:String!,$cursor:String){repository(owner:$owner,name:$name){ + releases(first:100,after:$cursor){nodes{tagName url publishedAt isDraft isPrerelease} + pageInfo{hasNextPage endCursor}}}}""", + ("repository", "releases"), + **variables, + ) + mainline = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=ROOT, + capture_output=True, + text=True, + timeout=30, + check=True, + ).stdout.strip() + plan = [] + for content in candidates: + item = tracked.get(content["id"]) + if item and item["isArchived"]: + continue + if content["__typename"] == "Issue": + if content["state"] not in {"OPEN", "CLOSED"}: + raise ValueError("Unexpected issue state") + labels = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on Issue{labels(first:100,after:$cursor){ + nodes{name}pageInfo{hasNextPage endCursor}}}}}""", + ("node", "labels"), + initial=content["labels"], + id=content["id"], + ) + content["labels"] = [label["name"] for label in labels] + current = {} + if item: + values = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on ProjectV2Item{ + fieldValues(first:100,after:$cursor){nodes{ + ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} + ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} + }pageInfo{hasNextPage endCursor}}}}}""", + ("node", "fieldValues"), + initial=item["fieldValues"], + id=item["id"], + ) + current = { + v["field"]["name"]: v.get("name", v.get("text", "")) + for v in values + if v.get("field") + } + canonical = { + **current, + "Status": next( + (k for k, v in status_names.items() if v == current.get("Status")), + "Todo", + ), + } + desired = delivery( + content, canonical, linked.get(content["number"], []), releases, mainline + ) + desired["Status"] = status_names[desired["Status"]] + changes = {k: v for k, v in desired.items() if current.get(k, "") != v} + if changes or not item: + plan.append( + { + "content": content["id"], + "item": item["id"] if item else None, + "number": content["number"], + "changes": changes, + } + ) + apply_plan(project, fields, plan, apply=apply) + return plan + + +def main(argv=None): + """Validate trusted context and reconcile; default to preview. + + Args: + argv: Optional command-line argument list. + + Raises: + ValueError: Credentials or supported event context are missing or invalid. + RuntimeError: Synchronization fails. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--apply", action="store_true") + args = parser.parse_args(argv) + project = os.environ.get("ASTRBOT_PROJECT_ID", "").strip() + if not project: + print("Project synchronization disabled: ASTRBOT_PROJECT_ID is not set") + return + if not os.environ.get("ASTRBOT_PROJECT_TOKEN", "").strip(): + raise ValueError( + "ASTRBOT_PROJECT_TOKEN is required when Project sync is enabled" + ) + repository = os.environ.get("GITHUB_REPOSITORY", "AstrBotDevs/AstrBot") + if repository != "AstrBotDevs/AstrBot": + raise ValueError("Unexpected repository") + subject = None + event_name = os.environ.get("GITHUB_EVENT_NAME") + if event_name: + allowed = { + "issues": { + "opened", + "reopened", + "closed", + "labeled", + "unlabeled", + "edited", + }, + "pull_request_target": { + "opened", + "reopened", + "closed", + "edited", + "synchronize", + "ready_for_review", + "converted_to_draft", + }, + "release": {"published", "edited", "deleted"}, + "push": None, + "schedule": None, + "workflow_dispatch": None, + } + if event_name not in allowed: + raise ValueError("Unsupported GitHub event") + event = json.loads( + Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8") + ) + if ( + event_name != "schedule" + and event.get("repository", {}).get("full_name") != repository + ): + raise ValueError("Unexpected event repository") + default_branch = ( + os.environ.get("ASTRBOT_DEFAULT_BRANCH") + if event_name == "schedule" + else event["repository"]["default_branch"] + ) + default_ref = f"refs/heads/{default_branch}" + if ( + event_name in {"push", "workflow_dispatch", "schedule"} + and os.environ.get("GITHUB_REF") != default_ref + ): + raise ValueError("Push and manual runs require the default branch") + if ( + allowed[event_name] is not None + and event.get("action") not in allowed[event_name] + ): + raise ValueError("Unexpected lifecycle action") + if event_name in {"issues", "pull_request_target"}: + subject = event.get( + "issue" if event_name == "issues" else "pull_request", {} + ).get("number") + if type(subject) is not int or subject <= 0: + raise ValueError("Unexpected item number") + status_names = dict(zip(STATUS_OPTIONS, STATUS_OPTIONS)) + overrides = json.loads(os.environ.get("ASTRBOT_PROJECT_STATUS_MAP") or "{}") + if not isinstance(overrides, dict) or not overrides.keys() <= status_names.keys(): + raise ValueError("Invalid Status mapping keys") + status_names.update(overrides) + for key, env in { + "Todo": "ASTRBOT_PROJECT_STATUS_OPEN", + "Done": "ASTRBOT_PROJECT_STATUS_DONE", + }.items(): + if os.environ.get(env): + status_names[key] = os.environ[env] + if any( + not isinstance(v, str) or not v.strip() for v in status_names.values() + ) or len(set(status_names.values())) != len(STATUS_OPTIONS): + raise ValueError("Status names must be nonempty and distinct") + plan = reconcile( + project, + repository, + subject=subject, + apply=args.apply, + status_names=status_names, + ) + print( + json.dumps({"apply": args.apply, "changes": plan}, ensure_ascii=False, indent=2) + ) + + +if __name__ == "__main__": + main() diff --git a/tests/test_project_delivery.py b/tests/test_project_delivery.py new file mode 100644 index 00000000000..ea4e9784852 --- /dev/null +++ b/tests/test_project_delivery.py @@ -0,0 +1,416 @@ +"""Network-free tests for full Project delivery reconciliation.""" + +import importlib.util +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +SPEC = importlib.util.spec_from_file_location( + "project_delivery", + Path(__file__).resolve().parents[1] / "scripts/sync_github_project.py", +) +sync = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(sync) + + +class DeliveryTests(unittest.TestCase): + def setUp(self): + self.fields = [ + { + "name": name, + "id": name, + "options": [{"name": value, "id": value} for value in values], + } + for name, values in [ + ("Status", sync.STATUS_OPTIONS), + ("交付进度", sync.DELIVERY_OPTIONS), + ] + ] + [ + {"name": name, "id": name, "dataType": "TEXT"} + for name in ("实现关联", "发布版本", "发布说明") + ] + self.page = {"nodes": [], "pageInfo": {"hasNextPage": False, "endCursor": None}} + self.issue = { + "__typename": "Issue", + "id": "ISSUE", + "number": 1, + "state": "OPEN", + "labels": self.page, + } + + def test_snapshot_preview_apply_and_second_run_idempotence(self): + for apply in (False, True): + with ( + self.subTest(apply=apply), + patch.object( + sync, + "connection", + side_effect=[self.fields, [], [dict(self.issue)], [], [], []], + ), + patch.object( + sync.subprocess, "run", return_value=Mock(stdout="a" * 40) + ), + patch.object( + sync, + "graphql", + return_value={"addProjectV2ItemById": {"item": {"id": "I"}}}, + ) as api, + ): + plan = sync.reconcile("P", "AstrBotDevs/AstrBot", apply=apply) + self.assertEqual( + plan[0]["changes"], {"Status": "Todo", "交付进度": "未关联实现"} + ) + self.assertEqual(api.call_count, 3 if apply else 0) + item = { + "id": "I", + "content": self.issue, + "isArchived": False, + "fieldValues": self.page, + } + values = [ + {"field": {"name": key}, "name": value} + for key, value in plan[0]["changes"].items() + ] + with ( + patch.object( + sync, + "connection", + side_effect=[ + self.fields, + [item], + [dict(self.issue)], + [], + [], + [], + values, + ], + ), + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + patch.object(sync, "graphql") as api, + ): + self.assertEqual(sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True), []) + api.assert_not_called() + + def test_snapshot_skips_archived_draft_foreign_and_old_closed(self): + archived = {"id": "I", "content": self.issue, "isArchived": True} + foreign = { + "id": "F", + "content": {"__typename": "Issue", "id": "FOREIGN"}, + "isArchived": False, + } + draft = { + "id": "D", + "content": {"__typename": "DraftIssue", "id": "DRAFT"}, + "isArchived": False, + } + closed = {**self.issue, "id": "OLD", "number": 2, "state": "CLOSED"} + with ( + patch.object( + sync, + "connection", + side_effect=[ + self.fields, + [archived, foreign, draft], + [self.issue, closed], + [], + [], + ], + ), + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + patch.object(sync, "graphql") as api, + ): + self.assertEqual(sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True), []) + api.assert_not_called() + + def test_reconciliation_explicitly_scans_closed_issues_and_merged_prs(self): + with ( + patch.object( + sync, "connection", side_effect=[self.fields, [], [], [], []] + ) as read, + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + ): + self.assertEqual(sync.reconcile("P", "AstrBotDevs/AstrBot"), []) + self.assertEqual(read.call_args_list[2].kwargs["states"], ["OPEN", "CLOSED"]) + self.assertEqual( + read.call_args_list[3].kwargs["states"], ["OPEN", "CLOSED", "MERGED"] + ) + + def test_invalid_field_configuration_fails_before_other_reads_or_writes(self): + for fields in [ + self.fields[:-1], + [{**self.fields[0], "options": []}, *self.fields[1:]], + [*self.fields, self.fields[0]], + [{**self.fields[0], "options": []}, *self.fields[1:]], + ]: + with ( + self.subTest(fields=fields), + patch.object(sync, "connection", return_value=fields) as read, + patch.object(sync, "graphql") as api, + ): + with self.assertRaises(ValueError): + sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True) + self.assertEqual(read.call_count, 1) + api.assert_not_called() + + def test_late_read_failure_never_partially_applies_plan(self): + second = {**self.issue, "id": "SECOND", "number": 2} + with ( + patch.object( + sync, + "connection", + side_effect=[ + self.fields, + [], + [dict(self.issue), second], + [], + [], + [], + RuntimeError("read failed"), + ], + ), + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + patch.object(sync, "graphql") as api, + ): + with self.assertRaisesRegex(RuntimeError, "read failed"): + sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True) + api.assert_not_called() + + def test_closed_subject_is_added_using_current_state(self): + closed = {**self.issue, "state": "CLOSED", "stateReason": "NOT_PLANNED"} + with ( + patch.object( + sync, "connection", side_effect=[self.fields, [], [closed], [], [], []] + ), + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + ): + plan = sync.reconcile("P", "AstrBotDevs/AstrBot", subject=1) + self.assertEqual(plan[0]["changes"]["Status"], "Cancelled") + + def test_initial_connection_page_avoids_network_and_continues_pagination(self): + initial = {"nodes": [1], "pageInfo": {"hasNextPage": True, "endCursor": "NEXT"}} + with patch.object( + sync, "graphql", return_value={"page": {**self.page, "nodes": [2]}} + ) as api: + self.assertEqual( + sync.connection("query", ("page",), initial=initial), [1, 2] + ) + self.assertEqual(api.call_args.args[1]["cursor"], "NEXT") + with patch.object(sync, "graphql") as api: + self.assertEqual(sync.connection("query", ("page",), initial=self.page), []) + api.assert_not_called() + + def test_multiple_implementations_need_all_commits_in_release(self): + issue = {"__typename": "Issue", "state": "OPEN", "labels": []} + prs = [ + {"state": "MERGED", "mergeCommit": {"oid": char * 40}, "url": char} + for char in ("a", "b") + ] + releases = [ + { + "tagName": "v1", + "publishedAt": "2026-01-01", + "url": "r", + "isDraft": False, + "isPrerelease": False, + } + ] + with patch.object( + sync, + "ancestor", + side_effect=lambda commit, ref: ref == "c" * 40 or commit == "a" * 40, + ): + desired = sync.delivery(issue, {}, prs, releases, "c" * 40) + self.assertEqual(desired["发布版本"], "") + self.assertEqual(desired["Status"], "Needs verification") + + def test_open_implementation_prevents_released_delivery(self): + issue = {"__typename": "Issue", "state": "OPEN", "labels": []} + merged = {"state": "MERGED", "mergeCommit": {"oid": "a" * 40}, "url": "merged"} + opened = {"state": "OPEN", "url": "open"} + releases = [ + { + "tagName": "v1", + "publishedAt": "2026-01-01", + "url": "r", + "isDraft": False, + "isPrerelease": False, + } + ] + with patch.object(sync, "ancestor", return_value=True): + desired = sync.delivery(issue, {}, [merged, opened], releases, "c" * 40) + self.assertEqual(desired["发布版本"], "") + self.assertEqual(desired["交付进度"], "尚未合入") + + def test_unreachable_merged_commit_is_not_reported_as_delivered(self): + issue = {"__typename": "Issue", "state": "OPEN", "labels": []} + pr = {"state": "MERGED", "mergeCommit": {"oid": "a" * 40}, "url": "pr"} + with patch.object(sync, "ancestor", return_value=False): + desired = sync.delivery(issue, {}, [pr], [], "c" * 40) + self.assertEqual(desired["交付进度"], "尚未合入") + + def test_closed_issue_referenced_by_implementation_is_candidate(self): + closed = {**self.issue, "state": "CLOSED", "number": 42, "id": "CLOSED"} + pr = { + "__typename": "PullRequest", + "id": "PR", + "number": 9, + "state": "MERGED", + "body": "Closes #42", + "url": "pr", + "mergeCommit": {"oid": "a" * 40}, + "closingIssuesReferences": self.page, + } + with ( + patch.object( + sync, + "connection", + side_effect=[self.fields, [], [closed], [pr], [], [], []], + ), + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + patch.object(sync, "ancestor", return_value=True), + ): + plan = sync.reconcile("P", "AstrBotDevs/AstrBot") + self.assertEqual({entry["number"] for entry in plan}, {9, 42}) + + def test_git_ancestry_errors_fail_closed(self): + sync.ancestor.cache_clear() + with patch.object(sync.subprocess, "run", return_value=Mock(returncode=128)): + with self.assertRaises(RuntimeError): + sync.ancestor("a" * 40, "refs/tags/missing") + with self.assertRaises(ValueError): + sync.ancestor("--bad-option", "refs/tags/v1") + + def test_reference_lines_ignore_incidental_and_foreign_mentions(self): + body = ( + "Mention #9 in passing\nRefs #12, #13\nFixes: AstrBotDevs/AstrBot#14\n" + "Closes https://github.com/AstrBotDevs/AstrBot/issues/15\n" + "Refs other/repo#12\nRefs https://github.com/other/repo/issues/16\n" + "```\nRefs #99\n```\n" + ) + self.assertEqual(sync.references(body, "AstrBotDevs/AstrBot"), {12, 13, 14, 15}) + + def test_decision_separates_acceptance_from_delivery(self): + issue = {"__typename": "Issue", "state": "OPEN", "labels": []} + for current, linked, expected in [ + ({}, [], "Todo"), + ({"Status": "In progress"}, [], "In progress"), + ({"Status": "Done"}, [], "Todo"), + ({}, [{"state": "OPEN"}], "In progress"), + ({}, [{"state": "MERGED"}], "Needs verification"), + ({}, [{"state": "OPEN"}, {"state": "MERGED"}], "In progress"), + ]: + with self.subTest(current=current, linked=linked): + self.assertEqual( + sync.decide(issue, current, linked)["Status"], expected + ) + issue.update(state="CLOSED", stateReason="NOT_PLANNED") + self.assertEqual(sync.decide(issue, {}, [])["Status"], "Cancelled") + issue["stateReason"] = "COMPLETED" + self.assertEqual(sync.decide(issue, {}, [])["Status"], "Done") + + def test_explicit_labels_and_unmerged_pr(self): + issue = { + "__typename": "Issue", + "state": "OPEN", + "labels": ["status:needs-info"], + } + self.assertEqual( + sync.decide(issue, {}, [{"state": "MERGED"}])["Status"], "Todo" + ) + issue["labels"] = ["status:needs-verification"] + self.assertEqual(sync.decide(issue, {}, [])["Status"], "Needs verification") + pr = {"__typename": "PullRequest", "state": "CLOSED"} + self.assertEqual(sync.decide(pr, {}, [])["Status"], "Closed unmerged") + + def test_release_requires_mainline_and_actual_tag_ancestry(self): + merged = { + "__typename": "PullRequest", + "state": "MERGED", + "mergeCommit": {"oid": "a" * 40}, + "url": "https://github.com/a/b/pull/1", + } + releases = [ + { + "tagName": "v1", + "url": "release1", + "publishedAt": "2026-01-01", + "isDraft": False, + "isPrerelease": False, + }, + { + "tagName": "v2", + "url": "release2", + "publishedAt": "2026-02-01", + "isDraft": False, + "isPrerelease": False, + }, + ] + with patch.object(sync, "ancestor", side_effect=[True, False, True]): + desired = sync.delivery(merged, {}, [], releases, "b" * 40) + self.assertEqual(desired["发布版本"], "v2") + self.assertEqual(desired["发布说明"], "release2") + self.assertEqual(desired["交付进度"], "已发布") + with patch.object(sync, "ancestor", return_value=False) as ancestor: + self.assertEqual( + sync.delivery(merged, {}, [], releases, "b" * 40)["发布版本"], "" + ) + self.assertEqual(ancestor.call_count, 1) + + def test_prerelease_and_draft_are_not_stable_delivery(self): + merged = { + "__typename": "PullRequest", + "state": "MERGED", + "mergeCommit": {"oid": "a" * 40}, + "url": "pr", + } + releases = [ + { + "tagName": "v1", + "publishedAt": "2026-01-01", + "isDraft": draft, + "isPrerelease": pre, + } + for draft, pre in [(True, False), (False, True)] + ] + with patch.object(sync, "ancestor", return_value=True): + desired = sync.delivery(merged, {}, [], releases, "b" * 40) + self.assertEqual(desired["交付进度"], "已合入待发布") + self.assertEqual(desired["发布版本"], "") + + def test_pagination_rejects_stalled_cursor(self): + data = { + "page": { + "nodes": [], + "pageInfo": {"hasNextPage": True, "endCursor": "same"}, + } + } + with patch.object(sync, "graphql", return_value=data): + with self.assertRaisesRegex(RuntimeError, "cursor"): + sync.connection("query", ("page",)) + + def test_dry_run_does_not_mutate_and_apply_skips_equal_fields(self): + plan = [ + { + "content": "C", + "item": "I", + "number": 1, + "changes": {"发布版本": "", "Status": "Done"}, + } + ] + fields = { + "发布版本": {"id": "V"}, + "Status": {"id": "S", "options": [{"name": "Done", "id": "D"}]}, + } + with patch.object(sync, "graphql", return_value={}) as api: + sync.apply_plan("P", fields, plan, apply=False) + api.assert_not_called() + sync.apply_plan("P", fields, plan, apply=True) + self.assertEqual(api.call_count, 2) + self.assertIn("clearProjectV2ItemFieldValue", api.call_args_list[0].args[0]) + self.assertEqual( + api.call_args_list[1].args[1]["value"], {"singleSelectOptionId": "D"} + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sync_github_project.py b/tests/test_sync_github_project.py new file mode 100644 index 00000000000..19bfa61bf38 --- /dev/null +++ b/tests/test_sync_github_project.py @@ -0,0 +1,268 @@ +"""Network-free transport and entrypoint tests for Project synchronization.""" + +import importlib.util +import io +import json +import os +import tempfile +import unittest +import urllib.error +from pathlib import Path +from unittest.mock import Mock, patch + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/sync_github_project.py" + + +class SyncProjectTests(unittest.TestCase): + def setUp(self): + spec = importlib.util.spec_from_file_location("sync_github_project", SCRIPT) + self.module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.module) + + def test_graphql_uses_variables_and_timeout(self): + with ( + patch.dict(os.environ, {"ASTRBOT_PROJECT_TOKEN": "secret"}), + patch.object( + self.module.urllib.request, + "urlopen", + return_value=io.StringIO('{"data": {"ok": true}}'), + ) as urlopen, + ): + self.assertEqual( + self.module.graphql("query", {"value": '"untrusted"'}), {"ok": True} + ) + request = urlopen.call_args.args[0] + self.assertEqual(request.full_url, "https://api.github.com/graphql") + self.assertEqual(request.get_header("Authorization"), "Bearer secret") + self.assertEqual( + json.loads(request.data), + {"query": "query", "variables": {"value": '"untrusted"'}}, + ) + self.assertEqual(urlopen.call_args.kwargs["timeout"], 30) + + def test_graphql_errors_do_not_leak_response(self): + for body in [ + '{"errors": [{"message": "secret"}], "data": {}}', + '{"data": null}', + "not JSON", + "[]", + "null", + ]: + with ( + self.subTest(body=body), + patch.dict(os.environ, {"ASTRBOT_PROJECT_TOKEN": "secret"}), + patch.object( + self.module.urllib.request, + "urlopen", + return_value=io.StringIO(body), + ), + ): + with self.assertRaises(RuntimeError) as error: + self.module.graphql("query", {}) + self.assertNotIn("secret", str(error.exception)) + + def test_transport_errors_do_not_leak_credentials(self): + for error in [urllib.error.URLError("secret"), TimeoutError("secret")]: + with ( + self.subTest(error=error), + patch.dict(os.environ, {"ASTRBOT_PROJECT_TOKEN": "secret"}), + patch.object(self.module.urllib.request, "urlopen", side_effect=error), + ): + with self.assertRaises(RuntimeError) as caught: + self.module.graphql("query", {}) + self.assertNotIn("secret", str(caught.exception)) + + def test_missing_project_is_disabled(self): + with ( + patch.dict(os.environ, {}, clear=True), + patch.object(self.module, "reconcile") as reconcile, + ): + self.module.main([]) + reconcile.assert_not_called() + + def test_configured_project_requires_token(self): + with patch.dict(os.environ, {"ASTRBOT_PROJECT_ID": "P"}, clear=True): + with self.assertRaisesRegex(ValueError, "ASTRBOT_PROJECT_TOKEN"): + self.module.main([]) + + def test_default_preview_and_explicit_apply(self): + env = {"ASTRBOT_PROJECT_ID": "P", "ASTRBOT_PROJECT_TOKEN": "secret"} + for args, apply in [([], False), (["--apply"], True)]: + with ( + self.subTest(args=args), + patch.dict(os.environ, env, clear=True), + patch.object(self.module, "reconcile", return_value=[]) as reconcile, + ): + self.module.main(args) + self.assertIs(reconcile.call_args.kwargs["apply"], apply) + + def test_status_map_and_legacy_names(self): + env = { + "ASTRBOT_PROJECT_ID": "P", + "ASTRBOT_PROJECT_TOKEN": "secret", + "ASTRBOT_PROJECT_STATUS_MAP": '{"Needs verification": "待验证"}', + "ASTRBOT_PROJECT_STATUS_OPEN": "待安排", + "ASTRBOT_PROJECT_STATUS_DONE": "已完成", + } + with ( + patch.dict(os.environ, env, clear=True), + patch.object(self.module, "reconcile", return_value=[]) as api, + ): + self.module.main([]) + names = api.call_args.kwargs["status_names"] + self.assertEqual(names["Todo"], "待安排") + self.assertEqual(names["Done"], "已完成") + self.assertEqual(names["Needs verification"], "待验证") + + def test_invalid_status_map_never_reconciles(self): + for value in [ + "[]", + '{"Typo":"x"}', + '{"Done":"Todo"}', + '{"Done":1}', + '{"Done":" "}', + ]: + env = { + "ASTRBOT_PROJECT_ID": "P", + "ASTRBOT_PROJECT_TOKEN": "secret", + "ASTRBOT_PROJECT_STATUS_MAP": value, + } + with ( + self.subTest(value=value), + patch.dict(os.environ, env, clear=True), + patch.object(self.module, "reconcile") as api, + ): + with self.assertRaises(ValueError): + self.module.main([]) + api.assert_not_called() + + def test_supported_events_and_subjects(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "event.json" + env = { + "ASTRBOT_PROJECT_ID": "P", + "ASTRBOT_PROJECT_TOKEN": "secret", + "GITHUB_EVENT_PATH": str(path), + "GITHUB_REPOSITORY": "AstrBotDevs/AstrBot", + "GITHUB_REF": "refs/heads/master", + "ASTRBOT_DEFAULT_BRANCH": "master", + } + for name, action, key in [ + ("issues", "opened", "issue"), + ("issues", "labeled", "issue"), + ("issues", "closed", "issue"), + ("issues", "reopened", "issue"), + ("pull_request_target", "closed", "pull_request"), + ("pull_request_target", "edited", "pull_request"), + ("pull_request_target", "synchronize", "pull_request"), + ("release", "published", None), + ("release", "deleted", None), + ("push", None, None), + ("schedule", None, None), + ("workflow_dispatch", None, None), + ]: + event = { + "repository": { + "full_name": "AstrBotDevs/AstrBot", + "default_branch": "master", + }, + "action": action, + } + if name == "schedule": + event = {} + if key: + event[key] = {"number": 42, "state": "outdated"} + path.write_text(json.dumps(event), encoding="utf-8") + with ( + self.subTest(name=name, action=action), + patch.dict( + os.environ, {**env, "GITHUB_EVENT_NAME": name}, clear=True + ), + patch.object( + self.module, "reconcile", return_value=[] + ) as reconcile, + ): + self.module.main([]) + self.assertEqual( + reconcile.call_args.kwargs["subject"], 42 if key else None + ) + self.assertFalse(reconcile.call_args.kwargs["apply"]) + + def test_untrusted_context_never_reconciles(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "event.json" + for name, action, repo, number, ref in [ + ( + "pull_request", + "opened", + "AstrBotDevs/AstrBot", + 42, + "refs/heads/master", + ), + ("issues", "deleted", "AstrBotDevs/AstrBot", 42, "refs/heads/master"), + ("issues", "opened", "attacker/fork", 42, "refs/heads/master"), + ("issues", "opened", "AstrBotDevs/AstrBot", True, "refs/heads/master"), + ("issues", "opened", "AstrBotDevs/AstrBot", 0, "refs/heads/master"), + ("issues", "opened", "AstrBotDevs/AstrBot", "42", "refs/heads/master"), + ( + "workflow_dispatch", + None, + "AstrBotDevs/AstrBot", + 42, + "refs/heads/untrusted", + ), + ("push", None, "AstrBotDevs/AstrBot", 42, "refs/heads/untrusted"), + ]: + path.write_text( + json.dumps( + { + "repository": { + "full_name": repo, + "default_branch": "master", + }, + "action": action, + "issue": {"number": number}, + } + ), + encoding="utf-8", + ) + env = { + "ASTRBOT_PROJECT_ID": "P", + "ASTRBOT_PROJECT_TOKEN": "secret", + "GITHUB_EVENT_NAME": name, + "GITHUB_EVENT_PATH": str(path), + "GITHUB_REPOSITORY": "AstrBotDevs/AstrBot", + "GITHUB_REF": ref, + } + with ( + self.subTest(name=name, action=action, number=number, ref=ref), + patch.dict(os.environ, env, clear=True), + patch.object(self.module, "reconcile") as reconcile, + ): + with self.assertRaises(ValueError): + self.module.main([]) + reconcile.assert_not_called() + + def test_schedule_uses_configured_default_branch(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "event.json" + path.write_text("{}", encoding="utf-8") + env = { + "ASTRBOT_PROJECT_ID": "P", + "ASTRBOT_PROJECT_TOKEN": "secret", + "ASTRBOT_DEFAULT_BRANCH": "development", + "GITHUB_EVENT_NAME": "schedule", + "GITHUB_EVENT_PATH": str(path), + "GITHUB_REPOSITORY": "AstrBotDevs/AstrBot", + "GITHUB_REF": "refs/heads/development", + } + with ( + patch.dict(os.environ, env, clear=True), + patch.object(self.module, "reconcile", return_value=[]) as reconcile, + ): + self.module.main([]) + reconcile.assert_called_once() + + +if __name__ == "__main__": + unittest.main() From 7f0e23030ddb046ab2502421c2bef31c398999e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sat, 31 Oct 2026 22:08:51 +0900 Subject: [PATCH 2/5] fix: recover missed Project sync events --- .github/PROJECT_SYNC.md | 9 ++- .github/workflows/project-sync.yml | 1 + scripts/sync_github_project.py | 23 ++++-- tests/test_project_delivery.py | 115 ++++++++++++++++++++++++++--- 4 files changed, 129 insertions(+), 19 deletions(-) diff --git a/.github/PROJECT_SYNC.md b/.github/PROJECT_SYNC.md index 91d2a011533..2a921f1bb36 100644 --- a/.github/PROJECT_SYNC.md +++ b/.github/PROJECT_SYNC.md @@ -25,8 +25,11 @@ must be explicitly selected. Sync never edits or deletes source Issues/PRs. to be contained in the earliest published stable release. Drafts/prereleases do not count. Populate PR links and actual release tag/URL, never guess a version. - Scan all open issues and all PRs. Also reconcile tracked closed items, linked - closed issues, and the current event subject; do not import unrelated closed - history. Skip archived items and draft issues. + closed issues, the current event subject, and all items closed on or after the + Project's creation time. This durable boundary recovers replaced/failed event + runs without importing unrelated items closed before the Project existed. For + an older Project, preview this catch-up set before enabling writes. Skip + archived items and draft issues. - Validate the Project schema/options and calculate all changes before writing; skip unchanged values and clear stale text. Paginate every GraphQL connection, reject stalled cursors, and serialize whole-project runs. @@ -92,7 +95,7 @@ next schedule reconciles current state. Remove `ASTRBOT_PROJECT_ID` to disable. - Never: commit secrets, check out PR head code in the privileged workflow, modify issue/PR state, delete project items, commit or push without permission. -Historical unrelated closed issues are intentionally not imported. Coordinate any +Unrelated items closed before Project creation are intentionally not imported. Coordinate any native Project automation that writes these same fields. GitHub Actions and live API validation require maintainer configuration after merge. diff --git a/.github/workflows/project-sync.yml b/.github/workflows/project-sync.yml index c1f72e46619..806b43bd8c5 100644 --- a/.github/workflows/project-sync.yml +++ b/.github/workflows/project-sync.yml @@ -23,6 +23,7 @@ permissions: contents: read # Every run reconciles the whole project; serialize snapshots, not just items. +# Pending runs can be replaced; full scans recover items closed since project creation. concurrency: group: project-sync-${{ github.repository }} cancel-in-progress: false diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py index 3f314204bde..d39f2240638 100644 --- a/scripts/sync_github_project.py +++ b/scripts/sync_github_project.py @@ -123,6 +123,8 @@ def decide(content, current, linked): ] elif state == "CLOSED": status = "Cancelled" if content.get("stateReason") == "NOT_PLANNED" else "Done" + elif status in {"Done", "Cancelled", "Closed unmerged"}: + status = "Todo" elif "status:needs-verification" in content.get("labels", []): status = "Needs verification" elif "status:needs-info" in content.get("labels", []): @@ -131,11 +133,7 @@ def decide(content, current, linked): status = "Needs verification" elif linked: status = "In progress" - elif status not in STATUS_OPTIONS or status in { - "Done", - "Cancelled", - "Closed unmerged", - }: + elif status not in STATUS_OPTIONS: status = "Todo" return {"Status": status} @@ -374,6 +372,15 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No for name in ("实现关联", "发布版本", "发布说明"): if fields.get(name, {}).get("dataType") != "TEXT": raise ValueError(f"Project {name} must be a text field") + metadata = graphql( + """query($project:ID!){node(id:$project){... on ProjectV2{createdAt}}}""", + {"project": project}, + ) + since = (metadata.get("node") or {}).get("createdAt") + if not isinstance(since, str) or not re.fullmatch( + r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", since + ): + raise ValueError("Project creation time is required for closed-item recovery") items = connection( """query($project:ID!,$cursor:String){node(id:$project){... on ProjectV2{ items(first:100,after:$cursor,archivedStates:[ARCHIVED,NOT_ARCHIVED]){nodes{ @@ -396,7 +403,7 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No variables = {"owner": owner, "name": name} issues = connection( """query($owner:String!,$name:String!,$states:[IssueState!],$cursor:String){repository(owner:$owner,name:$name){ - issues(first:100,after:$cursor,states:$states){nodes{__typename id number state stateReason + issues(first:100,after:$cursor,states:$states){nodes{__typename id number state stateReason closedAt labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}}} pageInfo{hasNextPage endCursor}}}}""", ("repository", "issues"), @@ -405,7 +412,7 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No ) prs = connection( """query($owner:String!,$name:String!,$states:[PullRequestState!],$cursor:String){repository(owner:$owner,name:$name){ - pullRequests(first:100,after:$cursor,states:$states){nodes{__typename id number state body url + pullRequests(first:100,after:$cursor,states:$states){nodes{__typename id number state body url closedAt mergeCommit{oid} closingIssuesReferences(first:100){nodes{number repository{nameWithOwner}} pageInfo{hasNextPage endCursor}} @@ -443,6 +450,7 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No or i["id"] in tracked or i["number"] == subject or i["number"] in linked + or (i.get("closedAt") or "") >= since ] issue_numbers = {i["number"] for i in candidates} associated_ids = { @@ -455,6 +463,7 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No or pr["id"] in tracked or pr["number"] == subject or pr["id"] in associated_ids + or (pr.get("closedAt") or "") >= since ) releases = connection( """query($owner:String!,$name:String!,$cursor:String){repository(owner:$owner,name:$name){ diff --git a/tests/test_project_delivery.py b/tests/test_project_delivery.py index ea4e9784852..ed80518d031 100644 --- a/tests/test_project_delivery.py +++ b/tests/test_project_delivery.py @@ -15,6 +15,10 @@ class DeliveryTests(unittest.TestCase): def setUp(self): + self.metadata = {"node": {"createdAt": "2026-10-01T00:00:00Z"}} + api = patch.object(sync, "graphql", return_value=self.metadata) + api.start() + self.addCleanup(api.stop) self.fields = [ { "name": name, @@ -53,14 +57,18 @@ def test_snapshot_preview_apply_and_second_run_idempotence(self): patch.object( sync, "graphql", - return_value={"addProjectV2ItemById": {"item": {"id": "I"}}}, + return_value={ + **self.metadata, + "addProjectV2ItemById": {"item": {"id": "I"}}, + }, ) as api, ): plan = sync.reconcile("P", "AstrBotDevs/AstrBot", apply=apply) self.assertEqual( plan[0]["changes"], {"Status": "Todo", "交付进度": "未关联实现"} ) - self.assertEqual(api.call_count, 3 if apply else 0) + self.assertEqual(api.call_count, 4 if apply else 1) + self.assertTrue(api.call_args_list[0].args[0].startswith("query")) item = { "id": "I", "content": self.issue, @@ -86,10 +94,11 @@ def test_snapshot_preview_apply_and_second_run_idempotence(self): ], ), patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), - patch.object(sync, "graphql") as api, + patch.object(sync, "graphql", return_value=self.metadata) as api, ): self.assertEqual(sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True), []) - api.assert_not_called() + api.assert_called_once() + self.assertTrue(api.call_args.args[0].startswith("query")) def test_snapshot_skips_archived_draft_foreign_and_old_closed(self): archived = {"id": "I", "content": self.issue, "isArchived": True} @@ -103,7 +112,13 @@ def test_snapshot_skips_archived_draft_foreign_and_old_closed(self): "content": {"__typename": "DraftIssue", "id": "DRAFT"}, "isArchived": False, } - closed = {**self.issue, "id": "OLD", "number": 2, "state": "CLOSED"} + closed = { + **self.issue, + "id": "OLD", + "number": 2, + "state": "CLOSED", + "closedAt": "2026-09-30T23:59:59Z", + } with ( patch.object( sync, @@ -117,10 +132,11 @@ def test_snapshot_skips_archived_draft_foreign_and_old_closed(self): ], ), patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), - patch.object(sync, "graphql") as api, + patch.object(sync, "graphql", return_value=self.metadata) as api, ): self.assertEqual(sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True), []) - api.assert_not_called() + api.assert_called_once() + self.assertTrue(api.call_args.args[0].startswith("query")) def test_reconciliation_explicitly_scans_closed_issues_and_merged_prs(self): with ( @@ -169,11 +185,12 @@ def test_late_read_failure_never_partially_applies_plan(self): ], ), patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), - patch.object(sync, "graphql") as api, + patch.object(sync, "graphql", return_value=self.metadata) as api, ): with self.assertRaisesRegex(RuntimeError, "read failed"): sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True) - api.assert_not_called() + api.assert_called_once() + self.assertTrue(api.call_args.args[0].startswith("query")) def test_closed_subject_is_added_using_current_state(self): closed = {**self.issue, "state": "CLOSED", "stateReason": "NOT_PLANNED"} @@ -280,6 +297,42 @@ def test_git_ancestry_errors_fail_closed(self): with self.assertRaises(ValueError): sync.ancestor("--bad-option", "refs/tags/v1") + def test_missing_recovery_boundary_fails_before_mutations(self): + for metadata in ( + {"node": None}, + {"node": {}}, + {"node": {"createdAt": "invalid"}}, + ): + with ( + self.subTest(metadata=metadata), + patch.object(sync, "connection", return_value=self.fields) as read, + patch.object(sync, "graphql", return_value=metadata) as api, + ): + with self.assertRaisesRegex(ValueError, "creation time"): + sync.reconcile("P", "AstrBotDevs/AstrBot", apply=True) + self.assertEqual(read.call_count, 1) + api.assert_called_once() + self.assertTrue(api.call_args.args[0].startswith("query")) + + def test_closed_recovery_includes_exact_boundary_but_excludes_older_items(self): + for closed_at, expected in [ + ("2026-10-01T00:00:00Z", {1}), + ("2026-09-30T23:59:59Z", set()), + ]: + issue = {**self.issue, "state": "CLOSED", "closedAt": closed_at} + pages = [self.fields, [], [issue], [], []] + if expected: + pages.append([]) + with ( + self.subTest(closed_at=closed_at), + patch.object(sync, "connection", side_effect=pages), + patch.object( + sync.subprocess, "run", return_value=Mock(stdout="a" * 40) + ), + ): + plan = sync.reconcile("P", "AstrBotDevs/AstrBot") + self.assertEqual({entry["number"] for entry in plan}, expected) + def test_reference_lines_ignore_incidental_and_foreign_mentions(self): body = ( "Mention #9 in passing\nRefs #12, #13\nFixes: AstrBotDevs/AstrBot#14\n" @@ -308,6 +361,50 @@ def test_decision_separates_acceptance_from_delivery(self): issue["stateReason"] = "COMPLETED" self.assertEqual(sync.decide(issue, {}, [])["Status"], "Done") + def test_reopened_terminal_issues_reset_before_linked_pr_inference(self): + issue = {"__typename": "Issue", "state": "OPEN", "labels": []} + for terminal in ("Done", "Cancelled", "Closed unmerged"): + for state in ("OPEN", "MERGED"): + with self.subTest(terminal=terminal, state=state): + self.assertEqual( + sync.decide(issue, {"Status": terminal}, [{"state": state}])[ + "Status" + ], + "Todo", + ) + + def test_full_scan_recovers_closed_items_without_their_event_subject(self): + issue = { + **self.issue, + "state": "CLOSED", + "closedAt": "2026-10-02T00:00:00Z", + "stateReason": "COMPLETED", + } + pr = { + "__typename": "PullRequest", + "id": "PR", + "number": 2, + "state": "CLOSED", + "closedAt": "2026-10-02T00:00:00Z", + "url": "pr", + } + for subject in (None, 999): + with ( + self.subTest(subject=subject), + patch.object( + sync, + "connection", + side_effect=[self.fields, [], [dict(issue)], [pr], [], []], + ), + patch.object( + sync.subprocess, "run", return_value=Mock(stdout="a" * 40) + ), + ): + plan = sync.reconcile("P", "AstrBotDevs/AstrBot", subject=subject) + self.assertEqual({entry["number"] for entry in plan}, {1, 2}) + self.assertEqual(plan[0]["changes"]["Status"], "Done") + self.assertEqual(plan[1]["changes"]["Status"], "Closed unmerged") + def test_explicit_labels_and_unmerged_pr(self): issue = { "__typename": "Issue", From 9fde0216ade6db06c97f55a5c928d385b32d11be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sat, 31 Oct 2026 22:24:05 +0900 Subject: [PATCH 3/5] fix: protect Project sync credentials --- .github/PROJECT_SYNC.md | 29 ++++++++++++++++++++++-- .github/workflows/project-sync-tests.yml | 4 ++-- .github/workflows/project-sync.yml | 8 ++++--- tests/test_sync_github_project.py | 25 ++++++++++++++++++++ 4 files changed, 59 insertions(+), 7 deletions(-) diff --git a/.github/PROJECT_SYNC.md b/.github/PROJECT_SYNC.md index 2a921f1bb36..640750d1001 100644 --- a/.github/PROJECT_SYNC.md +++ b/.github/PROJECT_SYNC.md @@ -62,8 +62,22 @@ Example map when an existing Project uses translated Status labels: {"In progress":"进行中","Needs verification":"待验证","Cancelled":"已取消","Closed unmerged":"已关闭未合入"} ``` -Set the Actions secret `ASTRBOT_PROJECT_TOKEN` to a credential with project write -access and read access to this repository's issues and pull requests. +Before enabling synchronization, create the `project-sync` GitHub Environment +under repository Settings → Environments. Select **Selected branches and tags** +and add exactly one **branch** rule for the default branch (`master` currently). +Do not allow tags, wildcard branches, or all protected branches. Use required +reviewers where available and limit who can change environment protection rules. +The workflow's inline branch check is defense in depth, not the credential boundary. + +Only after those rules are configured, add the **environment secret** +`ASTRBOT_PROJECT_ENV_TOKEN` with project write access and repository Issue/PR read +access. Never define this secret at repository or organization scope; remove any +old repository/organization `ASTRBOT_PROJECT_TOKEN` used for this integration. +The workflow maps the environment secret to the script's `ASTRBOT_PROJECT_TOKEN` +process variable; local runs continue using that process variable. No fallback to +the old secret exists. YAML cannot create or enforce these server-side rules. +If environment protection is unavailable, leave synchronization disabled. + For example, use a classic personal access token with the `project` scope, owned by an account that can edit the destination project. Honor any organization SSO authorization and token restrictions. The repository `GITHUB_TOKEN` is not @@ -71,6 +85,17 @@ used for project mutations. The Project must contain all five fields and options listed above. Do not use this credential in ordinary pull request test jobs. +Branch protection evaluates the triggering workflow ref, not the checked-out ref. +Release events use tag refs, and PR-target events against non-default branches may +therefore be rejected by this default-branch-only Environment. Do not add tag or +branch exceptions to bypass that restriction: the next default-branch push, +six-hour scheduled run, or default-branch manual dispatch reconciles their state. +Test that a non-default dispatch is denied before using a live credential. + +Both workflows pin checkout/setup-python to full commit SHAs verified against +their official repositories. Existing weekly Dependabot updates propose SHA +changes for review; keep the immutable pins when updating Actions. + To resolve an organization project's node ID, replace `PROJECT_NUMBER` with the number from its GitHub URL (not its node ID): diff --git a/.github/workflows/project-sync-tests.yml b/.github/workflows/project-sync-tests.yml index d4b9906c6f4..cf32ba58b96 100644 --- a/.github/workflows/project-sync-tests.yml +++ b/.github/workflows/project-sync-tests.yml @@ -24,10 +24,10 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - - uses: actions/setup-python@v7 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: '3.12' - name: Run network-free regression tests diff --git a/.github/workflows/project-sync.yml b/.github/workflows/project-sync.yml index 806b43bd8c5..3edcc12b3ef 100644 --- a/.github/workflows/project-sync.yml +++ b/.github/workflows/project-sync.yml @@ -31,6 +31,8 @@ concurrency: jobs: sync: if: github.repository == 'AstrBotDevs/AstrBot' && vars.ASTRBOT_PROJECT_ID != '' + # Configure this environment to allow only the default branch before adding secrets. + environment: project-sync runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -41,7 +43,7 @@ jobs: exit 1 # Never check out the PR head or a PR-controlled base branch with this token. - name: Check out trusted default branch - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event.repository.default_branch || github.ref_name }} persist-credentials: false @@ -51,7 +53,7 @@ jobs: sparse-checkout-cone-mode: false - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: '3.12' @@ -61,7 +63,7 @@ jobs: ASTRBOT_PROJECT_STATUS_OPEN: ${{ vars.ASTRBOT_PROJECT_STATUS_OPEN }} ASTRBOT_PROJECT_STATUS_DONE: ${{ vars.ASTRBOT_PROJECT_STATUS_DONE }} ASTRBOT_PROJECT_STATUS_MAP: ${{ vars.ASTRBOT_PROJECT_STATUS_MAP }} - ASTRBOT_PROJECT_TOKEN: ${{ secrets.ASTRBOT_PROJECT_TOKEN }} + ASTRBOT_PROJECT_TOKEN: ${{ secrets.ASTRBOT_PROJECT_ENV_TOKEN }} ASTRBOT_DEFAULT_BRANCH: ${{ github.event.repository.default_branch || github.ref_name }} APPLY_CHANGES: ${{ github.event_name != 'workflow_dispatch' || inputs.apply }} run: | diff --git a/tests/test_sync_github_project.py b/tests/test_sync_github_project.py index 19bfa61bf38..6dd6392f9db 100644 --- a/tests/test_sync_github_project.py +++ b/tests/test_sync_github_project.py @@ -4,6 +4,7 @@ import io import json import os +import re import tempfile import unittest import urllib.error @@ -264,5 +265,29 @@ def test_schedule_uses_configured_default_branch(self): reconcile.assert_called_once() +class WorkflowSecurityTests(unittest.TestCase): + def test_sync_job_requires_environment_before_any_steps(self): + workflow = ( + SCRIPT.parents[1] / ".github/workflows/project-sync.yml" + ).read_text() + job = workflow.split(" sync:\n", 1)[1] + self.assertIn(" environment: project-sync\n", job.split(" steps:", 1)[0]) + self.assertIn( + "ASTRBOT_PROJECT_TOKEN: ${{ secrets.ASTRBOT_PROJECT_ENV_TOKEN }}", job + ) + self.assertNotIn("secrets.ASTRBOT_PROJECT_TOKEN", job) + + def test_both_workflows_pin_all_actions_to_full_commit_ids(self): + for name in ("project-sync.yml", "project-sync-tests.yml"): + workflow = (SCRIPT.parents[1] / ".github/workflows" / name).read_text() + actions = re.findall(r"uses:\s+([^\s#]+)", workflow) + self.assertEqual(len(actions), 2) + for action in actions: + with self.subTest(workflow=name, action=action): + self.assertRegex( + action, r"^actions/(checkout|setup-python)@[0-9a-f]{40}$" + ) + + if __name__ == "__main__": unittest.main() From 6fa2ade1fe8d68306fa4bd5cfa94a0f1384aacc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sat, 31 Oct 2026 22:36:09 +0900 Subject: [PATCH 4/5] fix: handle Project sync failures in main --- scripts/sync_github_project.py | 23 +++++++++++++++-------- tests/test_sync_github_project.py | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py index d39f2240638..e25b755ab53 100644 --- a/scripts/sync_github_project.py +++ b/scripts/sync_github_project.py @@ -546,7 +546,7 @@ def main(argv=None): Raises: ValueError: Credentials or supported event context are missing or invalid. - RuntimeError: Synchronization fails. + SystemExit: Synchronization fails; report a sanitized error without a traceback. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--apply", action="store_true") @@ -635,13 +635,20 @@ def main(argv=None): not isinstance(v, str) or not v.strip() for v in status_names.values() ) or len(set(status_names.values())) != len(STATUS_OPTIONS): raise ValueError("Status names must be nonempty and distinct") - plan = reconcile( - project, - repository, - subject=subject, - apply=args.apply, - status_names=status_names, - ) + try: + plan = reconcile( + project, + repository, + subject=subject, + apply=args.apply, + status_names=status_names, + ) + except (RuntimeError, ValueError, OSError, subprocess.SubprocessError): + raise SystemExit( + "Project synchronization failed; check API access, Project schema, " + "pagination and full Git history. Rerun after correcting the cause; " + "some Project updates may already have been applied." + ) from None print( json.dumps({"apply": args.apply, "changes": plan}, ensure_ascii=False, indent=2) ) diff --git a/tests/test_sync_github_project.py b/tests/test_sync_github_project.py index 6dd6392f9db..ad3d83a86f1 100644 --- a/tests/test_sync_github_project.py +++ b/tests/test_sync_github_project.py @@ -15,6 +15,31 @@ class SyncProjectTests(unittest.TestCase): + def test_main_reports_sync_failures_without_raw_details(self): + failures = [ + RuntimeError("secret stalled cursor"), + ValueError("secret invalid ref"), + urllib.error.URLError("secret transport"), + TimeoutError("secret timeout"), + OSError("secret missing git"), + ] + for failure in failures: + with ( + self.subTest(failure=failure), + patch.dict( + os.environ, + {"ASTRBOT_PROJECT_ID": "P", "ASTRBOT_PROJECT_TOKEN": "secret"}, + clear=True, + ), + patch.object(self.module, "reconcile", side_effect=failure), + patch("sys.stdout", new_callable=io.StringIO) as output, + ): + with self.assertRaises(SystemExit) as caught: + self.module.main([]) + self.assertIn("Project synchronization failed", str(caught.exception)) + self.assertNotIn("secret", str(caught.exception)) + self.assertEqual(output.getvalue(), "") + def setUp(self): spec = importlib.util.spec_from_file_location("sync_github_project", SCRIPT) self.module = importlib.util.module_from_spec(spec) From b84ed54d57549a615c24535a74a7acce19c04a79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sat, 31 Oct 2026 23:31:49 +0900 Subject: [PATCH 5/5] perf: bound Project sync event reads --- .github/PROJECT_SYNC.md | 45 +- .github/workflows/project-sync-tests.yml | 3 + .github/workflows/project-sync.yml | 4 - scripts/sync_github_project.py | 547 +++++++++++++++++------ tests/test_project_delivery.py | 46 +- tests/test_project_events.py | 203 +++++++++ tests/test_sync_github_project.py | 20 +- 7 files changed, 682 insertions(+), 186 deletions(-) create mode 100644 tests/test_project_events.py diff --git a/.github/PROJECT_SYNC.md b/.github/PROJECT_SYNC.md index 640750d1001..caab003bcb0 100644 --- a/.github/PROJECT_SYNC.md +++ b/.github/PROJECT_SYNC.md @@ -2,10 +2,10 @@ ## Behavior -This follows Peach's event-driven plus periodic reconciliation approach. Every run -builds a read-only snapshot and full diff first. Events and the six-hour schedule -apply changes; manual dispatch and local runs preview by default. Manual `apply` -must be explicitly selected. Sync never edits or deletes source Issues/PRs. +Each run builds a read-only plan first. Issue/PR events reconcile only their direct +associations; six-hour schedule and manual dispatch run full scans. Manual dispatch +and local runs preview by default; manual `apply` must be selected. Sync never edits +or deletes source Issues/PRs. - Required single-select `Status`: `Todo`, `In progress`, `Needs verification`, `Done`, `Cancelled`, `Closed unmerged`. Required single-select `交付进度`: @@ -16,23 +16,35 @@ must be explicitly selected. Sync never edits or deletes source Issues/PRs. reason is NOT_PLANNED (Cancelled). Closed unmerged PRs are not Done. Reopened terminal items return to Todo. Preserve manually selected nonterminal status without implementation. Optional labels `status:needs-info` and - `status:needs-verification` override inferred open-issue progress. + `status:needs-verification` override inferred open-issue progress. `needs-info` + intentionally wins in Status even with a merged PR (Todo + 已合入待发布); the + fields represent acceptance and delivery separately. - Associate same-repository issues using closing references or standalone `Ref(s)`, `Fix(es/ed)`, `Close(d)`, or `Resolve(s/d)` lines. Incidental mentions, - code fences, and cross-repository references do not establish a link. + code fences, and cross-repository references do not establish a link. A reference + line containing `Fixes #12, and see #99 for context` links both same-repo issues; + keep unrelated numbers off reference lines to avoid unintended associations. - Delivery requires every associated implementation PR to be merged, every merge commit to be reachable from the trusted default branch, and every such commit to be contained in the earliest published stable release. Drafts/prereleases do not count. Populate PR links and actual release tag/URL, never guess a version. -- Scan all open issues and all PRs. Also reconcile tracked closed items, linked - closed issues, the current event subject, and all items closed on or after the - Project's creation time. This durable boundary recovers replaced/failed event - runs without importing unrelated items closed before the Project existed. For - an older Project, preview this catch-up set before enabling writes. Skip - archived items and draft issues. +- Issue/PR lifecycle events read only their subject and bounded linked issues/PRs, + including old/new body references and previously stored implementation links. + They do not scan repository Issues, PRs, Project items, or releases. Six-hour + scheduled and manual runs do full reconciliation; changes discovered only by + broad push/release scans wait until the next scheduled or manual run. +- Full scans include open issues/all PRs, tracked and linked closed issues, and + all items closed on or after Project creation. This durable boundary recovers + replaced/failed events without unrelated older closed history. For an older + Project, preview catch-up before writes. Skip archived items and draft issues. +- Release version verification runs only during full scans. Event runs defer it to + the next full scan, while preserving an existing published result when its + implementation links are unchanged. - Validate the Project schema/options and calculate all changes before writing; skip unchanged values and clear stale text. Paginate every GraphQL connection, - reject stalled cursors, and serialize whole-project runs. + reject stalled cursors, and serialize runs. Apply mode prints the plan first; + on failure it reports confirmed, outcome-unknown and unattempted mutation counts, + with affected item/field, so partial writes can be reconciled. - Privileged jobs run trusted default-branch code only, use full Git history/tags, and never execute PR code. PR tests use no Project secret. @@ -41,6 +53,7 @@ Run offline tests and checks: ```sh python -I tests/test_sync_github_project.py -v python -I tests/test_project_delivery.py -v +python -I tests/test_project_events.py -v uv run ruff format --check scripts/sync_github_project.py tests/test_sync_github_project.py tests/test_project_delivery.py uv run ruff check scripts/sync_github_project.py ``` @@ -130,9 +143,3 @@ GitHub's official "Using the API to manage Projects" documentation describes ProjectV2 field lookup, `addProjectV2ItemById` (including existing-item reuse), and `updateProjectV2ItemFieldValue`: https://docs.github.com/en/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects - -Peach reference: [Issue #268](https://github.com/peach-mitao/peach/issues/268), -[Project Board workflow](https://github.com/peach-mitao/peach/blob/master/.github/workflows/project-board.yml), -and [reconciler](https://github.com/peach-mitao/peach/blob/master/scripts/project_board.py). -This implementation adopts event/schedule/manual reconciliation and delivery -evidence, not Peach's unrelated migration/alias configuration. diff --git a/.github/workflows/project-sync-tests.yml b/.github/workflows/project-sync-tests.yml index cf32ba58b96..0b44f7fbbf3 100644 --- a/.github/workflows/project-sync-tests.yml +++ b/.github/workflows/project-sync-tests.yml @@ -7,6 +7,7 @@ on: - 'scripts/sync_github_project.py' - 'tests/test_sync_github_project.py' - 'tests/test_project_delivery.py' + - 'tests/test_project_events.py' push: branches: [master] paths: @@ -14,6 +15,7 @@ on: - 'scripts/sync_github_project.py' - 'tests/test_sync_github_project.py' - 'tests/test_project_delivery.py' + - 'tests/test_project_events.py' workflow_dispatch: permissions: @@ -34,3 +36,4 @@ jobs: run: | python -I tests/test_sync_github_project.py -v python -I tests/test_project_delivery.py -v + python -I tests/test_project_events.py -v diff --git a/.github/workflows/project-sync.yml b/.github/workflows/project-sync.yml index 3edcc12b3ef..cae724a1934 100644 --- a/.github/workflows/project-sync.yml +++ b/.github/workflows/project-sync.yml @@ -5,10 +5,6 @@ on: types: [opened, reopened, closed, labeled, unlabeled, edited] pull_request_target: types: [opened, reopened, closed, edited, synchronize, ready_for_review, converted_to_draft] - release: - types: [published, edited, deleted] - push: - branches: [master] schedule: - cron: '17 */6 * * *' workflow_dispatch: diff --git a/scripts/sync_github_project.py b/scripts/sync_github_project.py index e25b755ab53..21ad26a155e 100644 --- a/scripts/sync_github_project.py +++ b/scripts/sync_github_project.py @@ -240,29 +240,41 @@ def apply_plan(project, fields, plan, *, apply=False): plan: Source IDs, existing item IDs and changed values. apply: Explicit permission to write. """ + print(json.dumps({"apply": apply, "plan": plan}, ensure_ascii=False), flush=True) if not apply: return + total = sum(len(entry["changes"]) + (not entry["item"]) for entry in plan) + confirmed = 0 for entry in plan: item = entry["item"] if not item: - result = graphql( - """mutation($project: ID!, $content: ID!) { - addProjectV2ItemById(input: {projectId:$project, contentId:$content}) { item { id } } - }""", - {"project": project, "content": entry["content"]}, - ) - item = result["addProjectV2ItemById"]["item"]["id"] + try: + result = graphql( + """mutation($project: ID!, $content: ID!) { + addProjectV2ItemById(input: {projectId:$project, contentId:$content}) { item { id } } + }""", + {"project": project, "content": entry["content"]}, + ) + item = result["addProjectV2ItemById"]["item"]["id"] + except (RuntimeError, ValueError, OSError, KeyError, TypeError): + print( + json.dumps( + { + "confirmed": confirmed, + "unknown": 1, + "unattempted": total - confirmed - 1, + "number": entry["number"], + "field": "addProjectItem", + } + ), + flush=True, + ) + raise + confirmed += 1 for name, value in entry["changes"].items(): field = fields[name] variables = {"project": project, "item": item, "field": field["id"]} - if value == "": - graphql( - """mutation($project:ID!,$item:ID!,$field:ID!){ - clearProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field}){projectV2Item{id}} - }""", - variables, - ) - else: + if value != "": variables["value"] = ( { "singleSelectOptionId": next( @@ -272,12 +284,40 @@ def apply_plan(project, fields, plan, *, apply=False): if "options" in field else {"text": value} ) - graphql( - """mutation($project:ID!,$item:ID!,$field:ID!,$value:ProjectV2FieldValue!){ + try: + if value == "": + graphql( + """mutation($project:ID!,$item:ID!,$field:ID!){ + clearProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field}){projectV2Item{id}} + }""", + variables, + ) + else: + graphql( + """mutation($project:ID!,$item:ID!,$field:ID!,$value:ProjectV2FieldValue!){ updateProjectV2ItemFieldValue(input:{projectId:$project,itemId:$item,fieldId:$field,value:$value}){projectV2Item{id}} - }""", - variables, + }""", + variables, + ) + except (RuntimeError, ValueError, OSError): + print( + json.dumps( + { + "confirmed": confirmed, + "unknown": 1, + "unattempted": total - confirmed - 1, + "number": entry["number"], + "field": name, + }, + ensure_ascii=False, + ), + flush=True, ) + raise + confirmed += 1 + print( + json.dumps({"confirmed": confirmed, "unknown": 0, "unattempted": 0}), flush=True + ) def graphql(query, variables): @@ -321,7 +361,201 @@ def graphql(query, variables): return result["data"] -def reconcile(project, repository, *, subject=None, apply=False, status_names=None): +def read_subject(repository, number): + """Read current source state, memberships and direct association metadata. + + Args: + repository: Allowed owner/name. + number: Issue or pull request number. + + Returns: + Current source item with fully paginated association metadata. + + Raises: + ValueError: The source is not an accessible Issue or PullRequest. + """ + owner, name = repository.split("/") + membership = """projectItems(first:100,includeArchived:true){nodes{ + id isArchived project{id} + fieldValues(first:100){nodes{ + ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} + ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} + }pageInfo{hasNextPage endCursor}} + }pageInfo{hasNextPage endCursor}}""" + query = """query($owner:String!,$name:String!,$number:Int!){ + repository(owner:$owner,name:$name){issueOrPullRequest(number:$number){ + __typename + ... on Issue {id number issueState:state stateReason closedAt + labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}} + timelineItems(first:100,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{ + ... on CrossReferencedEvent{source{__typename + ... on PullRequest{number repository{nameWithOwner}}}} + }pageInfo{hasNextPage endCursor}} MEMBERSHIP} + ... on PullRequest {id number pullRequestState:state closedAt body url mergeCommit{oid} + closingIssuesReferences(first:100){nodes{number repository{nameWithOwner}} + pageInfo{hasNextPage endCursor}} MEMBERSHIP} + }} + }""".replace("MEMBERSHIP", membership) + result = graphql(query, {"owner": owner, "name": name, "number": number}) + content = (result.get("repository") or {}).get("issueOrPullRequest") + if not content or content.get("__typename") not in {"Issue", "PullRequest"}: + raise ValueError("Source must be an accessible issue or pull request") + kind = content["__typename"] + content["state"] = content.pop( + "issueState" if kind == "Issue" else "pullRequestState" + ) + if content["state"] not in ( + {"OPEN", "CLOSED"} if kind == "Issue" else {"OPEN", "CLOSED", "MERGED"} + ): + raise ValueError("Unexpected source state") + for field, selection in { + "projectItems": "projectItems(first:100,after:$cursor,includeArchived:true){nodes{id isArchived project{id} fieldValues(first:100){nodes{... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}}}pageInfo{hasNextPage endCursor}}}pageInfo{hasNextPage endCursor}}", + **( + { + "timelineItems": "timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{source{__typename ... on PullRequest{number repository{nameWithOwner}}}}}pageInfo{hasNextPage endCursor}}" + } + if kind == "Issue" + else { + "closingIssuesReferences": "closingIssuesReferences(first:100,after:$cursor){nodes{number repository{nameWithOwner}}pageInfo{hasNextPage endCursor}}" + } + ), + }.items(): + content[field] = connection( + "query($id:ID!,$cursor:String){node(id:$id){... on " + + kind + + "{" + + selection + + "}}}", + ("node", field), + initial=content[field], + id=content["id"], + ) + return content + + +def event_snapshot(project, repository, subject, event): + """Read the subject and one hop, leaving exhaustive discovery to scheduled runs. + + Args: + project: Destination ProjectV2 ID. + repository: Allowed owner/name. + subject: Event subject number. + event: Webhook metadata used only for previous-body association hints. + + Returns: + Candidates, existing memberships, and current implementation associations. + """ + primary = read_subject(repository, subject) + related = set() + if primary["__typename"] == "Issue": + related.update( + source["number"] + for entry in primary["timelineItems"] + if (source := entry.get("source")) + and source.get("__typename") == "PullRequest" + and source["repository"]["nameWithOwner"].casefold() + == repository.casefold() + ) + for item in primary["projectItems"]: + if item["project"]["id"] != project: + continue + for field in item["fieldValues"]: + if field.get("field", {}).get("name") != "实现关联": + continue + for owner_repo, number in re.findall( + r"https://github\.com/([\w.-]+/[\w.-]+)/pull/([0-9]+)", + field.get("text", ""), + re.I, + ): + if owner_repo.casefold() == repository.casefold(): + related.add(int(number)) + else: + related.update( + issue["number"] + for issue in primary["closingIssuesReferences"] + if issue["repository"]["nameWithOwner"].casefold() == repository.casefold() + ) + related |= references(primary.get("body"), repository) + related |= references( + event.get("changes", {}).get("body", {}).get("from"), repository + ) + for item in primary["projectItems"]: + if item["project"]["id"] != project: + continue + for field in item["fieldValues"]: + if field.get("field", {}).get("name") != "实现关联": + continue + for owner_repo, number in re.findall( + r"https://github\.com/([\w.-]+/[\w.-]+)/pull/([0-9]+)", + field.get("text", ""), + re.I, + ): + if owner_repo.casefold() == repository.casefold(): + related.add(int(number)) + # Keep the traversal bounded: read neighbours but never recursively expand them. + contents = [ + primary, + *(read_subject(repository, number) for number in sorted(related - {subject})), + ] + seen = {content["id"] for content in contents} + # An edited PR can remove an old Issue link; follow that Issue's direct PR links once + # so the removed relationship is also reconciled without scanning the repository. + for content in tuple(contents): + if content["__typename"] != "Issue": + continue + linked_numbers = { + entry["source"]["number"] + for entry in content["timelineItems"] + if entry.get("source", {}).get("__typename") == "PullRequest" + and entry["source"]["repository"]["nameWithOwner"].casefold() + == repository.casefold() + } + for item in content["projectItems"]: + if item["project"]["id"] != project: + continue + for field in item["fieldValues"]: + if field.get("field", {}).get("name") == "实现关联": + linked_numbers.update( + int(number) + for owner_repo, number in re.findall( + r"https://github\.com/([\w.-]+/[\w.-]+)/pull/([0-9]+)", + field.get("text", ""), + re.I, + ) + if owner_repo.casefold() == repository.casefold() + ) + for number in sorted(linked_numbers): + if not any( + item["__typename"] == "PullRequest" and item["number"] == number + for item in contents + ): + pr = read_subject(repository, number) + if pr["id"] not in seen: + contents.append(pr) + seen.add(pr["id"]) + tracked, linked = {}, {} + for content in contents: + memberships = content["projectItems"] + for item in memberships: + if item["project"]["id"] == project: + tracked[content["id"]] = item + if content["__typename"] != "PullRequest" or content["state"] == "CLOSED": + continue + closing = content["closingIssuesReferences"] + numbers = { + i["number"] + for i in closing + if i["repository"]["nameWithOwner"].casefold() == repository.casefold() + } + numbers |= references(content.get("body"), repository) + for number in numbers: + linked.setdefault(number, []).append(content) + return contents, tracked, linked + + +def reconcile( + project, repository, *, subject=None, apply=False, status_names=None, event=None +): """Plan a complete snapshot before performing any Project mutations. Args: @@ -372,106 +606,116 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No for name in ("实现关联", "发布版本", "发布说明"): if fields.get(name, {}).get("dataType") != "TEXT": raise ValueError(f"Project {name} must be a text field") - metadata = graphql( - """query($project:ID!){node(id:$project){... on ProjectV2{createdAt}}}""", - {"project": project}, - ) - since = (metadata.get("node") or {}).get("createdAt") - if not isinstance(since, str) or not re.fullmatch( - r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", since - ): - raise ValueError("Project creation time is required for closed-item recovery") - items = connection( - """query($project:ID!,$cursor:String){node(id:$project){... on ProjectV2{ - items(first:100,after:$cursor,archivedStates:[ARCHIVED,NOT_ARCHIVED]){nodes{ - id isArchived content{__typename ... on Issue{id} ... on PullRequest{id}} - fieldValues(first:100){nodes{ - ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} - ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} - }pageInfo{hasNextPage endCursor}} - }pageInfo{hasNextPage endCursor}}}}}""", - ("node", "items"), - project=project, - ) - tracked = { - item["content"]["id"]: item - for item in items - if item.get("content") - and item["content"]["__typename"] in {"Issue", "PullRequest"} - } - owner, name = repository.split("/") - variables = {"owner": owner, "name": name} - issues = connection( - """query($owner:String!,$name:String!,$states:[IssueState!],$cursor:String){repository(owner:$owner,name:$name){ - issues(first:100,after:$cursor,states:$states){nodes{__typename id number state stateReason closedAt - labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}}} - pageInfo{hasNextPage endCursor}}}}""", - ("repository", "issues"), - states=["OPEN", "CLOSED"], - **variables, - ) - prs = connection( - """query($owner:String!,$name:String!,$states:[PullRequestState!],$cursor:String){repository(owner:$owner,name:$name){ - pullRequests(first:100,after:$cursor,states:$states){nodes{__typename id number state body url closedAt - mergeCommit{oid} - closingIssuesReferences(first:100){nodes{number repository{nameWithOwner}} - pageInfo{hasNextPage endCursor}} - }pageInfo{hasNextPage endCursor}}}}""", - ("repository", "pullRequests"), - states=["OPEN", "CLOSED", "MERGED"], - **variables, - ) - linked = {} - for pr in prs: - if pr["state"] not in {"OPEN", "MERGED", "CLOSED"}: - raise ValueError("Unexpected pull request state") - if pr["state"] == "CLOSED": - continue - closing = connection( - """query($id:ID!,$cursor:String){node(id:$id){... on PullRequest{ - closingIssuesReferences(first:100,after:$cursor){nodes{number repository{nameWithOwner}} - pageInfo{hasNextPage endCursor}}}}}""", - ("node", "closingIssuesReferences"), - initial=pr["closingIssuesReferences"], - id=pr["id"], + if subject is not None: + candidates, tracked, linked = event_snapshot( + project, repository, subject, event or {} ) - numbers = { - issue["number"] - for issue in closing - if issue["repository"]["nameWithOwner"].casefold() == repository.casefold() + else: + metadata = graphql( + """query($project:ID!){node(id:$project){... on ProjectV2{createdAt}}}""", + {"project": project}, + ) + since = (metadata.get("node") or {}).get("createdAt") + if not isinstance(since, str) or not re.fullmatch( + r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", since + ): + raise ValueError( + "Project creation time is required for closed-item recovery" + ) + items = connection( + """query($project:ID!,$cursor:String){node(id:$project){... on ProjectV2{ + items(first:100,after:$cursor,archivedStates:[ARCHIVED,NOT_ARCHIVED]){nodes{ + id isArchived content{__typename ... on Issue{id} ... on PullRequest{id}} + fieldValues(first:100){nodes{ + ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} + ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} + }pageInfo{hasNextPage endCursor}} + }pageInfo{hasNextPage endCursor}}}}}""", + ("node", "items"), + project=project, + ) + tracked = { + item["content"]["id"]: item + for item in items + if item.get("content") + and item["content"]["__typename"] in {"Issue", "PullRequest"} } - numbers |= references(pr.get("body"), repository) - for number in numbers: - linked.setdefault(number, []).append(pr) - candidates = [ - i - for i in issues - if i["state"] == "OPEN" - or i["id"] in tracked - or i["number"] == subject - or i["number"] in linked - or (i.get("closedAt") or "") >= since - ] - issue_numbers = {i["number"] for i in candidates} - associated_ids = { - pr["id"] for number in issue_numbers for pr in linked.get(number, []) - } - candidates.extend( - pr - for pr in prs - if pr["state"] == "OPEN" - or pr["id"] in tracked - or pr["number"] == subject - or pr["id"] in associated_ids - or (pr.get("closedAt") or "") >= since - ) - releases = connection( - """query($owner:String!,$name:String!,$cursor:String){repository(owner:$owner,name:$name){ - releases(first:100,after:$cursor){nodes{tagName url publishedAt isDraft isPrerelease} - pageInfo{hasNextPage endCursor}}}}""", - ("repository", "releases"), - **variables, - ) + owner, name = repository.split("/") + variables = {"owner": owner, "name": name} + issues = connection( + """query($owner:String!,$name:String!,$states:[IssueState!],$cursor:String){repository(owner:$owner,name:$name){ + issues(first:100,after:$cursor,states:$states){nodes{__typename id number state stateReason closedAt + labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}}} + pageInfo{hasNextPage endCursor}}}}""", + ("repository", "issues"), + states=["OPEN", "CLOSED"], + **variables, + ) + prs = connection( + """query($owner:String!,$name:String!,$states:[PullRequestState!],$cursor:String){repository(owner:$owner,name:$name){ + pullRequests(first:100,after:$cursor,states:$states){nodes{__typename id number state body url closedAt + mergeCommit{oid} + closingIssuesReferences(first:100){nodes{number repository{nameWithOwner}} + pageInfo{hasNextPage endCursor}} + }pageInfo{hasNextPage endCursor}}}}""", + ("repository", "pullRequests"), + states=["OPEN", "CLOSED", "MERGED"], + **variables, + ) + linked = {} + for pr in prs: + if pr["state"] not in {"OPEN", "MERGED", "CLOSED"}: + raise ValueError("Unexpected pull request state") + if pr["state"] == "CLOSED": + continue + closing = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on PullRequest{ + closingIssuesReferences(first:100,after:$cursor){nodes{number repository{nameWithOwner}} + pageInfo{hasNextPage endCursor}}}}}""", + ("node", "closingIssuesReferences"), + initial=pr["closingIssuesReferences"], + id=pr["id"], + ) + numbers = { + issue["number"] + for issue in closing + if issue["repository"]["nameWithOwner"].casefold() + == repository.casefold() + } + numbers |= references(pr.get("body"), repository) + for number in numbers: + linked.setdefault(number, []).append(pr) + candidates = [ + i + for i in issues + if i["state"] == "OPEN" + or i["id"] in tracked + or i["number"] == subject + or i["number"] in linked + or (i.get("closedAt") or "") >= since + ] + issue_numbers = {i["number"] for i in candidates} + associated_ids = { + pr["id"] for number in issue_numbers for pr in linked.get(number, []) + } + candidates.extend( + pr + for pr in prs + if pr["state"] == "OPEN" + or pr["id"] in tracked + or pr["number"] == subject + or pr["id"] in associated_ids + or (pr.get("closedAt") or "") >= since + ) + releases = [] + if subject is None: + releases = connection( + """query($owner:String!,$name:String!,$cursor:String){repository(owner:$owner,name:$name){ + releases(first:100,after:$cursor){nodes{tagName url publishedAt isDraft isPrerelease} + pageInfo{hasNextPage endCursor}}}}""", + ("repository", "releases"), + **variables, + ) mainline = subprocess.run( ["git", "rev-parse", "HEAD"], cwd=ROOT, @@ -488,26 +732,30 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No if content["__typename"] == "Issue": if content["state"] not in {"OPEN", "CLOSED"}: raise ValueError("Unexpected issue state") - labels = connection( - """query($id:ID!,$cursor:String){node(id:$id){... on Issue{labels(first:100,after:$cursor){ - nodes{name}pageInfo{hasNextPage endCursor}}}}}""", - ("node", "labels"), - initial=content["labels"], - id=content["id"], - ) + labels = content["labels"] + if isinstance(labels, dict): + labels = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on Issue{labels(first:100,after:$cursor){ + nodes{name}pageInfo{hasNextPage endCursor}}}}}""", + ("node", "labels"), + initial=labels, + id=content["id"], + ) content["labels"] = [label["name"] for label in labels] current = {} if item: - values = connection( - """query($id:ID!,$cursor:String){node(id:$id){... on ProjectV2Item{ - fieldValues(first:100,after:$cursor){nodes{ - ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} - ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} - }pageInfo{hasNextPage endCursor}}}}}""", - ("node", "fieldValues"), - initial=item["fieldValues"], - id=item["id"], - ) + values = item["fieldValues"] + if isinstance(values, dict): + values = connection( + """query($id:ID!,$cursor:String){node(id:$id){... on ProjectV2Item{ + fieldValues(first:100,after:$cursor){nodes{ + ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}} + ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}} + }pageInfo{hasNextPage endCursor}}}}}""", + ("node", "fieldValues"), + initial=values, + id=item["id"], + ) current = { v["field"]["name"]: v.get("name", v.get("text", "")) for v in values @@ -523,6 +771,27 @@ def reconcile(project, repository, *, subject=None, apply=False, status_names=No desired = delivery( content, canonical, linked.get(content["number"], []), releases, mainline ) + if subject is not None: + if ( + current.get("交付进度") == "已发布" + and current.get("实现关联") == desired["实现关联"] + ): + desired["交付进度"] = current["交付进度"] + desired["发布版本"] = current.get("发布版本", "") + desired["发布说明"] = current.get("发布说明", "") + else: + desired["交付进度"] = ( + "已合入待发布" + if any( + pr["state"] == "MERGED" + for pr in linked.get(content["number"], []) + ) + else "尚未合入" + if desired["实现关联"] + else "未关联实现" + ) + desired["发布版本"] = "" + desired["发布说明"] = "" desired["Status"] = status_names[desired["Status"]] changes = {k: v for k, v in desired.items() if current.get(k, "") != v} if changes or not item: @@ -563,6 +832,7 @@ def main(argv=None): if repository != "AstrBotDevs/AstrBot": raise ValueError("Unexpected repository") subject = None + event = {} event_name = os.environ.get("GITHUB_EVENT_NAME") if event_name: allowed = { @@ -583,8 +853,6 @@ def main(argv=None): "ready_for_review", "converted_to_draft", }, - "release": {"published", "edited", "deleted"}, - "push": None, "schedule": None, "workflow_dispatch": None, } @@ -605,10 +873,10 @@ def main(argv=None): ) default_ref = f"refs/heads/{default_branch}" if ( - event_name in {"push", "workflow_dispatch", "schedule"} + event_name in {"workflow_dispatch", "schedule"} and os.environ.get("GITHUB_REF") != default_ref ): - raise ValueError("Push and manual runs require the default branch") + raise ValueError("Manual runs require the default branch") if ( allowed[event_name] is not None and event.get("action") not in allowed[event_name] @@ -642,6 +910,7 @@ def main(argv=None): subject=subject, apply=args.apply, status_names=status_names, + event=event, ) except (RuntimeError, ValueError, OSError, subprocess.SubprocessError): raise SystemExit( diff --git a/tests/test_project_delivery.py b/tests/test_project_delivery.py index ed80518d031..8520d049979 100644 --- a/tests/test_project_delivery.py +++ b/tests/test_project_delivery.py @@ -193,11 +193,15 @@ def test_late_read_failure_never_partially_applies_plan(self): self.assertTrue(api.call_args.args[0].startswith("query")) def test_closed_subject_is_added_using_current_state(self): - closed = {**self.issue, "state": "CLOSED", "stateReason": "NOT_PLANNED"} + closed = { + **self.issue, + "state": "CLOSED", + "stateReason": "NOT_PLANNED", + "labels": [], + } with ( - patch.object( - sync, "connection", side_effect=[self.fields, [], [closed], [], [], []] - ), + patch.object(sync, "connection", return_value=self.fields), + patch.object(sync, "event_snapshot", return_value=([closed], {}, {})), patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), ): plan = sync.reconcile("P", "AstrBotDevs/AstrBot", subject=1) @@ -341,6 +345,12 @@ def test_reference_lines_ignore_incidental_and_foreign_mentions(self): "```\nRefs #99\n```\n" ) self.assertEqual(sync.references(body, "AstrBotDevs/AstrBot"), {12, 13, 14, 15}) + self.assertEqual( + sync.references( + "Fixes #12, and see #99 for context", "AstrBotDevs/AstrBot" + ), + {12, 99}, + ) def test_decision_separates_acceptance_from_delivery(self): issue = {"__typename": "Issue", "state": "OPEN", "labels": []} @@ -388,22 +398,18 @@ def test_full_scan_recovers_closed_items_without_their_event_subject(self): "closedAt": "2026-10-02T00:00:00Z", "url": "pr", } - for subject in (None, 999): - with ( - self.subTest(subject=subject), - patch.object( - sync, - "connection", - side_effect=[self.fields, [], [dict(issue)], [pr], [], []], - ), - patch.object( - sync.subprocess, "run", return_value=Mock(stdout="a" * 40) - ), - ): - plan = sync.reconcile("P", "AstrBotDevs/AstrBot", subject=subject) - self.assertEqual({entry["number"] for entry in plan}, {1, 2}) - self.assertEqual(plan[0]["changes"]["Status"], "Done") - self.assertEqual(plan[1]["changes"]["Status"], "Closed unmerged") + with ( + patch.object( + sync, + "connection", + side_effect=[self.fields, [], [dict(issue)], [pr], [], []], + ), + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + ): + plan = sync.reconcile("P", "AstrBotDevs/AstrBot") + self.assertEqual({entry["number"] for entry in plan}, {1, 2}) + self.assertEqual(plan[0]["changes"]["Status"], "Done") + self.assertEqual(plan[1]["changes"]["Status"], "Closed unmerged") def test_explicit_labels_and_unmerged_pr(self): issue = { diff --git a/tests/test_project_events.py b/tests/test_project_events.py new file mode 100644 index 00000000000..442d5825c19 --- /dev/null +++ b/tests/test_project_events.py @@ -0,0 +1,203 @@ +"""Bounded event reads and mutation failure accounting.""" + +import importlib.util +import io +import json +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +SPEC = importlib.util.spec_from_file_location( + "project_events", + Path(__file__).resolve().parents[1] / "scripts/sync_github_project.py", +) +sync = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(sync) + + +class EventTests(unittest.TestCase): + def setUp(self): + self.page = {"nodes": [], "pageInfo": {"hasNextPage": False, "endCursor": None}} + self.fields = [ + { + "name": name, + "id": name, + "options": [{"name": value, "id": value} for value in values], + } + for name, values in [ + ("Status", sync.STATUS_OPTIONS), + ("交付进度", sync.DELIVERY_OPTIONS), + ] + ] + [ + {"name": name, "id": name, "dataType": "TEXT"} + for name in ("实现关联", "发布版本", "发布说明") + ] + self.issue = { + "__typename": "Issue", + "id": "I", + "number": 1, + "state": "OPEN", + "labels": [], + "projectItems": [], + "timelineItems": [], + } + self.pr = { + "__typename": "PullRequest", + "id": "PR", + "number": 2, + "state": "OPEN", + "body": "Refs #1", + "url": "https://github.com/AstrBotDevs/AstrBot/pull/2", + "projectItems": [], + "closingIssuesReferences": [], + } + + def test_issue_event_reads_only_subject_and_one_hop(self): + issue = { + **self.issue, + "timelineItems": [ + { + "source": { + "__typename": "PullRequest", + "number": 2, + "repository": {"nameWithOwner": "AstrBotDevs/AstrBot"}, + } + } + ], + } + with patch.object(sync, "read_subject", side_effect=[issue, self.pr]) as read: + candidates, tracked, linked = sync.event_snapshot( + "P", "AstrBotDevs/AstrBot", 1, {} + ) + self.assertEqual({x["number"] for x in candidates}, {1, 2}) + self.assertEqual(linked[1], [self.pr]) + self.assertEqual(read.call_count, 2) + self.assertEqual(tracked, {}) + + def test_pr_edit_refreshes_old_and_new_issue_references(self): + pr = {**self.pr, "body": "Refs #3"} + third = {**self.issue, "id": "I3", "number": 3} + event = {"changes": {"body": {"from": "Refs #1"}}} + old_pr = {**self.pr, "id": "PR4", "number": 4, "body": "Refs #1"} + old_issue = { + **self.issue, + "timelineItems": [ + { + "source": { + "__typename": "PullRequest", + "number": 4, + "repository": {"nameWithOwner": "AstrBotDevs/AstrBot"}, + } + } + ], + } + with patch.object( + sync, "read_subject", side_effect=[pr, old_issue, third, old_pr] + ): + candidates, _, linked = sync.event_snapshot( + "P", "AstrBotDevs/AstrBot", 2, event + ) + self.assertEqual({x["number"] for x in candidates}, {1, 2, 3, 4}) + self.assertEqual(linked[1], [old_pr]) + self.assertEqual(linked[3], [pr]) + + def test_pr_edit_recovers_old_custom_ref_from_project_link_field(self): + pr = {**self.pr, "body": "Refs #3"} + old_pr = {**self.pr, "id": "PR4", "number": 4, "body": "Refs #1"} + old_issue = { + **self.issue, + "projectItems": [ + { + "project": {"id": "P"}, + "fieldValues": [ + { + "field": {"name": "实现关联"}, + "text": "https://github.com/AstrBotDevs/AstrBot/pull/4", + } + ], + } + ], + } + third = {**self.issue, "id": "I3", "number": 3} + with patch.object( + sync, "read_subject", side_effect=[pr, old_issue, third, old_pr] + ): + candidates, _, linked = sync.event_snapshot( + "P", + "AstrBotDevs/AstrBot", + 2, + {"changes": {"body": {"from": "Refs #1"}}}, + ) + self.assertEqual({item["number"] for item in candidates}, {1, 2, 3, 4}) + self.assertEqual(linked[1], [old_pr]) + + def test_event_path_reads_no_full_release_connection(self): + with ( + patch.object(sync, "event_snapshot", return_value=([self.issue], {}, {})), + patch.object( + sync, "connection", side_effect=[self.fields, []] + ) as connection, + patch.object(sync.subprocess, "run", return_value=Mock(stdout="a" * 40)), + ): + sync.reconcile("P", "AstrBotDevs/AstrBot", subject=1) + queries = [call.args[0] for call in connection.call_args_list] + for forbidden in ( + "issues(first:", + "pullRequests(first:", + "items(first:", + "releases(first:", + ): + self.assertFalse(any(forbidden in query for query in queries)) + queries = [call.args[0] for call in connection.call_args_list] + self.assertFalse(any("issues(first:" in query for query in queries)) + self.assertFalse(any("pullRequests(first:" in query for query in queries)) + self.assertFalse(any("items(first:" in query for query in queries)) + + def test_subject_reads_never_scan_repository_or_project_connections(self): + node = {**self.issue, "issueState": "OPEN"} + with ( + patch.object( + sync, + "graphql", + return_value={"repository": {"issueOrPullRequest": node}}, + ) as api, + patch.object(sync, "connection", return_value=[]), + ): + sync.read_subject("AstrBotDevs/AstrBot", 1) + query = api.call_args.args[0] + for forbidden in ( + "issues(first:", + "pullRequests(first:", + "items(first:", + "releases(first:", + ): + self.assertNotIn(forbidden, query) + self.assertIn("issueOrPullRequest(number:", query) + + def test_apply_failure_reports_confirmed_unknown_and_unattempted(self): + plan = [ + { + "content": "C", + "item": "I", + "number": 1, + "changes": {"发布版本": "v1", "发布说明": "r", "实现关联": "pr"}, + } + ] + fields = {name: {"id": name} for name in plan[0]["changes"]} + with ( + patch.object(sync, "graphql", side_effect=[{}, RuntimeError("secret")]), + patch("sys.stdout", new_callable=io.StringIO) as output, + ): + with self.assertRaises(RuntimeError): + sync.apply_plan("P", fields, plan, apply=True) + messages = [json.loads(line) for line in output.getvalue().splitlines()] + self.assertEqual(messages[0]["plan"], plan) + self.assertEqual(messages[-1]["confirmed"], 1) + self.assertEqual(messages[-1]["unknown"], 1) + self.assertEqual(messages[-1]["unattempted"], 1) + self.assertEqual(messages[-1]["field"], "发布说明") + self.assertNotIn("secret", output.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sync_github_project.py b/tests/test_sync_github_project.py index ad3d83a86f1..692348b0696 100644 --- a/tests/test_sync_github_project.py +++ b/tests/test_sync_github_project.py @@ -181,9 +181,6 @@ def test_supported_events_and_subjects(self): ("pull_request_target", "closed", "pull_request"), ("pull_request_target", "edited", "pull_request"), ("pull_request_target", "synchronize", "pull_request"), - ("release", "published", None), - ("release", "deleted", None), - ("push", None, None), ("schedule", None, None), ("workflow_dispatch", None, None), ]: @@ -230,6 +227,14 @@ def test_untrusted_context_never_reconciles(self): ("issues", "opened", "AstrBotDevs/AstrBot", True, "refs/heads/master"), ("issues", "opened", "AstrBotDevs/AstrBot", 0, "refs/heads/master"), ("issues", "opened", "AstrBotDevs/AstrBot", "42", "refs/heads/master"), + ( + "release", + "published", + "AstrBotDevs/AstrBot", + 42, + "refs/heads/master", + ), + ("push", None, "AstrBotDevs/AstrBot", 42, "refs/heads/master"), ( "workflow_dispatch", None, @@ -237,7 +242,14 @@ def test_untrusted_context_never_reconciles(self): 42, "refs/heads/untrusted", ), - ("push", None, "AstrBotDevs/AstrBot", 42, "refs/heads/untrusted"), + ( + "release", + "published", + "AstrBotDevs/AstrBot", + 42, + "refs/heads/master", + ), + ("push", None, "AstrBotDevs/AstrBot", 42, "refs/heads/master"), ]: path.write_text( json.dumps(