From a8b1c36d6d5d512c1c3279ebc1f75cf747d70d3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Mon, 23 Nov 2026 23:40:15 -0300 Subject: [PATCH 01/53] ci: validate coordination claims on pull requests --- .github/workflows/coordination-claim.yml | 153 +++++++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 .github/workflows/coordination-claim.yml diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml new file mode 100644 index 0000000000..e3cc2e0f7c --- /dev/null +++ b/.github/workflows/coordination-claim.yml @@ -0,0 +1,153 @@ +name: Coordination claim + +on: + pull_request: + branches: [main] + types: [opened, reopened, edited, synchronize, ready_for_review] + +permissions: + issues: read + pull-requests: read + +jobs: + coordination-claim: + name: coordination-claim + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Validate claim against issue #14 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + python3 - <<'PY' + import json + import os + import re + import sys + import urllib.error + import urllib.request + + API = "https://api.github.com" + OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) + TOKEN = os.environ["GITHUB_TOKEN"] + ISSUE_NUMBER = 14 + ID_RE = re.compile(r"^[A-Z0-9]+(?:-[A-Z0-9]+)*$") + CLAIM_RE = re.compile(r"(?im)^\s*claiming:\s*([A-Z0-9]+(?:-[A-Z0-9]+)*)\s*$") + + def fail(message): + print(f"::error title=Coordination claim::{message}") + sys.exit(1) + + def get_json(path): + request = urllib.request.Request( + API + path, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + }, + ) + try: + with urllib.request.urlopen(request, timeout=20) as response: + return json.load(response) + except urllib.error.HTTPError as error: + fail(f"Cannot verify the claim against issue #14 (HTTP {error.code}).") + except (urllib.error.URLError, TimeoutError): + fail("Cannot reach GitHub to verify the claim against issue #14.") + + def open_work_ids(body): + in_open_work = False + result = set() + for line in (body or "").splitlines(): + if re.match(r"^##\s+Open work\b", line, re.IGNORECASE): + in_open_work = True + continue + if in_open_work and re.match(r"^##\s+", line): + break + if not in_open_work or not line.lstrip().startswith("|"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + if len(cells) < 5: + continue + item_id = cells[0].strip(chr(96)).upper() + status = cells[-1].strip().lower() + if item_id != "ID" and ID_RE.fullmatch(item_id) and status.startswith("open"): + result.add(item_id) + return result + + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: + event = json.load(event_file) + pull = event.get("pull_request") or {} + author = (pull.get("user") or {}).get("login") or "" + title = pull.get("title") or "" + body = pull.get("body") or "" + clean_body = re.sub(r"", "", body) + submitted_text = title + "\\n" + clean_body + + issue = get_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") + work_ids = open_work_ids(issue.get("body") or "") + if not work_ids: + fail("Issue #14 has no readable open work-item IDs.") + + comments = [] + for page in range(1, 101): + batch = get_json( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" + f"?per_page=100&page={page}" + ) + comments.extend(batch) + if len(batch) < 100: + break + else: + fail("Issue #14 has too many comments to verify safely.") + + candidate_ids = { + item_id + for item_id in work_ids + if re.search( + rf"(? Date: Mon, 23 Nov 2026 23:45:39 -0300 Subject: [PATCH 02/53] ci: correct claim parser escaping --- .github/workflows/coordination-claim.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index e3cc2e0f7c..d74bc3c2e5 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -81,8 +81,8 @@ jobs: author = (pull.get("user") or {}).get("login") or "" title = pull.get("title") or "" body = pull.get("body") or "" - clean_body = re.sub(r"", "", body) - submitted_text = title + "\\n" + clean_body + clean_body = re.sub(r"", "", body) + submitted_text = title + "\n" + clean_body issue = get_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") work_ids = open_work_ids(issue.get("body") or "") @@ -112,11 +112,11 @@ jobs: } claim_field = re.search( - r"(?im)^Claimed in the coordination issue as:\\s*(.*)$", + r"(?im)^Claimed in the coordination issue as:\s*(.*)$", clean_body, ) if claim_field: - link = re.search(r"#issuecomment-(\\d+)", claim_field.group(1)) + link = re.search(r"#issuecomment-(\d+)", claim_field.group(1)) if link: linked_comment_id = link.group(1) linked_comment = next( From a2061ebd164b16c84a358f02f0fdc1cf62191172 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Mon, 23 Nov 2026 23:50:42 -0300 Subject: [PATCH 03/53] ci: require claim before pull request creation --- .github/workflows/coordination-claim.yml | 25 +++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index d74bc3c2e5..c5ba215da5 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -26,6 +26,7 @@ jobs: import sys import urllib.error import urllib.request +from datetime import datetime API = "https://api.github.com" OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) @@ -134,14 +135,36 @@ jobs: "(or link the claim comment) before requesting review." ) + def parse_time(value): + if not value: + return None + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + + pull_opened = parse_time(pull.get("created_at")) + if pull_opened is None: + fail("Cannot determine when this PR was opened.") + item_id = next(iter(candidate_ids)) matching_claims = [] + later_claim_exists = False for comment in comments: for match in CLAIM_RE.finditer(comment.get("body") or ""): - if match.group(1).upper() == item_id: + if match.group(1).upper() != item_id: + continue + claim_time = parse_time(comment.get("created_at")) + if claim_time is None: + continue + if claim_time < pull_opened: matching_claims.append(comment) + else: + later_claim_exists = True if not matching_claims: + if later_claim_exists: + fail(f"Claim {item_id} must be posted before the PR is opened.") fail(f"No claiming comment was found for work item {item_id} on issue #14.") owners = { ((comment.get("user") or {}).get("login") or "").casefold() From a4971f4f71279dcf7cc2340a09a845c8c9936898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 00:32:29 -0300 Subject: [PATCH 04/53] ci: sync coordination activity in issue 14 --- .github/workflows/coordination-claim.yml | 502 +++++++++++++++++++---- 1 file changed, 412 insertions(+), 90 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index c5ba215da5..6955c11d73 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -3,17 +3,29 @@ name: Coordination claim on: pull_request: branches: [main] - types: [opened, reopened, edited, synchronize, ready_for_review] + types: [opened, reopened, edited, synchronize, ready_for_review, converted_to_draft, closed] + issue_comment: + types: [created, edited, deleted] + workflow_run: + workflows: ["Coordination claim"] + types: [completed] + workflow_dispatch: -permissions: - issues: read - pull-requests: read +permissions: {} + +concurrency: + group: coordination-activity + cancel-in-progress: false jobs: - coordination-claim: + validate-claim: + if: github.event_name == 'pull_request' && github.event.action != 'closed' name: coordination-claim runs-on: ubuntu-latest - timeout-minutes: 2 + timeout-minutes: 3 + permissions: + issues: read + pull-requests: read steps: - name: Validate claim against issue #14 env: @@ -26,20 +38,28 @@ jobs: import sys import urllib.error import urllib.request -from datetime import datetime + from datetime import datetime API = "https://api.github.com" OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) TOKEN = os.environ["GITHUB_TOKEN"] ISSUE_NUMBER = 14 - ID_RE = re.compile(r"^[A-Z0-9]+(?:-[A-Z0-9]+)*$") - CLAIM_RE = re.compile(r"(?im)^\s*claiming:\s*([A-Z0-9]+(?:-[A-Z0-9]+)*)\s*$") + WORK_ID_RE = re.compile(r"[A-Z0-9]+(?:-[A-Z0-9]+)+") + CLAIM_LIST_RE = re.compile( + r"^([A-Z0-9]+(?:-[A-Z0-9]+)+" + r"(?:\s*,\s*[A-Z0-9]+(?:-[A-Z0-9]+)+)*)" + ) + CLAIM_FIELD_RE = re.compile( + r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + ) + BACKTICK = chr(96) def fail(message): - print(f"::error title=Coordination claim::{message}") + safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::error title=Coordination claim::{safe}") sys.exit(1) - def get_json(path): + def request_json(path): request = urllib.request.Request( API + path, headers={ @@ -56,6 +76,35 @@ from datetime import datetime except (urllib.error.URLError, TimeoutError): fail("Cannot reach GitHub to verify the claim against issue #14.") + def get_collection(path): + result = [] + for page in range(1, 101): + batch = request_json(f"{path}?per_page=100&page={page}") + if not isinstance(batch, list): + fail("GitHub returned an invalid issue #14 response.") + result.extend(batch) + if len(batch) < 100: + return result + fail("Issue #14 has too many comments to verify safely.") + + def claim_ids_from_comment(body): + lines = (body or "").splitlines() + found = set() + for index, line in enumerate(lines): + match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + if not match: + continue + tail = match.group(1).strip() + listed = CLAIM_LIST_RE.match(tail) + if listed: + found.update(part.strip().upper() for part in listed.group(1).split(",")) + elif re.match(r"^(the items below|a second batch)\b", tail, re.IGNORECASE): + for bullet in lines[index + 1:]: + if not re.match(r"^\s*[-*]\s+", bullet): + continue + found.update(re.findall(BACKTICK + r"([A-Z0-9]+(?:-[A-Z0-9]+)+)" + BACKTICK, bullet)) + return found + def open_work_ids(body): in_open_work = False result = set() @@ -70,70 +119,223 @@ from datetime import datetime cells = [cell.strip() for cell in line.strip().strip("|").split("|")] if len(cells) < 5: continue - item_id = cells[0].strip(chr(96)).upper() - status = cells[-1].strip().lower() - if item_id != "ID" and ID_RE.fullmatch(item_id) and status.startswith("open"): + item_id = cells[0].strip(BACKTICK).upper() + status = cells[-1].lower() + if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): result.add(item_id) return result + def find_ids(text, allowed): + text = text or "" + return { + item_id + for item_id in allowed + if re.search( + rf"(?", "", body) - submitted_text = title + "\n" + clean_body + author = ((pull.get("user") or {}).get("login") or "").casefold() + opened_at = parse_time(pull.get("created_at")) + if not author or opened_at is None: + fail("Cannot determine the PR author or opening time.") + + issue = request_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") + comments = get_collection(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments") + comments_by_id = {str(comment.get("id")): comment for comment in comments} + claims_by_id = {} + for comment in comments: + for item_id in claim_ids_from_comment(comment.get("body") or ""): + claims_by_id.setdefault(item_id, []).append(comment) - issue = get_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") work_ids = open_work_ids(issue.get("body") or "") - if not work_ids: - fail("Issue #14 has no readable open work-item IDs.") - - comments = [] - for page in range(1, 101): - batch = get_json( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" - f"?per_page=100&page={page}" - ) - comments.extend(batch) - if len(batch) < 100: - break - else: - fail("Issue #14 has too many comments to verify safely.") + allowed_ids = work_ids | set(claims_by_id) + title = pull.get("title") or "" + title_candidates = find_ids(title, allowed_ids) + candidates = set(title_candidates) + if not candidates: + body = re.sub(r"", "", pull.get("body") or "") + field = CLAIM_FIELD_RE.search(body) + if field: + value = field.group(1) + linked = re.search(r"#issuecomment-(\d+)", value) + if linked: + linked_comment = comments_by_id.get(linked.group(1)) + if linked_comment: + candidates.update( + claim_ids_from_comment(linked_comment.get("body") or "") & allowed_ids + ) + if not candidates: + candidates.update(find_ids(value, allowed_ids)) - candidate_ids = { - item_id - for item_id in work_ids - if re.search( - rf"(?- + (github.event_name == 'issue_comment' && github.event.issue.number == 14) || + (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') || + github.event_name == 'workflow_dispatch' + name: sync-issue-activity + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write + pull-requests: read + steps: + - name: Refresh the managed activity block in issue #14 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + python3 - <<'PY' + import json + import os + import re + import sys + import urllib.error + import urllib.request + from collections import defaultdict + from datetime import datetime, timezone + + API = "https://api.github.com" + OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) + TOKEN = os.environ["GITHUB_TOKEN"] + ISSUE_NUMBER = 14 + BEGIN = "" + END = "" + WORK_ID_RE = re.compile(r"[A-Z0-9]+(?:-[A-Z0-9]+)+") + CLAIM_LIST_RE = re.compile( + r"^([A-Z0-9]+(?:-[A-Z0-9]+)+" + r"(?:\s*,\s*[A-Z0-9]+(?:-[A-Z0-9]+)+)*)" ) - if claim_field: - link = re.search(r"#issuecomment-(\d+)", claim_field.group(1)) - if link: - linked_comment_id = link.group(1) - linked_comment = next( - (comment for comment in comments if str(comment.get("id")) == linked_comment_id), - None, - ) - if linked_comment: - linked_claim = CLAIM_RE.search(linked_comment.get("body") or "") - if linked_claim and linked_claim.group(1).upper() in work_ids: - candidate_ids.add(linked_claim.group(1).upper()) + CLAIM_FIELD_RE = re.compile( + r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + ) + BACKTICK = chr(96) - if len(candidate_ids) != 1: - fail( - "Add exactly one open work-item ID from issue #14 to the PR title/body " - "(or link the claim comment) before requesting review." + def stop(message): + safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::error title=Coordination activity::{safe}") + sys.exit(1) + + def api_json(path, method="GET", payload=None): + data = None if payload is None else json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + API + path, + data=data, + method=method, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, ) + try: + with urllib.request.urlopen(request, timeout=25) as response: + return json.load(response) + except urllib.error.HTTPError as error: + stop(f"GitHub API request failed (HTTP {error.code}); issue #14 was not changed.") + except (urllib.error.URLError, TimeoutError): + stop("Cannot reach GitHub; issue #14 was not changed.") + + def get_collection(path, label): + result = [] + for page in range(1, 101): + batch = api_json(f"{path}?per_page=100&page={page}") + if not isinstance(batch, list): + stop(f"GitHub returned an invalid {label} response.") + result.extend(batch) + if len(batch) < 100: + return result + stop(f"The {label} collection is too large to sync safely.") + + def claim_ids_from_comment(body): + lines = (body or "").splitlines() + found = set() + for index, line in enumerate(lines): + match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + if not match: + continue + tail = match.group(1).strip() + listed = CLAIM_LIST_RE.match(tail) + if listed: + found.update(part.strip().upper() for part in listed.group(1).split(",")) + elif re.match(r"^(the items below|a second batch)\b", tail, re.IGNORECASE): + for bullet in lines[index + 1:]: + if not re.match(r"^\s*[-*]\s+", bullet): + continue + found.update(re.findall(BACKTICK + r"([A-Z0-9]+(?:-[A-Z0-9]+)+)" + BACKTICK, bullet)) + return found + + def open_work_ids(body): + in_open_work = False + result = set() + for line in (body or "").splitlines(): + if re.match(r"^##\s+Open work\b", line, re.IGNORECASE): + in_open_work = True + continue + if in_open_work and re.match(r"^##\s+", line): + break + if not in_open_work or not line.lstrip().startswith("|"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + if len(cells) < 5: + continue + item_id = cells[0].strip(BACKTICK).upper() + status = cells[-1].lower() + if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): + result.add(item_id) + return result + + def find_ids(text, allowed): + text = text or "" + return { + item_id + for item_id in allowed + if re.search( + rf"(?", "", pull.get("body") or "") + field = CLAIM_FIELD_RE.search(body) + if field: + value = field.group(1) + linked = re.search(r"#issuecomment-(\d+)", value) + if linked: + linked_comment = comments_by_id.get(linked.group(1)) + if linked_comment: + candidates.update( + claim_ids_from_comment(linked_comment.get("body") or "") & allowed_ids + ) + if not candidates: + candidates.update(find_ids(value, allowed_ids)) + if not candidates: + return "unclaimed", set(), None, {} + + owners = set() + links = {} + for item_id in sorted(candidates): + prior = [] + for comment in claims_by_id.get(item_id, []): + effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + if effective_at is not None and effective_at < opened_at: + prior.append(comment) + claim_owners = { + ((comment.get("user") or {}).get("login") or "").casefold() + for comment in prior + } + if not prior or len(claim_owners) != 1: + return "invalid", candidates, None, {} + owners.update(claim_owners) + prior.sort(key=lambda comment: comment.get("created_at") or "") + links[item_id] = str(prior[0].get("id") or "") + if len(owners) != 1 or next(iter(owners)).casefold() != author.casefold(): + return "invalid", candidates, None, {} + return "claimed", candidates, author, links + + def safe_cell(value, limit=180): + value = re.sub(r"[\r\n\t]+", " ", str(value or "")).strip() + value = ( + value.replace("\\", "\\\\") + .replace("|", "\\|") + .replace(BACKTICK, "\\" + BACKTICK) + .replace("[", "\\[") + .replace("]", "\\]") + .replace("<", "<") + .replace(">", ">") + ) + if len(value) > limit: + value = value[:limit - 3].rstrip() + "..." + return value - item_id = next(iter(candidate_ids)) - matching_claims = [] - later_claim_exists = False + issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") + comments = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + "issue #14 comments", + ) + pulls = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/pulls", + "open pull requests", + ) + pulls = [pull for pull in pulls if pull.get("state") == "open"] + comments_by_id = {str(comment.get("id")): comment for comment in comments} + claims_by_id = defaultdict(list) for comment in comments: - for match in CLAIM_RE.finditer(comment.get("body") or ""): - if match.group(1).upper() != item_id: - continue - claim_time = parse_time(comment.get("created_at")) - if claim_time is None: - continue - if claim_time < pull_opened: - matching_claims.append(comment) - else: - later_claim_exists = True - - if not matching_claims: - if later_claim_exists: - fail(f"Claim {item_id} must be posted before the PR is opened.") - fail(f"No claiming comment was found for work item {item_id} on issue #14.") - owners = { - ((comment.get("user") or {}).get("login") or "").casefold() - for comment in matching_claims - } - if len(owners) != 1 or author.casefold() not in owners: - fail(f"Claim {item_id} must have one owner, matching the PR author.") - print(f"Coordination claim verified for {item_id}.") - PY \ No newline at end of file + for item_id in claim_ids_from_comment(comment.get("body") or ""): + claims_by_id[item_id].append(comment) + allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + + activity_rows = [] + for pull in pulls: + status, item_ids, owner, links = evaluate_claim( + pull, allowed_ids, claims_by_id, comments_by_id + ) + activity_rows.append((pull, status, item_ids, owner, links)) + + groups = defaultdict(list) + for row in activity_rows: + pull = row[0] + groups[((pull.get("user") or {}).get("login") or "unknown")].append(row) + + updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + section = [ + BEGIN, + "## Current open pull request activity", + "", + f"Updated: **{updated_at}** — **{len(pulls)} open PRs** across **{len(groups)} submitters**.", + "PR author is the submitter; it does not establish ownership. A linked claim is valid only when its issue #14 comment predates the PR and the claimant matches the author. Rows marked **Needs claim** require a valid claim. The action reports status only; it never closes or assigns a PR.", + "", + "Submitters are grouped below. The Action replaces only this marked block; all surrounding issue text remains editable.", + ] + for author in sorted(groups, key=str.casefold): + author_rows = sorted(groups[author], key=lambda row: row[0].get("number", 0), reverse=True) + section.extend([ + "", + f"### @{safe_cell(author)} — {len(author_rows)} open PRs", + "", + "| PR | Claim / owner | Work (PR title) | State |", + "|---|---|---|---|", + ]) + for pull, status, item_ids, owner, links in author_rows: + claim_cell = "Unclaimed" + if status == "invalid": + claim_cell = "Needs claim" + elif status == "claimed": + rendered = [] + for item_id in sorted(item_ids): + comment_id = links.get(item_id) + comment_url = ( + f"https://github.com/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}" + f"#issuecomment-{comment_id}" + ) + rendered.append(f"[{BACKTICK}{item_id}{BACKTICK}]({comment_url})") + claim_cell = ", ".join(rendered) + f" — @{safe_cell(owner)}" + pr_url = pull.get("html_url") or f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" + pr_label = f"[#{pull.get('number')}]({pr_url})" + title = safe_cell(pull.get("title") or "") + state = "Draft" if pull.get("draft") else "Ready" + section.append(f"| {pr_label} | {claim_cell} | {title} | {state} |") + section.append(END) + managed_block = "\n".join(section) + + current_body = issue.get("body") or "" + if current_body.count(BEGIN) != 1 or current_body.count(END) != 1: + stop("Issue #14 must contain exactly one pair of activity markers; it was not changed.") + start = current_body.index(BEGIN) + end = current_body.index(END) + if end < start: + stop("Issue #14 activity markers are out of order; it was not changed.") + end += len(END) + new_body = current_body[:start] + managed_block + current_body[end:] + if len(new_body) > 65536: + stop("The activity table would exceed GitHub's issue-body limit; the prior table was kept.") + if new_body == current_body: + print(f"Issue #14 is already current ({len(pulls)} open PRs).") + else: + api_json( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", + method="PATCH", + payload={"body": new_body}, + ) + print(f"Updated issue #14 with {len(pulls)} open PRs across {len(groups)} submitters.") + PY From 56a2f632a023d684dfe4878fc469e112342764d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 00:35:55 -0300 Subject: [PATCH 05/53] ci: separate read-only claim validation --- .github/workflows/coordination-claim.yml | 299 ----------------------- 1 file changed, 299 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 6955c11d73..e3140e4863 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -4,19 +4,9 @@ on: pull_request: branches: [main] types: [opened, reopened, edited, synchronize, ready_for_review, converted_to_draft, closed] - issue_comment: - types: [created, edited, deleted] - workflow_run: - workflows: ["Coordination claim"] - types: [completed] - workflow_dispatch: permissions: {} -concurrency: - group: coordination-activity - cancel-in-progress: false - jobs: validate-claim: if: github.event_name == 'pull_request' && github.event.action != 'closed' @@ -207,292 +197,3 @@ jobs: if owners != {author}: fail("Every claim must have one owner, and that owner must match the PR author.") print("Coordination claim verified for " + ", ".join(sorted(candidates)) + ".") - - sync-activity: - if: >- - (github.event_name == 'issue_comment' && github.event.issue.number == 14) || - (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') || - github.event_name == 'workflow_dispatch' - name: sync-issue-activity - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - issues: write - pull-requests: read - steps: - - name: Refresh the managed activity block in issue #14 - env: - GITHUB_TOKEN: ${{ github.token }} - run: | - python3 - <<'PY' - import json - import os - import re - import sys - import urllib.error - import urllib.request - from collections import defaultdict - from datetime import datetime, timezone - - API = "https://api.github.com" - OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) - TOKEN = os.environ["GITHUB_TOKEN"] - ISSUE_NUMBER = 14 - BEGIN = "" - END = "" - WORK_ID_RE = re.compile(r"[A-Z0-9]+(?:-[A-Z0-9]+)+") - CLAIM_LIST_RE = re.compile( - r"^([A-Z0-9]+(?:-[A-Z0-9]+)+" - r"(?:\s*,\s*[A-Z0-9]+(?:-[A-Z0-9]+)+)*)" - ) - CLAIM_FIELD_RE = re.compile( - r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" - ) - BACKTICK = chr(96) - - def stop(message): - safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") - print(f"::error title=Coordination activity::{safe}") - sys.exit(1) - - def api_json(path, method="GET", payload=None): - data = None if payload is None else json.dumps(payload).encode("utf-8") - request = urllib.request.Request( - API + path, - data=data, - method=method, - headers={ - "Accept": "application/vnd.github+json", - "Authorization": f"Bearer {TOKEN}", - "X-GitHub-Api-Version": "2022-11-28", - "Content-Type": "application/json", - }, - ) - try: - with urllib.request.urlopen(request, timeout=25) as response: - return json.load(response) - except urllib.error.HTTPError as error: - stop(f"GitHub API request failed (HTTP {error.code}); issue #14 was not changed.") - except (urllib.error.URLError, TimeoutError): - stop("Cannot reach GitHub; issue #14 was not changed.") - - def get_collection(path, label): - result = [] - for page in range(1, 101): - batch = api_json(f"{path}?per_page=100&page={page}") - if not isinstance(batch, list): - stop(f"GitHub returned an invalid {label} response.") - result.extend(batch) - if len(batch) < 100: - return result - stop(f"The {label} collection is too large to sync safely.") - - def claim_ids_from_comment(body): - lines = (body or "").splitlines() - found = set() - for index, line in enumerate(lines): - match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) - if not match: - continue - tail = match.group(1).strip() - listed = CLAIM_LIST_RE.match(tail) - if listed: - found.update(part.strip().upper() for part in listed.group(1).split(",")) - elif re.match(r"^(the items below|a second batch)\b", tail, re.IGNORECASE): - for bullet in lines[index + 1:]: - if not re.match(r"^\s*[-*]\s+", bullet): - continue - found.update(re.findall(BACKTICK + r"([A-Z0-9]+(?:-[A-Z0-9]+)+)" + BACKTICK, bullet)) - return found - - def open_work_ids(body): - in_open_work = False - result = set() - for line in (body or "").splitlines(): - if re.match(r"^##\s+Open work\b", line, re.IGNORECASE): - in_open_work = True - continue - if in_open_work and re.match(r"^##\s+", line): - break - if not in_open_work or not line.lstrip().startswith("|"): - continue - cells = [cell.strip() for cell in line.strip().strip("|").split("|")] - if len(cells) < 5: - continue - item_id = cells[0].strip(BACKTICK).upper() - status = cells[-1].lower() - if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): - result.add(item_id) - return result - - def find_ids(text, allowed): - text = text or "" - return { - item_id - for item_id in allowed - if re.search( - rf"(?", "", pull.get("body") or "") - field = CLAIM_FIELD_RE.search(body) - if field: - value = field.group(1) - linked = re.search(r"#issuecomment-(\d+)", value) - if linked: - linked_comment = comments_by_id.get(linked.group(1)) - if linked_comment: - candidates.update( - claim_ids_from_comment(linked_comment.get("body") or "") & allowed_ids - ) - if not candidates: - candidates.update(find_ids(value, allowed_ids)) - if not candidates: - return "unclaimed", set(), None, {} - - owners = set() - links = {} - for item_id in sorted(candidates): - prior = [] - for comment in claims_by_id.get(item_id, []): - effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) - if effective_at is not None and effective_at < opened_at: - prior.append(comment) - claim_owners = { - ((comment.get("user") or {}).get("login") or "").casefold() - for comment in prior - } - if not prior or len(claim_owners) != 1: - return "invalid", candidates, None, {} - owners.update(claim_owners) - prior.sort(key=lambda comment: comment.get("created_at") or "") - links[item_id] = str(prior[0].get("id") or "") - if len(owners) != 1 or next(iter(owners)).casefold() != author.casefold(): - return "invalid", candidates, None, {} - return "claimed", candidates, author, links - - def safe_cell(value, limit=180): - value = re.sub(r"[\r\n\t]+", " ", str(value or "")).strip() - value = ( - value.replace("\\", "\\\\") - .replace("|", "\\|") - .replace(BACKTICK, "\\" + BACKTICK) - .replace("[", "\\[") - .replace("]", "\\]") - .replace("<", "<") - .replace(">", ">") - ) - if len(value) > limit: - value = value[:limit - 3].rstrip() + "..." - return value - - issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") - comments = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", - "issue #14 comments", - ) - pulls = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/pulls", - "open pull requests", - ) - pulls = [pull for pull in pulls if pull.get("state") == "open"] - comments_by_id = {str(comment.get("id")): comment for comment in comments} - claims_by_id = defaultdict(list) - for comment in comments: - for item_id in claim_ids_from_comment(comment.get("body") or ""): - claims_by_id[item_id].append(comment) - allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) - - activity_rows = [] - for pull in pulls: - status, item_ids, owner, links = evaluate_claim( - pull, allowed_ids, claims_by_id, comments_by_id - ) - activity_rows.append((pull, status, item_ids, owner, links)) - - groups = defaultdict(list) - for row in activity_rows: - pull = row[0] - groups[((pull.get("user") or {}).get("login") or "unknown")].append(row) - - updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") - section = [ - BEGIN, - "## Current open pull request activity", - "", - f"Updated: **{updated_at}** — **{len(pulls)} open PRs** across **{len(groups)} submitters**.", - "PR author is the submitter; it does not establish ownership. A linked claim is valid only when its issue #14 comment predates the PR and the claimant matches the author. Rows marked **Needs claim** require a valid claim. The action reports status only; it never closes or assigns a PR.", - "", - "Submitters are grouped below. The Action replaces only this marked block; all surrounding issue text remains editable.", - ] - for author in sorted(groups, key=str.casefold): - author_rows = sorted(groups[author], key=lambda row: row[0].get("number", 0), reverse=True) - section.extend([ - "", - f"### @{safe_cell(author)} — {len(author_rows)} open PRs", - "", - "| PR | Claim / owner | Work (PR title) | State |", - "|---|---|---|---|", - ]) - for pull, status, item_ids, owner, links in author_rows: - claim_cell = "Unclaimed" - if status == "invalid": - claim_cell = "Needs claim" - elif status == "claimed": - rendered = [] - for item_id in sorted(item_ids): - comment_id = links.get(item_id) - comment_url = ( - f"https://github.com/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}" - f"#issuecomment-{comment_id}" - ) - rendered.append(f"[{BACKTICK}{item_id}{BACKTICK}]({comment_url})") - claim_cell = ", ".join(rendered) + f" — @{safe_cell(owner)}" - pr_url = pull.get("html_url") or f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" - pr_label = f"[#{pull.get('number')}]({pr_url})" - title = safe_cell(pull.get("title") or "") - state = "Draft" if pull.get("draft") else "Ready" - section.append(f"| {pr_label} | {claim_cell} | {title} | {state} |") - section.append(END) - managed_block = "\n".join(section) - - current_body = issue.get("body") or "" - if current_body.count(BEGIN) != 1 or current_body.count(END) != 1: - stop("Issue #14 must contain exactly one pair of activity markers; it was not changed.") - start = current_body.index(BEGIN) - end = current_body.index(END) - if end < start: - stop("Issue #14 activity markers are out of order; it was not changed.") - end += len(END) - new_body = current_body[:start] + managed_block + current_body[end:] - if len(new_body) > 65536: - stop("The activity table would exceed GitHub's issue-body limit; the prior table was kept.") - if new_body == current_body: - print(f"Issue #14 is already current ({len(pulls)} open PRs).") - else: - api_json( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", - method="PATCH", - payload={"body": new_body}, - ) - print(f"Updated issue #14 with {len(pulls)} open PRs across {len(groups)} submitters.") - PY From 13cc7cd16bfb4c8dc2ce95db59d1d78e07e7ee51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 00:36:22 -0300 Subject: [PATCH 06/53] ci: maintain issue 14 PR activity --- .github/workflows/coordination-activity.yml | 305 ++++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 .github/workflows/coordination-activity.yml diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml new file mode 100644 index 0000000000..696e20f283 --- /dev/null +++ b/.github/workflows/coordination-activity.yml @@ -0,0 +1,305 @@ +name: Coordination activity + +on: + issue_comment: + types: [created, edited, deleted] + workflow_run: + workflows: ["Coordination claim"] + types: [completed] + workflow_dispatch: + +permissions: {} + +concurrency: + group: coordination-activity + cancel-in-progress: false + +jobs: + sync-activity: + if: >- + (github.event_name == 'issue_comment' && github.event.issue.number == 14) || + (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') || + github.event_name == 'workflow_dispatch' + name: sync-issue-activity + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write + pull-requests: read + steps: + - name: Refresh the managed activity block in issue #14 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + python3 - <<'PY' + import json + import os + import re + import sys + import urllib.error + import urllib.request + from collections import defaultdict + from datetime import datetime, timezone + + API = "https://api.github.com" + OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) + TOKEN = os.environ["GITHUB_TOKEN"] + ISSUE_NUMBER = 14 + BEGIN = "" + END = "" + WORK_ID_RE = re.compile(r"[A-Z0-9]+(?:-[A-Z0-9]+)+") + CLAIM_LIST_RE = re.compile( + r"^([A-Z0-9]+(?:-[A-Z0-9]+)+" + r"(?:\s*,\s*[A-Z0-9]+(?:-[A-Z0-9]+)+)*)" + ) + CLAIM_FIELD_RE = re.compile( + r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + ) + BACKTICK = chr(96) + + def stop(message): + safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::error title=Coordination activity::{safe}") + sys.exit(1) + + def api_json(path, method="GET", payload=None): + data = None if payload is None else json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + API + path, + data=data, + method=method, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(request, timeout=25) as response: + return json.load(response) + except urllib.error.HTTPError as error: + stop(f"GitHub API request failed (HTTP {error.code}); issue #14 was not changed.") + except (urllib.error.URLError, TimeoutError): + stop("Cannot reach GitHub; issue #14 was not changed.") + + def get_collection(path, label): + result = [] + for page in range(1, 101): + batch = api_json(f"{path}?per_page=100&page={page}") + if not isinstance(batch, list): + stop(f"GitHub returned an invalid {label} response.") + result.extend(batch) + if len(batch) < 100: + return result + stop(f"The {label} collection is too large to sync safely.") + + def claim_ids_from_comment(body): + lines = (body or "").splitlines() + found = set() + for index, line in enumerate(lines): + match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + if not match: + continue + tail = match.group(1).strip() + listed = CLAIM_LIST_RE.match(tail) + if listed: + found.update(part.strip().upper() for part in listed.group(1).split(",")) + elif re.match(r"^(the items below|a second batch)\b", tail, re.IGNORECASE): + for bullet in lines[index + 1:]: + if not re.match(r"^\s*[-*]\s+", bullet): + continue + found.update(re.findall(BACKTICK + r"([A-Z0-9]+(?:-[A-Z0-9]+)+)" + BACKTICK, bullet)) + return found + + def open_work_ids(body): + in_open_work = False + result = set() + for line in (body or "").splitlines(): + if re.match(r"^##\s+Open work\b", line, re.IGNORECASE): + in_open_work = True + continue + if in_open_work and re.match(r"^##\s+", line): + break + if not in_open_work or not line.lstrip().startswith("|"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + if len(cells) < 5: + continue + item_id = cells[0].strip(BACKTICK).upper() + status = cells[-1].lower() + if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): + result.add(item_id) + return result + + def find_ids(text, allowed): + text = text or "" + return { + item_id + for item_id in allowed + if re.search( + rf"(?", "", pull.get("body") or "") + field = CLAIM_FIELD_RE.search(body) + if field: + value = field.group(1) + linked = re.search(r"#issuecomment-(\d+)", value) + if linked: + linked_comment = comments_by_id.get(linked.group(1)) + if linked_comment: + candidates.update( + claim_ids_from_comment(linked_comment.get("body") or "") & allowed_ids + ) + if not candidates: + candidates.update(find_ids(value, allowed_ids)) + if not candidates: + return "unclaimed", set(), None, {} + + owners = set() + links = {} + for item_id in sorted(candidates): + prior = [] + for comment in claims_by_id.get(item_id, []): + effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + if effective_at is not None and effective_at < opened_at: + prior.append(comment) + claim_owners = { + ((comment.get("user") or {}).get("login") or "").casefold() + for comment in prior + } + if not prior or len(claim_owners) != 1: + return "invalid", candidates, None, {} + owners.update(claim_owners) + prior.sort(key=lambda comment: comment.get("created_at") or "") + links[item_id] = str(prior[0].get("id") or "") + if len(owners) != 1 or next(iter(owners)).casefold() != author.casefold(): + return "invalid", candidates, None, {} + return "claimed", candidates, author, links + + def safe_cell(value, limit=180): + value = re.sub(r"[\r\n\t]+", " ", str(value or "")).strip() + value = ( + value.replace("\\", "\\\\") + .replace("|", "\\|") + .replace(BACKTICK, "\\" + BACKTICK) + .replace("[", "\\[") + .replace("]", "\\]") + .replace("<", "<") + .replace(">", ">") + ) + if len(value) > limit: + value = value[:limit - 3].rstrip() + "..." + return value + + issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") + comments = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + "issue #14 comments", + ) + pulls = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/pulls", + "open pull requests", + ) + pulls = [pull for pull in pulls if pull.get("state") == "open"] + comments_by_id = {str(comment.get("id")): comment for comment in comments} + claims_by_id = defaultdict(list) + for comment in comments: + for item_id in claim_ids_from_comment(comment.get("body") or ""): + claims_by_id[item_id].append(comment) + allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + + activity_rows = [] + for pull in pulls: + status, item_ids, owner, links = evaluate_claim( + pull, allowed_ids, claims_by_id, comments_by_id + ) + activity_rows.append((pull, status, item_ids, owner, links)) + + groups = defaultdict(list) + for row in activity_rows: + pull = row[0] + groups[((pull.get("user") or {}).get("login") or "unknown")].append(row) + + updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + section = [ + BEGIN, + "## Current open pull request activity", + "", + f"Updated: **{updated_at}** — **{len(pulls)} open PRs** across **{len(groups)} submitters**.", + "PR author is the submitter; it does not establish ownership. A linked claim is valid only when its issue #14 comment predates the PR and the claimant matches the author. Rows marked **Needs claim** require a valid claim. The action reports status only; it never closes or assigns a PR.", + "", + "Submitters are grouped below. The Action replaces only this marked block; all surrounding issue text remains editable.", + ] + for author in sorted(groups, key=str.casefold): + author_rows = sorted(groups[author], key=lambda row: row[0].get("number", 0), reverse=True) + section.extend([ + "", + f"### @{safe_cell(author)} — {len(author_rows)} open PRs", + "", + "| PR | Claim / owner | Work (PR title) | State |", + "|---|---|---|---|", + ]) + for pull, status, item_ids, owner, links in author_rows: + claim_cell = "Unclaimed" + if status == "invalid": + claim_cell = "Needs claim" + elif status == "claimed": + rendered = [] + for item_id in sorted(item_ids): + comment_id = links.get(item_id) + comment_url = ( + f"https://github.com/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}" + f"#issuecomment-{comment_id}" + ) + rendered.append(f"[{BACKTICK}{item_id}{BACKTICK}]({comment_url})") + claim_cell = ", ".join(rendered) + f" — @{safe_cell(owner)}" + pr_url = pull.get("html_url") or f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" + pr_label = f"[#{pull.get('number')}]({pr_url})" + title = safe_cell(pull.get("title") or "") + state = "Draft" if pull.get("draft") else "Ready" + section.append(f"| {pr_label} | {claim_cell} | {title} | {state} |") + section.append(END) + managed_block = "\n".join(section) + + current_body = issue.get("body") or "" + if current_body.count(BEGIN) != 1 or current_body.count(END) != 1: + stop("Issue #14 must contain exactly one pair of activity markers; it was not changed.") + start = current_body.index(BEGIN) + end = current_body.index(END) + if end < start: + stop("Issue #14 activity markers are out of order; it was not changed.") + end += len(END) + new_body = current_body[:start] + managed_block + current_body[end:] + if len(new_body) > 65536: + stop("The activity table would exceed GitHub's issue-body limit; the prior table was kept.") + if new_body == current_body: + print(f"Issue #14 is already current ({len(pulls)} open PRs).") + else: + api_json( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", + method="PATCH", + payload={"body": new_body}, + ) + print(f"Updated issue #14 with {len(pulls)} open PRs across {len(groups)} submitters.") + PY From 02099d7a6f1cfec74a419a05464a94ef8904c4a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 00:43:09 -0300 Subject: [PATCH 07/53] ci: avoid mentions in activity roster --- .github/workflows/coordination-activity.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 696e20f283..8d26b6ac99 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -207,6 +207,7 @@ jobs: .replace("]", "\\]") .replace("<", "<") .replace(">", ">") + .replace("@", "@") ) if len(value) > limit: value = value[:limit - 3].rstrip() + "..." @@ -255,7 +256,7 @@ jobs: author_rows = sorted(groups[author], key=lambda row: row[0].get("number", 0), reverse=True) section.extend([ "", - f"### @{safe_cell(author)} — {len(author_rows)} open PRs", + f"### {BACKTICK}{safe_cell(author)}{BACKTICK} — {len(author_rows)} open PRs", "", "| PR | Claim / owner | Work (PR title) | State |", "|---|---|---|---|", @@ -273,7 +274,7 @@ jobs: f"#issuecomment-{comment_id}" ) rendered.append(f"[{BACKTICK}{item_id}{BACKTICK}]({comment_url})") - claim_cell = ", ".join(rendered) + f" — @{safe_cell(owner)}" + claim_cell = ", ".join(rendered) + f" — {BACKTICK}{safe_cell(owner)}{BACKTICK}" pr_url = pull.get("html_url") or f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" pr_label = f"[#{pull.get('number')}]({pr_url})" title = safe_cell(pull.get("title") or "") From 588071070f9f191b3d2075bb24bd2ac1d0da2b18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:05:05 -0300 Subject: [PATCH 08/53] fix: validate all declared coordination claims --- .github/workflows/coordination-claim.yml | 146 +++++++++++++---------- 1 file changed, 82 insertions(+), 64 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index e3140e4863..3c79f64fd3 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -17,7 +17,7 @@ jobs: issues: read pull-requests: read steps: - - name: Validate claim against issue #14 + - name: Validate every declared claim against issue #14 env: GITHUB_TOKEN: ${{ github.token }} run: | @@ -29,26 +29,26 @@ jobs: import urllib.error import urllib.request from datetime import datetime - + API = "https://api.github.com" OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) TOKEN = os.environ["GITHUB_TOKEN"] ISSUE_NUMBER = 14 - WORK_ID_RE = re.compile(r"[A-Z0-9]+(?:-[A-Z0-9]+)+") - CLAIM_LIST_RE = re.compile( - r"^([A-Z0-9]+(?:-[A-Z0-9]+)+" - r"(?:\s*,\s*[A-Z0-9]+(?:-[A-Z0-9]+)+)*)" - ) + ID_PATTERN = r"[A-Z0-9]+(?:-[A-Z0-9]+)+" + WORK_ID_RE = re.compile(ID_PATTERN) + ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)", re.IGNORECASE) CLAIM_FIELD_RE = re.compile( r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) BACKTICK = chr(96) - + + def fail(message): safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") print(f"::error title=Coordination claim::{safe}") sys.exit(1) - + + def request_json(path): request = urllib.request.Request( API + path, @@ -65,19 +65,25 @@ jobs: fail(f"Cannot verify the claim against issue #14 (HTTP {error.code}).") except (urllib.error.URLError, TimeoutError): fail("Cannot reach GitHub to verify the claim against issue #14.") - + + def get_collection(path): result = [] for page in range(1, 101): batch = request_json(f"{path}?per_page=100&page={page}") if not isinstance(batch, list): - fail("GitHub returned an invalid issue #14 response.") + fail("GitHub returned an invalid issue #14 comments response.") result.extend(batch) if len(batch) < 100: return result fail("Issue #14 has too many comments to verify safely.") - - def claim_ids_from_comment(body): + + + def ids_from_text(text): + return {value.upper() for value in WORK_ID_RE.findall(text or "")} + + + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() for index, line in enumerate(lines): @@ -85,16 +91,34 @@ jobs: if not match: continue tail = match.group(1).strip() - listed = CLAIM_LIST_RE.match(tail) + listed = ID_LIST_RE.match(tail) if listed: - found.update(part.strip().upper() for part in listed.group(1).split(",")) - elif re.match(r"^(the items below|a second batch)\b", tail, re.IGNORECASE): - for bullet in lines[index + 1:]: - if not re.match(r"^\s*[-*]\s+", bullet): - continue - found.update(re.findall(BACKTICK + r"([A-Z0-9]+(?:-[A-Z0-9]+)+)" + BACKTICK, bullet)) + found.update(ids_from_text(listed.group(1))) + continue + batch_intro = re.match( + r"^(?:the items below|a second batch)\b", + tail, + re.IGNORECASE, + ) + if tail and not batch_intro: + continue + cursor = index + 1 + while cursor < len(lines) and not lines[cursor].strip(): + cursor += 1 + bullets = [] + while cursor < len(lines): + bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) + if not bullet: + break + bullets.append(bullet.group(1)) + cursor += 1 + for bullet in bullets: + first_ids = ID_LIST_RE.match(bullet.strip().strip(BACKTICK)) + if first_ids: + found.update(ids_from_text(first_ids.group(1))) return found - + + def open_work_ids(body): in_open_work = False result = set() @@ -114,19 +138,8 @@ jobs: if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): result.add(item_id) return result - - def find_ids(text, allowed): - text = text or "" - return { - item_id - for item_id in allowed - if re.search( - rf"(?", "", pull.get("body") or "") + for field in CLAIM_FIELD_RE.finditer(body): + value = field.group(1) + found.update(ids_from_text(value) & allowed_ids) + for comment_id in re.findall(r"#issuecomment-(\d+)", value): + linked = comments_by_id.get(comment_id) + if linked: + found.update( + ids_from_claim_comment(linked.get("body") or "") & allowed_ids + ) + return found + + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: event = json.load(event_file) pull = event.get("pull_request") or {} @@ -142,41 +171,25 @@ jobs: opened_at = parse_time(pull.get("created_at")) if not author or opened_at is None: fail("Cannot determine the PR author or opening time.") - + issue = request_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") - comments = get_collection(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments") + comments = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" + ) comments_by_id = {str(comment.get("id")): comment for comment in comments} claims_by_id = {} for comment in comments: - for item_id in claim_ids_from_comment(comment.get("body") or ""): + for item_id in ids_from_claim_comment(comment.get("body") or ""): claims_by_id.setdefault(item_id, []).append(comment) - - work_ids = open_work_ids(issue.get("body") or "") - allowed_ids = work_ids | set(claims_by_id) - title = pull.get("title") or "" - title_candidates = find_ids(title, allowed_ids) - candidates = set(title_candidates) - if not candidates: - body = re.sub(r"", "", pull.get("body") or "") - field = CLAIM_FIELD_RE.search(body) - if field: - value = field.group(1) - linked = re.search(r"#issuecomment-(\d+)", value) - if linked: - linked_comment = comments_by_id.get(linked.group(1)) - if linked_comment: - candidates.update( - claim_ids_from_comment(linked_comment.get("body") or "") & allowed_ids - ) - if not candidates: - candidates.update(find_ids(value, allowed_ids)) - + + allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + candidates = pull_claim_ids(pull, allowed_ids, comments_by_id) if not candidates: fail( - "Put one or more item IDs from issue #14 in the PR title or " + "Put one or more work-item IDs from issue #14 in the PR title or " "the 'Claimed in the coordination issue as' field." ) - + owners = set() for item_id in sorted(candidates): prior_claims = [] @@ -189,11 +202,16 @@ jobs: for comment in prior_claims } if not prior_claims: - fail(f"No claim for {item_id} was posted before the PR was opened.") + fail( + f"No unchanged claim for {item_id} predates this PR. " + "Post the claim first and open a replacement PR." + ) if len(claim_owners) != 1: fail(f"Claim {item_id} has multiple owners; resolve it in issue #14.") owners.update(claim_owners) - + if owners != {author}: - fail("Every claim must have one owner, and that owner must match the PR author.") + fail("Every declared claim must have one owner, and that owner must match the PR author.") print("Coordination claim verified for " + ", ".join(sorted(candidates)) + ".") + + PY From cbf2a71374859e4d7ee909b407f674aa7be47f8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:07:02 -0300 Subject: [PATCH 09/53] fix: isolate activity roster in managed comment --- .github/workflows/coordination-activity.yml | 337 ++++++++++++++------ 1 file changed, 231 insertions(+), 106 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 8d26b6ac99..62f6376025 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -6,6 +6,8 @@ on: workflow_run: workflows: ["Coordination claim"] types: [completed] + schedule: + - cron: "*/15 * * * *" workflow_dispatch: permissions: {} @@ -17,17 +19,18 @@ concurrency: jobs: sync-activity: if: >- - (github.event_name == 'issue_comment' && github.event.issue.number == 14) || - (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') || - github.event_name == 'workflow_dispatch' + github.event_name != 'issue_comment' || + (github.event.issue.number == 14 && + github.event.comment.user.login != 'github-actions[bot]') name: sync-issue-activity runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 10 permissions: + actions: write issues: write pull-requests: read steps: - - name: Refresh the managed activity block in issue #14 + - name: Refresh the Action-owned activity comment env: GITHUB_TOKEN: ${{ github.token }} run: | @@ -37,31 +40,32 @@ jobs: import re import sys import urllib.error + import urllib.parse import urllib.request from collections import defaultdict from datetime import datetime, timezone - + API = "https://api.github.com" OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) TOKEN = os.environ["GITHUB_TOKEN"] ISSUE_NUMBER = 14 BEGIN = "" END = "" - WORK_ID_RE = re.compile(r"[A-Z0-9]+(?:-[A-Z0-9]+)+") - CLAIM_LIST_RE = re.compile( - r"^([A-Z0-9]+(?:-[A-Z0-9]+)+" - r"(?:\s*,\s*[A-Z0-9]+(?:-[A-Z0-9]+)+)*)" - ) + ID_PATTERN = r"[A-Z0-9]+(?:-[A-Z0-9]+)+" + WORK_ID_RE = re.compile(ID_PATTERN) + ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)", re.IGNORECASE) CLAIM_FIELD_RE = re.compile( r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) BACKTICK = chr(96) - + + def stop(message): safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") print(f"::error title=Coordination activity::{safe}") sys.exit(1) - + + def api_json(path, method="GET", payload=None): data = None if payload is None else json.dumps(payload).encode("utf-8") request = urllib.request.Request( @@ -77,12 +81,14 @@ jobs: ) try: with urllib.request.urlopen(request, timeout=25) as response: - return json.load(response) + raw = response.read() + return json.loads(raw) if raw else {} except urllib.error.HTTPError as error: - stop(f"GitHub API request failed (HTTP {error.code}); issue #14 was not changed.") + stop(f"GitHub API request failed (HTTP {error.code}); the activity comment was not changed.") except (urllib.error.URLError, TimeoutError): - stop("Cannot reach GitHub; issue #14 was not changed.") - + stop("Cannot reach GitHub; the activity comment was not changed.") + + def get_collection(path, label): result = [] for page in range(1, 101): @@ -93,8 +99,13 @@ jobs: if len(batch) < 100: return result stop(f"The {label} collection is too large to sync safely.") - - def claim_ids_from_comment(body): + + + def ids_from_text(text): + return {value.upper() for value in WORK_ID_RE.findall(text or "")} + + + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() for index, line in enumerate(lines): @@ -102,16 +113,34 @@ jobs: if not match: continue tail = match.group(1).strip() - listed = CLAIM_LIST_RE.match(tail) + listed = ID_LIST_RE.match(tail) if listed: - found.update(part.strip().upper() for part in listed.group(1).split(",")) - elif re.match(r"^(the items below|a second batch)\b", tail, re.IGNORECASE): - for bullet in lines[index + 1:]: - if not re.match(r"^\s*[-*]\s+", bullet): - continue - found.update(re.findall(BACKTICK + r"([A-Z0-9]+(?:-[A-Z0-9]+)+)" + BACKTICK, bullet)) + found.update(ids_from_text(listed.group(1))) + continue + batch_intro = re.match( + r"^(?:the items below|a second batch)\b", + tail, + re.IGNORECASE, + ) + if tail and not batch_intro: + continue + cursor = index + 1 + while cursor < len(lines) and not lines[cursor].strip(): + cursor += 1 + bullets = [] + while cursor < len(lines): + bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) + if not bullet: + break + bullets.append(bullet.group(1)) + cursor += 1 + for bullet in bullets: + first_ids = ID_LIST_RE.match(bullet.strip().strip(BACKTICK)) + if first_ids: + found.update(ids_from_text(first_ids.group(1))) return found - + + def open_work_ids(body): in_open_work = False result = set() @@ -131,19 +160,8 @@ jobs: if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): result.add(item_id) return result - - def find_ids(text, allowed): - text = text or "" - return { - item_id - for item_id in allowed - if re.search( - rf"(?", "", pull.get("body") or "") + for field in CLAIM_FIELD_RE.finditer(body): + value = field.group(1) + found.update(ids_from_text(value) & allowed_ids) + for comment_id in re.findall(r"#issuecomment-(\d+)", value): + linked = comments_by_id.get(comment_id) + if linked: + found.update( + ids_from_claim_comment(linked.get("body") or "") & allowed_ids + ) + return found + + def evaluate_claim(pull, allowed_ids, claims_by_id, comments_by_id): author = ((pull.get("user") or {}).get("login") or "") opened_at = parse_time(pull.get("created_at")) if not author or opened_at is None: return "invalid", set(), None, {} - title_candidates = find_ids(pull.get("title") or "", allowed_ids) - candidates = set(title_candidates) + candidates = pull_claim_ids(pull, allowed_ids, comments_by_id) if not candidates: - body = re.sub(r"", "", pull.get("body") or "") - field = CLAIM_FIELD_RE.search(body) - if field: - value = field.group(1) - linked = re.search(r"#issuecomment-(\d+)", value) - if linked: - linked_comment = comments_by_id.get(linked.group(1)) - if linked_comment: - candidates.update( - claim_ids_from_comment(linked_comment.get("body") or "") & allowed_ids - ) - if not candidates: - candidates.update(find_ids(value, allowed_ids)) - if not candidates: - return "unclaimed", set(), None, {} - + return "needs-claim", set(), None, {} owners = set() links = {} for item_id in sorted(candidates): @@ -196,7 +214,8 @@ jobs: if len(owners) != 1 or next(iter(owners)).casefold() != author.casefold(): return "invalid", candidates, None, {} return "claimed", candidates, author, links - + + def safe_cell(value, limit=180): value = re.sub(r"[\r\n\t]+", " ", str(value or "")).strip() value = ( @@ -207,65 +226,143 @@ jobs: .replace("]", "\\]") .replace("<", "<") .replace(">", ">") - .replace("@", "@") + .replace("@", "@") ) if len(value) > limit: value = value[:limit - 3].rstrip() + "..." return value - + + + def changed_claim_ids(event): + comment = event.get("comment") or {} + bodies = [comment.get("body") or ""] + old_body = ((event.get("changes") or {}).get("body") or {}).get("from") + if old_body: + bodies.append(old_body) + found = set() + for body in bodies: + found.update(ids_from_claim_comment(body)) + return found, str(comment.get("id") or "") + + + def rerun_affected_checks(event, pulls, allowed_ids, comments_by_id): + changed_ids, changed_comment_id = changed_claim_ids(event) + if not changed_ids and not changed_comment_id: + return 0 + rerun = 0 + for pull in pulls: + if pull_claim_ids(pull, allowed_ids | changed_ids, comments_by_id).isdisjoint(changed_ids): + body = re.sub(r"", "", pull.get("body") or "") + linked_ids = { + comment_id + for field in CLAIM_FIELD_RE.finditer(body) + for comment_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) + } + if changed_comment_id not in linked_ids: + continue + head = pull.get("head") or {} + sha = head.get("sha") + if not sha: + continue + workflow = urllib.parse.quote("coordination-claim.yml", safe="") + encoded_sha = urllib.parse.quote(sha, safe="") + result = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/workflows/{workflow}/runs" + f"?event=pull_request&head_sha={encoded_sha}&per_page=100" + ) + runs = result.get("workflow_runs") or [] + selected = None + for run in runs: + if run.get("status") != "completed": + continue + associated = run.get("pull_requests") or [] + if associated: + matches = any( + item.get("number") == pull.get("number") + for item in associated + ) + else: + matches = ( + run.get("head_sha") == sha + and run.get("head_branch") == head.get("ref") + ) + if matches: + selected = run + break + if selected: + try: + api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{selected['id']}/rerun", + method="POST", + ) + rerun += 1 + except SystemExit: + print( + f"::warning::Could not re-run claim check for PR #{pull.get('number')}." + ) + return rerun + + issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", "issue #14 comments", ) pulls = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/pulls", + f"/repos/{OWNER}/{REPOSITORY}/pulls?state=open", "open pull requests", ) pulls = [pull for pull in pulls if pull.get("state") == "open"] comments_by_id = {str(comment.get("id")): comment for comment in comments} claims_by_id = defaultdict(list) for comment in comments: - for item_id in claim_ids_from_comment(comment.get("body") or ""): + for item_id in ids_from_claim_comment(comment.get("body") or ""): claims_by_id[item_id].append(comment) allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) - - activity_rows = [] + + event_name = os.environ.get("GITHUB_EVENT_NAME") + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: + event = json.load(event_file) + rerun_count = 0 + if event_name == "issue_comment": + rerun_count = rerun_affected_checks(event, pulls, allowed_ids, comments_by_id) + + groups = defaultdict(list) for pull in pulls: status, item_ids, owner, links = evaluate_claim( pull, allowed_ids, claims_by_id, comments_by_id ) - activity_rows.append((pull, status, item_ids, owner, links)) - - groups = defaultdict(list) - for row in activity_rows: - pull = row[0] - groups[((pull.get("user") or {}).get("login") or "unknown")].append(row) - + author = ((pull.get("user") or {}).get("login") or "unknown") + groups[author].append((pull, status, item_ids, owner, links)) + updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") section = [ BEGIN, "## Current open pull request activity", "", f"Updated: **{updated_at}** — **{len(pulls)} open PRs** across **{len(groups)} submitters**.", - "PR author is the submitter; it does not establish ownership. A linked claim is valid only when its issue #14 comment predates the PR and the claimant matches the author. Rows marked **Needs claim** require a valid claim. The action reports status only; it never closes or assigns a PR.", + "PR author is the submitter; it does not establish ownership. A claim is valid only when every declared work ID has one unchanged issue #14 claim that predates the PR and names the same owner as its author. Rows marked **Needs claim** need a valid claim. The Action reports status only; it never closes or assigns a PR.", "", - "Submitters are grouped below. The Action replaces only this marked block; all surrounding issue text remains editable.", + "Edit the **Open work** table and rules in this issue directly. The Action manages only this separate comment.", ] for author in sorted(groups, key=str.casefold): - author_rows = sorted(groups[author], key=lambda row: row[0].get("number", 0), reverse=True) - section.extend([ - "", - f"### {BACKTICK}{safe_cell(author)}{BACKTICK} — {len(author_rows)} open PRs", - "", - "| PR | Claim / owner | Work (PR title) | State |", - "|---|---|---|---|", - ]) + author_rows = sorted( + groups[author], + key=lambda row: row[0].get("number", 0), + reverse=True, + ) + section.extend( + [ + "", + f"### {BACKTICK}{safe_cell(author)}{BACKTICK} — {len(author_rows)} open PRs", + "", + "| PR | Claim / owner | Work (PR title) | State |", + "|---|---|---|---|", + ] + ) for pull, status, item_ids, owner, links in author_rows: - claim_cell = "Unclaimed" - if status == "invalid": - claim_cell = "Needs claim" - elif status == "claimed": + claim_cell = "Needs claim" + if status == "claimed": rendered = [] for item_id in sorted(item_ids): comment_id = links.get(item_id) @@ -275,32 +372,60 @@ jobs: ) rendered.append(f"[{BACKTICK}{item_id}{BACKTICK}]({comment_url})") claim_cell = ", ".join(rendered) + f" — {BACKTICK}{safe_cell(owner)}{BACKTICK}" - pr_url = pull.get("html_url") or f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" + pr_url = pull.get("html_url") or ( + f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" + ) pr_label = f"[#{pull.get('number')}]({pr_url})" title = safe_cell(pull.get("title") or "") state = "Draft" if pull.get("draft") else "Ready" section.append(f"| {pr_label} | {claim_cell} | {title} | {state} |") section.append(END) managed_block = "\n".join(section) - - current_body = issue.get("body") or "" - if current_body.count(BEGIN) != 1 or current_body.count(END) != 1: - stop("Issue #14 must contain exactly one pair of activity markers; it was not changed.") - start = current_body.index(BEGIN) - end = current_body.index(END) - if end < start: - stop("Issue #14 activity markers are out of order; it was not changed.") - end += len(END) - new_body = current_body[:start] + managed_block + current_body[end:] - if len(new_body) > 65536: - stop("The activity table would exceed GitHub's issue-body limit; the prior table was kept.") - if new_body == current_body: - print(f"Issue #14 is already current ({len(pulls)} open PRs).") + + action_comments = [ + comment + for comment in comments + if (comment.get("user") or {}).get("login") == "github-actions[bot]" + and (BEGIN in (comment.get("body") or "") or END in (comment.get("body") or "")) + ] + if len(action_comments) > 1: + stop("More than one managed activity comment exists; no comment was changed.") + + if action_comments: + comment = action_comments[0] + current_body = comment.get("body") or "" + if current_body.count(BEGIN) != 1 or current_body.count(END) != 1: + stop("The managed activity comment markers are malformed; no comment was changed.") + start = current_body.index(BEGIN) + end = current_body.index(END) + if end < start: + stop("The managed activity comment markers are out of order; no comment was changed.") + end += len(END) + new_body = current_body[:start] + managed_block + current_body[end:] + normalize = lambda value: re.sub( + r"(?m)^Updated: \*\*.*$", + "Updated: *timestamp*", + value, + ) + if len(new_body) > 65536: + stop("The activity comment would exceed GitHub's comment limit; the previous comment was kept.") + if normalize(new_body) == normalize(current_body): + print(f"Activity comment is already current ({len(pulls)} open PRs; {rerun_count} checks re-run).") + else: + api_json( + f"/repos/{OWNER}/{REPOSITORY}/issues/comments/{comment.get('id')}", + method="PATCH", + payload={"body": new_body}, + ) + print(f"Updated the activity comment with {len(pulls)} open PRs across {len(groups)} submitters.") else: + if len(managed_block) > 65536: + stop("The activity comment would exceed GitHub's comment limit; no comment was created.") api_json( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", - method="PATCH", - payload={"body": new_body}, + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + method="POST", + payload={"body": managed_block}, ) - print(f"Updated issue #14 with {len(pulls)} open PRs across {len(groups)} submitters.") + print(f"Created the activity comment with {len(pulls)} open PRs across {len(groups)} submitters.") + PY From d72a680b941f6b69ac4a9358050ea001c4a36ff3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:07:54 -0300 Subject: [PATCH 10/53] fix: strip PR comments when rechecking claims --- .github/workflows/coordination-activity.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 62f6376025..2d565a9814 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -252,7 +252,7 @@ jobs: rerun = 0 for pull in pulls: if pull_claim_ids(pull, allowed_ids | changed_ids, comments_by_id).isdisjoint(changed_ids): - body = re.sub(r"", "", pull.get("body") or "") + body = re.sub(r"", "", pull.get("body") or "") linked_ids = { comment_id for field in CLAIM_FIELD_RE.finditer(body) From 288c777b268f35bc3e86b4ce7dacdfe8b46513b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:19:21 -0300 Subject: [PATCH 11/53] fix: validate the current PR head and strict claim batches --- .github/workflows/coordination-claim.yml | 95 +++++++++++++----------- 1 file changed, 50 insertions(+), 45 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 3c79f64fd3..a1a2b64c43 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -36,7 +36,7 @@ jobs: ISSUE_NUMBER = 14 ID_PATTERN = r"[A-Z0-9]+(?:-[A-Z0-9]+)+" WORK_ID_RE = re.compile(ID_PATTERN) - ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)", re.IGNORECASE) + ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)") CLAIM_FIELD_RE = re.compile( r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) @@ -83,42 +83,40 @@ jobs: return {value.upper() for value in WORK_ID_RE.findall(text or "")} - def ids_from_claim_comment(body): - lines = (body or "").splitlines() - found = set() - for index, line in enumerate(lines): - match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) - if not match: - continue - tail = match.group(1).strip() - listed = ID_LIST_RE.match(tail) - if listed: - found.update(ids_from_text(listed.group(1))) - continue - batch_intro = re.match( - r"^(?:the items below|a second batch)\b", - tail, - re.IGNORECASE, - ) - if tail and not batch_intro: - continue - cursor = index + 1 - while cursor < len(lines) and not lines[cursor].strip(): - cursor += 1 - bullets = [] - while cursor < len(lines): - bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) - if not bullet: - break - bullets.append(bullet.group(1)) - cursor += 1 - for bullet in bullets: - first_ids = ID_LIST_RE.match(bullet.strip().strip(BACKTICK)) - if first_ids: - found.update(ids_from_text(first_ids.group(1))) - return found - - + def ids_from_claim_comment(body): + lines = (body or "").splitlines() + found = set() + for index, line in enumerate(lines): + match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + if not match: + continue + tail = match.group(1).strip() + listed = ID_LIST_RE.match(tail) + if listed: + found.update(ids_from_text(listed.group(1))) + continue + batch_intro = re.match( + r"^(?:the items below|a second batch)\b", + tail, + re.IGNORECASE, + ) + if tail and not batch_intro: + continue + cursor = index + 1 + while cursor < len(lines) and not lines[cursor].strip(): + cursor += 1 + while cursor < len(lines): + bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) + if not bullet: + break + first_ids = ID_LIST_RE.match( + bullet.group(1).strip().strip(BACKTICK) + ) + if not first_ids: + break + found.update(ids_from_text(first_ids.group(1))) + cursor += 1 + return found def open_work_ids(body): in_open_work = False result = set() @@ -164,14 +162,21 @@ jobs: return found - with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: - event = json.load(event_file) - pull = event.get("pull_request") or {} - author = ((pull.get("user") or {}).get("login") or "").casefold() - opened_at = parse_time(pull.get("created_at")) - if not author or opened_at is None: - fail("Cannot determine the PR author or opening time.") - + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: + event = json.load(event_file) + event_pull = event.get("pull_request") or {} + pull_number = event_pull.get("number") or event.get("number") + event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") + if not pull_number or not event_head_sha: + fail("Cannot determine the PR number or event head SHA.") + pull = request_json(f"/repos/{OWNER}/{REPOSITORY}/pulls/{pull_number}") + live_head_sha = ((pull.get("head") or {}).get("sha") or "") + if live_head_sha != event_head_sha: + fail("The PR head changed after this run was queued; check the current PR head.") + author = ((pull.get("user") or {}).get("login") or "").casefold() + opened_at = parse_time(pull.get("created_at")) + if not author or opened_at is None: + fail("Cannot determine the current PR author or opening time.") issue = request_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" From 927f9c3c0aa006c10962887b27dc9ae89dbd296a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:21:33 -0300 Subject: [PATCH 12/53] fix: reconcile activity pagination and stale claim checks --- .github/workflows/coordination-activity.yml | 239 ++++++++++++++------ 1 file changed, 172 insertions(+), 67 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 2d565a9814..84f5e70a9b 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -39,6 +39,7 @@ jobs: import os import re import sys + import time import urllib.error import urllib.parse import urllib.request @@ -53,7 +54,7 @@ jobs: END = "" ID_PATTERN = r"[A-Z0-9]+(?:-[A-Z0-9]+)+" WORK_ID_RE = re.compile(ID_PATTERN) - ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)", re.IGNORECASE) + ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)") CLAIM_FIELD_RE = re.compile( r"(?im)^\s*>?\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) @@ -92,7 +93,8 @@ jobs: def get_collection(path, label): result = [] for page in range(1, 101): - batch = api_json(f"{path}?per_page=100&page={page}") + separator = "&" if "?" in path else "?" + batch = api_json(f"{path}{separator}per_page=100&page={page}") if not isinstance(batch, list): stop(f"GitHub returned an invalid {label} response.") result.extend(batch) @@ -127,20 +129,18 @@ jobs: cursor = index + 1 while cursor < len(lines) and not lines[cursor].strip(): cursor += 1 - bullets = [] while cursor < len(lines): bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullets.append(bullet.group(1)) + first_ids = ID_LIST_RE.match( + bullet.group(1).strip().strip(BACKTICK) + ) + if not first_ids: + break + found.update(ids_from_text(first_ids.group(1))) cursor += 1 - for bullet in bullets: - first_ids = ID_LIST_RE.match(bullet.strip().strip(BACKTICK)) - if first_ids: - found.update(ids_from_text(first_ids.group(1))) return found - - def open_work_ids(body): in_open_work = False result = set() @@ -245,64 +245,162 @@ jobs: return found, str(comment.get("id") or "") - def rerun_affected_checks(event, pulls, allowed_ids, comments_by_id): - changed_ids, changed_comment_id = changed_claim_ids(event) - if not changed_ids and not changed_comment_id: - return 0 - rerun = 0 - for pull in pulls: - if pull_claim_ids(pull, allowed_ids | changed_ids, comments_by_id).isdisjoint(changed_ids): - body = re.sub(r"", "", pull.get("body") or "") - linked_ids = { - comment_id - for field in CLAIM_FIELD_RE.finditer(body) - for comment_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) - } - if changed_comment_id not in linked_ids: + def comment_change_targets_pull(pull, changed_ids, comment_id, allowed_ids, comments_by_id): + if not changed_ids and not comment_id: + return False + candidates = pull_claim_ids(pull, allowed_ids | changed_ids, comments_by_id) + if candidates & changed_ids: + return True + body = re.sub(r"", "", pull.get("body") or "") + linked_ids = { + linked_id + for field in CLAIM_FIELD_RE.finditer(body) + for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) + } + return bool(comment_id and comment_id in linked_ids) + + + def list_claim_workflow_runs(): + workflow = urllib.parse.quote("coordination-claim.yml", safe="") + result = [] + for page in range(1, 101): + response = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/workflows/{workflow}/runs" + f"?event=pull_request&per_page=100&page={page}" + ) + batch = response.get("workflow_runs") + if not isinstance(batch, list): + stop("GitHub returned an invalid Coordination claim workflow-runs response.") + result.extend(batch) + if len(batch) < 100: + return result + stop("There are too many Coordination claim runs to reconcile safely.") + + + def run_matches_pull(run, pull): + head = pull.get("head") or {} + if run.get("event") != "pull_request" or run.get("head_sha") != head.get("sha"): + return False + associated = run.get("pull_requests") or [] + if associated: + return any( + str(item.get("number")) == str(pull.get("number")) + for item in associated + ) + return run.get("head_branch") == head.get("ref") + + + def latest_runs_by_pull(pulls, runs): + latest = {} + for run in runs: + for pull in pulls: + if not run_matches_pull(run, pull): continue - head = pull.get("head") or {} - sha = head.get("sha") - if not sha: + key = str(pull.get("number")) + sort_key = ( + run.get("created_at") or "", + int(run.get("run_attempt") or 1), + run.get("updated_at") or "", + ) + old = latest.get(key) + if old is None or sort_key > old[0]: + latest[key] = (sort_key, run) + return {key: value[1] for key, value in latest.items()} + + + def latest_claim_update(candidates, claims_by_id): + timestamps = [] + for item_id in candidates: + for comment in claims_by_id.get(item_id, []): + updated = parse_time(comment.get("updated_at") or comment.get("created_at")) + if updated is not None: + timestamps.append(updated) + return max(timestamps) if timestamps else None + + + def wait_for_run_completion(run): + if run.get("status") == "completed": + return run + current = run + for _ in range(24): + time.sleep(10) + current = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" + ) + if current.get("status") == "completed": + return current + return current + + + def reconcile_claim_checks( + event_name, + event, + pulls, + activity_rows, + allowed_ids, + claims_by_id, + comments_by_id, + ): + runs = list_claim_workflow_runs() + latest = latest_runs_by_pull(pulls, runs) + changed_ids, changed_comment_id = changed_claim_ids(event) + rerun_count = 0 + for pull, status, candidates, _owner, _links in activity_rows: + run = latest.get(str(pull.get("number"))) + if run is None: continue - workflow = urllib.parse.quote("coordination-claim.yml", safe="") - encoded_sha = urllib.parse.quote(sha, safe="") - result = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/workflows/{workflow}/runs" - f"?event=pull_request&head_sha={encoded_sha}&per_page=100" + force = ( + event_name == "issue_comment" + and comment_change_targets_pull( + pull, + changed_ids, + changed_comment_id, + allowed_ids, + comments_by_id, + ) ) - runs = result.get("workflow_runs") or [] - selected = None - for run in runs: - if run.get("status") != "completed": + if run.get("status") != "completed": + if not force: continue - associated = run.get("pull_requests") or [] - if associated: - matches = any( - item.get("number") == pull.get("number") - for item in associated - ) - else: - matches = ( - run.get("head_sha") == sha - and run.get("head_branch") == head.get("ref") - ) - if matches: - selected = run - break - if selected: - try: - api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{selected['id']}/rerun", - method="POST", - ) - rerun += 1 - except SystemExit: + run = wait_for_run_completion(run) + if run.get("status") != "completed": print( - f"::warning::Could not re-run claim check for PR #{pull.get('number')}." + f"::warning::Claim check for PR #{pull.get('number')} is still running; a later sync will reconcile it." ) - return rerun - + continue + expected = "success" if status == "claimed" else "failure" + if run.get("conclusion") == expected: + continue + attempt = int(run.get("run_attempt") or 1) + run_started = parse_time(run.get("run_started_at") or run.get("created_at")) + last_claim_change = latest_claim_update(candidates, claims_by_id) + changed_after_run = ( + run_started is not None + and last_claim_change is not None + and last_claim_change > run_started + ) + if not force and attempt >= 2 and not changed_after_run: + print( + f"::warning::Claim check for PR #{pull.get('number')} still differs from issue #14 after an automatic retry; inspect the run." + ) + continue + if attempt >= 50: + print( + f"::warning::Claim check for PR #{pull.get('number')} reached GitHub's rerun limit." + ) + continue + try: + api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}/rerun", + method="POST", + ) + rerun_count += 1 + except SystemExit: + print( + f"::warning::Could not re-run claim check for PR #{pull.get('number')}." + ) + return rerun_count issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", @@ -323,18 +421,25 @@ jobs: event_name = os.environ.get("GITHUB_EVENT_NAME") with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: event = json.load(event_file) - rerun_count = 0 - if event_name == "issue_comment": - rerun_count = rerun_affected_checks(event, pulls, allowed_ids, comments_by_id) - + activity_rows = [] groups = defaultdict(list) for pull in pulls: status, item_ids, owner, links = evaluate_claim( pull, allowed_ids, claims_by_id, comments_by_id ) + activity_rows.append((pull, status, item_ids, owner, links)) author = ((pull.get("user") or {}).get("login") or "unknown") groups[author].append((pull, status, item_ids, owner, links)) + rerun_count = reconcile_claim_checks( + event_name, + event, + pulls, + activity_rows, + allowed_ids, + claims_by_id, + comments_by_id, + ) updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") section = [ BEGIN, @@ -403,8 +508,8 @@ jobs: end += len(END) new_body = current_body[:start] + managed_block + current_body[end:] normalize = lambda value: re.sub( - r"(?m)^Updated: \*\*.*$", - "Updated: *timestamp*", + r"(?m)^(Updated: \*\*)[^*]+(\*\* — \*\*\d+ open PRs\*\* across \*\*\d+ submitters\*\*\.)$", + r"\1timestamp\2", value, ) if len(new_body) > 65536: From ad426b4d1fa0dc9e927ee8c645db9e8a0484f936 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:22:59 -0300 Subject: [PATCH 13/53] fix: correct claim workflow indentation --- .github/workflows/coordination-claim.yml | 98 ++++++++++++------------ 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index a1a2b64c43..ca0897267e 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -83,40 +83,40 @@ jobs: return {value.upper() for value in WORK_ID_RE.findall(text or "")} - def ids_from_claim_comment(body): - lines = (body or "").splitlines() - found = set() - for index, line in enumerate(lines): - match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) - if not match: - continue - tail = match.group(1).strip() - listed = ID_LIST_RE.match(tail) - if listed: - found.update(ids_from_text(listed.group(1))) - continue - batch_intro = re.match( - r"^(?:the items below|a second batch)\b", - tail, - re.IGNORECASE, - ) - if tail and not batch_intro: - continue - cursor = index + 1 - while cursor < len(lines) and not lines[cursor].strip(): - cursor += 1 - while cursor < len(lines): - bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) - if not bullet: - break - first_ids = ID_LIST_RE.match( - bullet.group(1).strip().strip(BACKTICK) - ) - if not first_ids: - break - found.update(ids_from_text(first_ids.group(1))) - cursor += 1 - return found + def ids_from_claim_comment(body): + lines = (body or "").splitlines() + found = set() + for index, line in enumerate(lines): + match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + if not match: + continue + tail = match.group(1).strip() + listed = ID_LIST_RE.match(tail) + if listed: + found.update(ids_from_text(listed.group(1))) + continue + batch_intro = re.match( + r"^(?:the items below|a second batch)\b", + tail, + re.IGNORECASE, + ) + if tail and not batch_intro: + continue + cursor = index + 1 + while cursor < len(lines) and not lines[cursor].strip(): + cursor += 1 + while cursor < len(lines): + bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) + if not bullet: + break + first_ids = ID_LIST_RE.match( + bullet.group(1).strip().strip(BACKTICK) + ) + if not first_ids: + break + found.update(ids_from_text(first_ids.group(1))) + cursor += 1 + return found def open_work_ids(body): in_open_work = False result = set() @@ -162,21 +162,21 @@ jobs: return found - with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: - event = json.load(event_file) - event_pull = event.get("pull_request") or {} - pull_number = event_pull.get("number") or event.get("number") - event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") - if not pull_number or not event_head_sha: - fail("Cannot determine the PR number or event head SHA.") - pull = request_json(f"/repos/{OWNER}/{REPOSITORY}/pulls/{pull_number}") - live_head_sha = ((pull.get("head") or {}).get("sha") or "") - if live_head_sha != event_head_sha: - fail("The PR head changed after this run was queued; check the current PR head.") - author = ((pull.get("user") or {}).get("login") or "").casefold() - opened_at = parse_time(pull.get("created_at")) - if not author or opened_at is None: - fail("Cannot determine the current PR author or opening time.") + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: + event = json.load(event_file) + event_pull = event.get("pull_request") or {} + pull_number = event_pull.get("number") or event.get("number") + event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") + if not pull_number or not event_head_sha: + fail("Cannot determine the PR number or event head SHA.") + pull = request_json(f"/repos/{OWNER}/{REPOSITORY}/pulls/{pull_number}") + live_head_sha = ((pull.get("head") or {}).get("sha") or "") + if live_head_sha != event_head_sha: + fail("The PR head changed after this run was queued; check the current PR head.") + author = ((pull.get("user") or {}).get("login") or "").casefold() + opened_at = parse_time(pull.get("created_at")) + if not author or opened_at is None: + fail("Cannot determine the current PR author or opening time.") issue = request_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" From 657971d51b8d6c87fe21b5d6d10902ebdaf265f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:25:47 -0300 Subject: [PATCH 14/53] fix: match claim runs to current PR heads --- .github/workflows/coordination-activity.yml | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 84f5e70a9b..33b49a59d1 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -279,17 +279,24 @@ jobs: def run_matches_pull(run, pull): head = pull.get("head") or {} - if run.get("event") != "pull_request" or run.get("head_sha") != head.get("sha"): + if run.get("event") != "pull_request": return False associated = run.get("pull_requests") or [] if associated: - return any( - str(item.get("number")) == str(pull.get("number")) + matches = [ + item for item in associated - ) - return run.get("head_branch") == head.get("ref") - - + if str(item.get("number")) == str(pull.get("number")) + ] + if not matches: + return False + associated_head = ((matches[0].get("head") or {}).get("sha") or "") + if associated_head: + return associated_head == head.get("sha") + return ( + run.get("head_sha") == head.get("sha") + and run.get("head_branch") == head.get("ref") + ) def latest_runs_by_pull(pulls, runs): latest = {} for run in runs: From 86a50c0893d7ea457dff79cce675e99018e694fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:34:50 -0300 Subject: [PATCH 15/53] fix: reject unresolved claims and add manual PR validation --- .github/workflows/coordination-claim.yml | 69 ++++++++++++++++-------- 1 file changed, 47 insertions(+), 22 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index ca0897267e..3c051f6fe1 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -4,12 +4,18 @@ on: pull_request: branches: [main] types: [opened, reopened, edited, synchronize, ready_for_review, converted_to_draft, closed] + workflow_dispatch: + inputs: + pr_number: + description: Current PR number to validate + required: true + type: number permissions: {} jobs: validate-claim: - if: github.event_name == 'pull_request' && github.event.action != 'closed' + if: (github.event_name == 'pull_request' && github.event.action != 'closed') || github.event_name == 'workflow_dispatch' name: coordination-claim runs-on: ubuntu-latest timeout-minutes: 3 @@ -34,9 +40,9 @@ jobs: OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) TOKEN = os.environ["GITHUB_TOKEN"] ISSUE_NUMBER = 14 - ID_PATTERN = r"[A-Z0-9]+(?:-[A-Z0-9]+)+" + ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) @@ -147,31 +153,43 @@ jobs: return None - def pull_claim_ids(pull, allowed_ids, comments_by_id): - found = ids_from_text(pull.get("title") or "") & allowed_ids + def pull_claim_ids(pull, comments_by_id): + found = ids_from_text(pull.get("title") or "") + unresolved_links = [] body = re.sub(r"", "", pull.get("body") or "") for field in CLAIM_FIELD_RE.finditer(body): value = field.group(1) - found.update(ids_from_text(value) & allowed_ids) + found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): linked = comments_by_id.get(comment_id) - if linked: - found.update( - ids_from_claim_comment(linked.get("body") or "") & allowed_ids - ) - return found - - + if not linked: + unresolved_links.append(comment_id) + continue + linked_ids = ids_from_claim_comment(linked.get("body") or "") + if not linked_ids: + unresolved_links.append(comment_id) + found.update(linked_ids) + return found, unresolved_links + event_name = os.environ.get("GITHUB_EVENT_NAME") with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: event = json.load(event_file) - event_pull = event.get("pull_request") or {} - pull_number = event_pull.get("number") or event.get("number") - event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") - if not pull_number or not event_head_sha: - fail("Cannot determine the PR number or event head SHA.") + if event_name == "workflow_dispatch": + try: + pull_number = int((event.get("inputs") or {}).get("pr_number") or 0) + except (TypeError, ValueError): + pull_number = 0 + event_head_sha = "" + else: + event_pull = event.get("pull_request") or {} + pull_number = event_pull.get("number") or event.get("number") + event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") + if not pull_number: + fail("Cannot determine the PR number.") pull = request_json(f"/repos/{OWNER}/{REPOSITORY}/pulls/{pull_number}") live_head_sha = ((pull.get("head") or {}).get("sha") or "") - if live_head_sha != event_head_sha: + if not live_head_sha: + fail("Cannot determine the current PR head.") + if event_head_sha and live_head_sha != event_head_sha: fail("The PR head changed after this run was queued; check the current PR head.") author = ((pull.get("user") or {}).get("login") or "").casefold() opened_at = parse_time(pull.get("created_at")) @@ -188,13 +206,20 @@ jobs: claims_by_id.setdefault(item_id, []).append(comment) allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) - candidates = pull_claim_ids(pull, allowed_ids, comments_by_id) + candidates, unresolved_links = pull_claim_ids(pull, comments_by_id) + if unresolved_links: + fail("The PR references a missing or non-claim issue comment.") if not candidates: fail( "Put one or more work-item IDs from issue #14 in the PR title or " "the 'Claimed in the coordination issue as' field." ) - + unknown_ids = candidates - allowed_ids + if unknown_ids: + fail( + "Unknown work-item IDs: " + ", ".join(sorted(unknown_ids)) + + ". Add them to the Open work table first." + ) owners = set() for item_id in sorted(candidates): prior_claims = [] @@ -217,6 +242,6 @@ jobs: if owners != {author}: fail("Every declared claim must have one owner, and that owner must match the PR author.") - print("Coordination claim verified for " + ", ".join(sorted(candidates)) + ".") + print(f"Coordination claim verified for PR #{pull_number} at head {live_head_sha}: " + ", ".join(sorted(candidates)) + ".") PY From f70cb976987a8e5349f41c3e9bddd03541a21c04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:37:03 -0300 Subject: [PATCH 16/53] fix: reconcile deleted claims and isolate sync concurrency --- .github/workflows/coordination-activity.yml | 673 ++++++++++++++++++-- 1 file changed, 635 insertions(+), 38 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 33b49a59d1..094bb29369 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -12,26 +12,23 @@ on: permissions: {} -concurrency: - group: coordination-activity - cancel-in-progress: false - jobs: - sync-activity: + reconcile-claims: if: >- github.event_name != 'issue_comment' || (github.event.issue.number == 14 && github.event.comment.user.login != 'github-actions[bot]') - name: sync-issue-activity + name: reconcile-claim-checks runs-on: ubuntu-latest timeout-minutes: 10 permissions: actions: write - issues: write + issues: read pull-requests: read steps: - - name: Refresh the Action-owned activity comment + - name: Reconcile claim-check runs env: + COORDINATION_MODE: reconcile GITHUB_TOKEN: ${{ github.token }} run: | python3 - <<'PY' @@ -39,6 +36,7 @@ jobs: import os import re import sys + from datetime import timedelta import time import urllib.error import urllib.parse @@ -52,7 +50,7 @@ jobs: ISSUE_NUMBER = 14 BEGIN = "" END = "" - ID_PATTERN = r"[A-Z0-9]+(?:-[A-Z0-9]+)+" + ID_PATTERN = r"(?", "", pull.get("body") or "") for field in CLAIM_FIELD_RE.finditer(body): value = field.group(1) - found.update(ids_from_text(value) & allowed_ids) + found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): linked = comments_by_id.get(comment_id) - if linked: - found.update( - ids_from_claim_comment(linked.get("body") or "") & allowed_ids - ) - return found - - + if not linked: + unresolved_links.append(comment_id) + continue + linked_ids = ids_from_claim_comment(linked.get("body") or "") + if not linked_ids: + unresolved_links.append(comment_id) + found.update(linked_ids) + return found, unresolved_links def evaluate_claim(pull, allowed_ids, claims_by_id, comments_by_id): author = ((pull.get("user") or {}).get("login") or "") opened_at = parse_time(pull.get("created_at")) if not author or opened_at is None: return "invalid", set(), None, {} - candidates = pull_claim_ids(pull, allowed_ids, comments_by_id) - if not candidates: + candidates, unresolved_links = pull_claim_ids(pull, comments_by_id) + if not candidates and not unresolved_links: return "needs-claim", set(), None, {} + if unresolved_links or candidates - allowed_ids: + return "invalid", candidates, None, {} owners = set() links = {} for item_id in sorted(candidates): @@ -214,8 +216,6 @@ jobs: if len(owners) != 1 or next(iter(owners)).casefold() != author.casefold(): return "invalid", candidates, None, {} return "claimed", candidates, author, links - - def safe_cell(value, limit=180): value = re.sub(r"[\r\n\t]+", " ", str(value or "")).strip() value = ( @@ -245,10 +245,10 @@ jobs: return found, str(comment.get("id") or "") - def comment_change_targets_pull(pull, changed_ids, comment_id, allowed_ids, comments_by_id): + def comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id): if not changed_ids and not comment_id: return False - candidates = pull_claim_ids(pull, allowed_ids | changed_ids, comments_by_id) + candidates, _unresolved = pull_claim_ids(pull, comments_by_id) if candidates & changed_ids: return True body = re.sub(r"", "", pull.get("body") or "") @@ -258,8 +258,6 @@ jobs: for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) } return bool(comment_id and comment_id in linked_ids) - - def list_claim_workflow_runs(): workflow = urllib.parse.quote("coordination-claim.yml", safe="") result = [] @@ -279,7 +277,16 @@ jobs: def run_matches_pull(run, pull): head = pull.get("head") or {} - if run.get("event") != "pull_request": + base = pull.get("base") or {} + source_repo = head.get("repo") or {} + run_source_repo = run.get("head_repository") or {} + if ( + run.get("event") != "pull_request" + or base.get("ref") != "main" + or not source_repo.get("id") + or not run_source_repo.get("id") + or str(source_repo.get("id")) != str(run_source_repo.get("id")) + ): return False associated = run.get("pull_requests") or [] if associated: @@ -344,7 +351,6 @@ jobs: event, pulls, activity_rows, - allowed_ids, claims_by_id, comments_by_id, ): @@ -352,7 +358,10 @@ jobs: latest = latest_runs_by_pull(pulls, runs) changed_ids, changed_comment_id = changed_claim_ids(event) rerun_count = 0 + now = datetime.now(timezone.utc) for pull, status, candidates, _owner, _links in activity_rows: + if ((pull.get("base") or {}).get("ref")) != "main": + continue run = latest.get(str(pull.get("number"))) if run is None: continue @@ -362,7 +371,6 @@ jobs: pull, changed_ids, changed_comment_id, - allowed_ids, comments_by_id, ) ) @@ -372,7 +380,7 @@ jobs: run = wait_for_run_completion(run) if run.get("status") != "completed": print( - f"::warning::Claim check for PR #{pull.get('number')} is still running; a later sync will reconcile it." + f"::warning::Claim check for PR #{pull.get('number')} is still running; the next sync will reconcile it." ) continue @@ -380,6 +388,12 @@ jobs: if run.get("conclusion") == expected: continue attempt = int(run.get("run_attempt") or 1) + created_at = parse_time(run.get("created_at")) + if created_at is not None and now - created_at > timedelta(days=30): + print( + f"::warning::Claim check for PR #{pull.get('number')} is outside GitHub's 30-day rerun window. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation; push a new PR commit to create a PR-associated check." + ) + continue run_started = parse_time(run.get("run_started_at") or run.get("created_at")) last_claim_change = latest_claim_update(candidates, claims_by_id) changed_after_run = ( @@ -387,17 +401,30 @@ jobs: and last_claim_change is not None and last_claim_change > run_started ) - if not force and attempt >= 2 and not changed_after_run: + if ( + expected == "success" + and run.get("conclusion") != "success" + and attempt >= 2 + and not force + and not changed_after_run + ): print( - f"::warning::Claim check for PR #{pull.get('number')} still differs from issue #14 after an automatic retry; inspect the run." + f"::warning::Claim check for PR #{pull.get('number')} remains failing after retry; inspect the run." ) continue - if attempt >= 50: + if attempt >= 51: print( - f"::warning::Claim check for PR #{pull.get('number')} reached GitHub's rerun limit." + f"::warning::Claim check for PR #{pull.get('number')} reached 50 reruns. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation, or push a new PR commit." ) continue try: + fresh = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" + ) + if fresh.get("status") != "completed": + continue + if fresh.get("conclusion") == expected: + continue api_json( f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}/rerun", method="POST", @@ -405,7 +432,7 @@ jobs: rerun_count += 1 except SystemExit: print( - f"::warning::Could not re-run claim check for PR #{pull.get('number')}." + f"::warning::Could not re-run claim check for PR #{pull.get('number')}; check its current head or use manual validation." ) return rerun_count issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") @@ -438,15 +465,585 @@ jobs: author = ((pull.get("user") or {}).get("login") or "unknown") groups[author].append((pull, status, item_ids, owner, links)) - rerun_count = reconcile_claim_checks( + mode = os.environ.get("COORDINATION_MODE", "sync") + rerun_count = 0 + if mode == "reconcile": + rerun_count = reconcile_claim_checks( + event_name, + event, + pulls, + activity_rows, + claims_by_id, + comments_by_id, + ) + print(f"Reconciled claim checks; requested {rerun_count} reruns.") + sys.exit(0) + if mode != "sync": + stop("Unknown coordination workflow mode.") + updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + section = [ + BEGIN, + "## Current open pull request activity", + "", + f"Updated: **{updated_at}** — **{len(pulls)} open PRs** across **{len(groups)} submitters**.", + "PR author is the submitter; it does not establish ownership. A claim is valid only when every declared work ID has one unchanged issue #14 claim that predates the PR and names the same owner as its author. Rows marked **Needs claim** need a valid claim. The Action reports status only; it never closes or assigns a PR.", + "", + "Edit the **Open work** table and rules in this issue directly. The Action manages only this separate comment.", + ] + for author in sorted(groups, key=str.casefold): + author_rows = sorted( + groups[author], + key=lambda row: row[0].get("number", 0), + reverse=True, + ) + section.extend( + [ + "", + f"### {BACKTICK}{safe_cell(author)}{BACKTICK} — {len(author_rows)} open PRs", + "", + "| PR | Claim / owner | Work (PR title) | State |", + "|---|---|---|---|", + ] + ) + for pull, status, item_ids, owner, links in author_rows: + claim_cell = "Needs claim" + if status == "claimed": + rendered = [] + for item_id in sorted(item_ids): + comment_id = links.get(item_id) + comment_url = ( + f"https://github.com/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}" + f"#issuecomment-{comment_id}" + ) + rendered.append(f"[{BACKTICK}{item_id}{BACKTICK}]({comment_url})") + claim_cell = ", ".join(rendered) + f" — {BACKTICK}{safe_cell(owner)}{BACKTICK}" + pr_url = pull.get("html_url") or ( + f"https://github.com/{OWNER}/{REPOSITORY}/pull/{pull.get('number')}" + ) + pr_label = f"[#{pull.get('number')}]({pr_url})" + title = safe_cell(pull.get("title") or "") + state = "Draft" if pull.get("draft") else "Ready" + section.append(f"| {pr_label} | {claim_cell} | {title} | {state} |") + section.append(END) + managed_block = "\n".join(section) + + action_comments = [ + comment + for comment in comments + if (comment.get("user") or {}).get("login") == "github-actions[bot]" + and (BEGIN in (comment.get("body") or "") or END in (comment.get("body") or "")) + ] + if len(action_comments) > 1: + stop("More than one managed activity comment exists; no comment was changed.") + + if action_comments: + comment = action_comments[0] + current_body = comment.get("body") or "" + if current_body.count(BEGIN) != 1 or current_body.count(END) != 1: + stop("The managed activity comment markers are malformed; no comment was changed.") + start = current_body.index(BEGIN) + end = current_body.index(END) + if end < start: + stop("The managed activity comment markers are out of order; no comment was changed.") + end += len(END) + new_body = current_body[:start] + managed_block + current_body[end:] + normalize = lambda value: re.sub( + r"(?m)^(Updated: \*\*)[^*]+(\*\* — \*\*\d+ open PRs\*\* across \*\*\d+ submitters\*\*\.)$", + r"\1timestamp\2", + value, + ) + if len(new_body) > 65536: + stop("The activity comment would exceed GitHub's comment limit; the previous comment was kept.") + if normalize(new_body) == normalize(current_body): + print(f"Activity comment is already current ({len(pulls)} open PRs; {rerun_count} checks re-run).") + else: + api_json( + f"/repos/{OWNER}/{REPOSITORY}/issues/comments/{comment.get('id')}", + method="PATCH", + payload={"body": new_body}, + ) + print(f"Updated the activity comment with {len(pulls)} open PRs across {len(groups)} submitters.") + else: + if len(managed_block) > 65536: + stop("The activity comment would exceed GitHub's comment limit; no comment was created.") + api_json( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + method="POST", + payload={"body": managed_block}, + ) + print(f"Created the activity comment with {len(pulls)} open PRs across {len(groups)} submitters.") + + PY + + sync-activity: + concurrency: + group: coordination-activity-comment + cancel-in-progress: false + if: >- + github.event_name != 'issue_comment' || + (github.event.issue.number == 14 && + github.event.comment.user.login != 'github-actions[bot]') + name: sync-issue-activity + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write + pull-requests: read + steps: + - name: Refresh the Action-owned activity comment + env: + COORDINATION_MODE: sync + GITHUB_TOKEN: ${{ github.token }} + run: | + python3 - <<'PY' + import json + import os + import re + import sys + from datetime import timedelta + import time + import urllib.error + import urllib.parse + import urllib.request + from collections import defaultdict + from datetime import datetime, timezone + + API = "https://api.github.com" + OWNER, REPOSITORY = os.environ["GITHUB_REPOSITORY"].split("/", 1) + TOKEN = os.environ["GITHUB_TOKEN"] + ISSUE_NUMBER = 14 + BEGIN = "" + END = "" + ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + ) + BACKTICK = chr(96) + + + def stop(message): + safe = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::error title=Coordination activity::{safe}") + sys.exit(1) + + + def api_json(path, method="GET", payload=None): + data = None if payload is None else json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + API + path, + data=data, + method=method, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(request, timeout=25) as response: + raw = response.read() + return json.loads(raw) if raw else {} + except urllib.error.HTTPError as error: + stop(f"GitHub API request failed (HTTP {error.code}); the activity comment was not changed.") + except (urllib.error.URLError, TimeoutError): + stop("Cannot reach GitHub; the activity comment was not changed.") + + + def get_collection(path, label): + result = [] + for page in range(1, 101): + separator = "&" if "?" in path else "?" + batch = api_json(f"{path}{separator}per_page=100&page={page}") + if not isinstance(batch, list): + stop(f"GitHub returned an invalid {label} response.") + result.extend(batch) + if len(batch) < 100: + return result + stop(f"The {label} collection is too large to sync safely.") + + + def ids_from_text(text): + return {value.upper() for value in WORK_ID_RE.findall(text or "")} + + + def ids_from_claim_comment(body): + lines = (body or "").splitlines() + found = set() + for index, line in enumerate(lines): + match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + if not match: + continue + tail = match.group(1).strip() + listed = ID_LIST_RE.match(tail) + if listed: + found.update(ids_from_text(listed.group(1))) + continue + batch_intro = re.match( + r"^(?:the items below|a second batch)\b", + tail, + re.IGNORECASE, + ) + if tail and not batch_intro: + continue + cursor = index + 1 + while cursor < len(lines) and not lines[cursor].strip(): + cursor += 1 + while cursor < len(lines): + bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) + if not bullet: + break + first_ids = ID_LIST_RE.match( + bullet.group(1).strip().strip(BACKTICK) + ) + if not first_ids: + break + found.update(ids_from_text(first_ids.group(1))) + cursor += 1 + return found + def open_work_ids(body): + in_open_work = False + result = set() + for line in (body or "").splitlines(): + if re.match(r"^##\s+Open work\b", line, re.IGNORECASE): + in_open_work = True + continue + if in_open_work and re.match(r"^##\s+", line): + break + if not in_open_work or not line.lstrip().startswith("|"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + if len(cells) < 5: + continue + item_id = cells[0].strip(BACKTICK).upper() + status = cells[-1].lower() + if item_id != "ID" and WORK_ID_RE.fullmatch(item_id) and status.startswith("open"): + result.add(item_id) + return result + + + def parse_time(value): + if not value: + return None + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + + + def pull_claim_ids(pull, comments_by_id): + found = ids_from_text(pull.get("title") or "") + unresolved_links = [] + body = re.sub(r"", "", pull.get("body") or "") + for field in CLAIM_FIELD_RE.finditer(body): + value = field.group(1) + found.update(ids_from_text(value)) + for comment_id in re.findall(r"#issuecomment-(\d+)", value): + linked = comments_by_id.get(comment_id) + if not linked: + unresolved_links.append(comment_id) + continue + linked_ids = ids_from_claim_comment(linked.get("body") or "") + if not linked_ids: + unresolved_links.append(comment_id) + found.update(linked_ids) + return found, unresolved_links + def evaluate_claim(pull, allowed_ids, claims_by_id, comments_by_id): + author = ((pull.get("user") or {}).get("login") or "") + opened_at = parse_time(pull.get("created_at")) + if not author or opened_at is None: + return "invalid", set(), None, {} + candidates, unresolved_links = pull_claim_ids(pull, comments_by_id) + if not candidates and not unresolved_links: + return "needs-claim", set(), None, {} + if unresolved_links or candidates - allowed_ids: + return "invalid", candidates, None, {} + owners = set() + links = {} + for item_id in sorted(candidates): + prior = [] + for comment in claims_by_id.get(item_id, []): + effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + if effective_at is not None and effective_at < opened_at: + prior.append(comment) + claim_owners = { + ((comment.get("user") or {}).get("login") or "").casefold() + for comment in prior + } + if not prior or len(claim_owners) != 1: + return "invalid", candidates, None, {} + owners.update(claim_owners) + prior.sort(key=lambda comment: comment.get("created_at") or "") + links[item_id] = str(prior[0].get("id") or "") + if len(owners) != 1 or next(iter(owners)).casefold() != author.casefold(): + return "invalid", candidates, None, {} + return "claimed", candidates, author, links + def safe_cell(value, limit=180): + value = re.sub(r"[\r\n\t]+", " ", str(value or "")).strip() + value = ( + value.replace("\\", "\\\\") + .replace("|", "\\|") + .replace(BACKTICK, "\\" + BACKTICK) + .replace("[", "\\[") + .replace("]", "\\]") + .replace("<", "<") + .replace(">", ">") + .replace("@", "@") + ) + if len(value) > limit: + value = value[:limit - 3].rstrip() + "..." + return value + + + def changed_claim_ids(event): + comment = event.get("comment") or {} + bodies = [comment.get("body") or ""] + old_body = ((event.get("changes") or {}).get("body") or {}).get("from") + if old_body: + bodies.append(old_body) + found = set() + for body in bodies: + found.update(ids_from_claim_comment(body)) + return found, str(comment.get("id") or "") + + + def comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id): + if not changed_ids and not comment_id: + return False + candidates, _unresolved = pull_claim_ids(pull, comments_by_id) + if candidates & changed_ids: + return True + body = re.sub(r"", "", pull.get("body") or "") + linked_ids = { + linked_id + for field in CLAIM_FIELD_RE.finditer(body) + for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) + } + return bool(comment_id and comment_id in linked_ids) + def list_claim_workflow_runs(): + workflow = urllib.parse.quote("coordination-claim.yml", safe="") + result = [] + for page in range(1, 101): + response = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/workflows/{workflow}/runs" + f"?event=pull_request&per_page=100&page={page}" + ) + batch = response.get("workflow_runs") + if not isinstance(batch, list): + stop("GitHub returned an invalid Coordination claim workflow-runs response.") + result.extend(batch) + if len(batch) < 100: + return result + stop("There are too many Coordination claim runs to reconcile safely.") + + + def run_matches_pull(run, pull): + head = pull.get("head") or {} + base = pull.get("base") or {} + source_repo = head.get("repo") or {} + run_source_repo = run.get("head_repository") or {} + if ( + run.get("event") != "pull_request" + or base.get("ref") != "main" + or not source_repo.get("id") + or not run_source_repo.get("id") + or str(source_repo.get("id")) != str(run_source_repo.get("id")) + ): + return False + associated = run.get("pull_requests") or [] + if associated: + matches = [ + item + for item in associated + if str(item.get("number")) == str(pull.get("number")) + ] + if not matches: + return False + associated_head = ((matches[0].get("head") or {}).get("sha") or "") + if associated_head: + return associated_head == head.get("sha") + return ( + run.get("head_sha") == head.get("sha") + and run.get("head_branch") == head.get("ref") + ) + def latest_runs_by_pull(pulls, runs): + latest = {} + for run in runs: + for pull in pulls: + if not run_matches_pull(run, pull): + continue + key = str(pull.get("number")) + sort_key = ( + run.get("created_at") or "", + int(run.get("run_attempt") or 1), + run.get("updated_at") or "", + ) + old = latest.get(key) + if old is None or sort_key > old[0]: + latest[key] = (sort_key, run) + return {key: value[1] for key, value in latest.items()} + + + def latest_claim_update(candidates, claims_by_id): + timestamps = [] + for item_id in candidates: + for comment in claims_by_id.get(item_id, []): + updated = parse_time(comment.get("updated_at") or comment.get("created_at")) + if updated is not None: + timestamps.append(updated) + return max(timestamps) if timestamps else None + + + def wait_for_run_completion(run): + if run.get("status") == "completed": + return run + current = run + for _ in range(24): + time.sleep(10) + current = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" + ) + if current.get("status") == "completed": + return current + return current + + + def reconcile_claim_checks( event_name, event, pulls, activity_rows, - allowed_ids, claims_by_id, comments_by_id, + ): + runs = list_claim_workflow_runs() + latest = latest_runs_by_pull(pulls, runs) + changed_ids, changed_comment_id = changed_claim_ids(event) + rerun_count = 0 + now = datetime.now(timezone.utc) + for pull, status, candidates, _owner, _links in activity_rows: + if ((pull.get("base") or {}).get("ref")) != "main": + continue + run = latest.get(str(pull.get("number"))) + if run is None: + continue + force = ( + event_name == "issue_comment" + and comment_change_targets_pull( + pull, + changed_ids, + changed_comment_id, + comments_by_id, + ) + ) + if run.get("status") != "completed": + if not force: + continue + run = wait_for_run_completion(run) + if run.get("status") != "completed": + print( + f"::warning::Claim check for PR #{pull.get('number')} is still running; the next sync will reconcile it." + ) + continue + + expected = "success" if status == "claimed" else "failure" + if run.get("conclusion") == expected: + continue + attempt = int(run.get("run_attempt") or 1) + created_at = parse_time(run.get("created_at")) + if created_at is not None and now - created_at > timedelta(days=30): + print( + f"::warning::Claim check for PR #{pull.get('number')} is outside GitHub's 30-day rerun window. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation; push a new PR commit to create a PR-associated check." + ) + continue + run_started = parse_time(run.get("run_started_at") or run.get("created_at")) + last_claim_change = latest_claim_update(candidates, claims_by_id) + changed_after_run = ( + run_started is not None + and last_claim_change is not None + and last_claim_change > run_started + ) + if ( + expected == "success" + and run.get("conclusion") != "success" + and attempt >= 2 + and not force + and not changed_after_run + ): + print( + f"::warning::Claim check for PR #{pull.get('number')} remains failing after retry; inspect the run." + ) + continue + if attempt >= 51: + print( + f"::warning::Claim check for PR #{pull.get('number')} reached 50 reruns. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation, or push a new PR commit." + ) + continue + try: + fresh = api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" + ) + if fresh.get("status") != "completed": + continue + if fresh.get("conclusion") == expected: + continue + api_json( + f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}/rerun", + method="POST", + ) + rerun_count += 1 + except SystemExit: + print( + f"::warning::Could not re-run claim check for PR #{pull.get('number')}; check its current head or use manual validation." + ) + return rerun_count + issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") + comments = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + "issue #14 comments", + ) + pulls = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/pulls?state=open", + "open pull requests", ) + pulls = [pull for pull in pulls if pull.get("state") == "open"] + comments_by_id = {str(comment.get("id")): comment for comment in comments} + claims_by_id = defaultdict(list) + for comment in comments: + for item_id in ids_from_claim_comment(comment.get("body") or ""): + claims_by_id[item_id].append(comment) + allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + + event_name = os.environ.get("GITHUB_EVENT_NAME") + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: + event = json.load(event_file) + activity_rows = [] + groups = defaultdict(list) + for pull in pulls: + status, item_ids, owner, links = evaluate_claim( + pull, allowed_ids, claims_by_id, comments_by_id + ) + activity_rows.append((pull, status, item_ids, owner, links)) + author = ((pull.get("user") or {}).get("login") or "unknown") + groups[author].append((pull, status, item_ids, owner, links)) + + mode = os.environ.get("COORDINATION_MODE", "sync") + rerun_count = 0 + if mode == "reconcile": + rerun_count = reconcile_claim_checks( + event_name, + event, + pulls, + activity_rows, + claims_by_id, + comments_by_id, + ) + print(f"Reconciled claim checks; requested {rerun_count} reruns.") + sys.exit(0) + if mode != "sync": + stop("Unknown coordination workflow mode.") updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") section = [ BEGIN, From 81efef0baba18ab4e11811606e64b374bce1d10b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 01:45:34 -0300 Subject: [PATCH 17/53] fix: enforce complete work IDs in activity batches --- .github/workflows/coordination-activity.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 094bb29369..f12ee447f2 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -52,7 +52,7 @@ jobs: END = "" ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) @@ -616,7 +616,7 @@ jobs: END = "" ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" ) From beab7943a66b96937a3a1529a0938ff35b54ca3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:12:00 -0300 Subject: [PATCH 18/53] fix: validate only catalogued claims --- .github/workflows/coordination-claim.yml | 37 ++++++++++-------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 3c051f6fe1..475274b32b 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -4,19 +4,13 @@ on: pull_request: branches: [main] types: [opened, reopened, edited, synchronize, ready_for_review, converted_to_draft, closed] - workflow_dispatch: - inputs: - pr_number: - description: Current PR number to validate - required: true - type: number permissions: {} jobs: validate-claim: - if: (github.event_name == 'pull_request' && github.event.action != 'closed') || github.event_name == 'workflow_dispatch' - name: coordination-claim + if: github.event.action != 'closed' + name: coordination-claim-validator runs-on: ubuntu-latest timeout-minutes: 3 permissions: @@ -89,6 +83,13 @@ jobs: return {value.upper() for value in WORK_ID_RE.findall(text or "")} + def work_id_list(text): + listed = ID_LIST_RE.match(text) + if listed and re.match(r"^\s*,", text[listed.end():]): + return None + return listed + + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -97,7 +98,7 @@ jobs: if not match: continue tail = match.group(1).strip() - listed = ID_LIST_RE.match(tail) + listed = work_id_list(tail) if listed: found.update(ids_from_text(listed.group(1))) continue @@ -115,7 +116,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - first_ids = ID_LIST_RE.match( + first_ids = work_id_list( bullet.group(1).strip().strip(BACKTICK) ) if not first_ids: @@ -170,19 +171,11 @@ jobs: unresolved_links.append(comment_id) found.update(linked_ids) return found, unresolved_links - event_name = os.environ.get("GITHUB_EVENT_NAME") with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: event = json.load(event_file) - if event_name == "workflow_dispatch": - try: - pull_number = int((event.get("inputs") or {}).get("pr_number") or 0) - except (TypeError, ValueError): - pull_number = 0 - event_head_sha = "" - else: - event_pull = event.get("pull_request") or {} - pull_number = event_pull.get("number") or event.get("number") - event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") + event_pull = event.get("pull_request") or {} + pull_number = event_pull.get("number") or event.get("number") + event_head_sha = ((event_pull.get("head") or {}).get("sha") or "") if not pull_number: fail("Cannot determine the PR number.") pull = request_json(f"/repos/{OWNER}/{REPOSITORY}/pulls/{pull_number}") @@ -205,7 +198,7 @@ jobs: for item_id in ids_from_claim_comment(comment.get("body") or ""): claims_by_id.setdefault(item_id, []).append(comment) - allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + allowed_ids = open_work_ids(issue.get("body") or "") candidates, unresolved_links = pull_claim_ids(pull, comments_by_id) if unresolved_links: fail("The PR references a missing or non-claim issue comment.") From 0096c2f41b085ed4304bc2f133793c38070a26d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:13:42 -0300 Subject: [PATCH 19/53] fix: publish current claim status on PR heads --- .github/workflows/coordination-activity.yml | 559 ++++++++------------ 1 file changed, 232 insertions(+), 327 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index f12ee447f2..ee984e317e 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -8,25 +8,36 @@ on: types: [completed] schedule: - cron: "*/15 * * * *" + - cron: "17 * * * *" workflow_dispatch: + inputs: + pr_number: + description: PR number whose current claim status should be refreshed + required: false + type: number permissions: {} jobs: reconcile-claims: + concurrency: + group: coordination-claim-status + cancel-in-progress: false if: >- - github.event_name != 'issue_comment' || + (github.event_name != 'issue_comment' || (github.event.issue.number == 14 && - github.event.comment.user.login != 'github-actions[bot]') - name: reconcile-claim-checks + github.event.comment.user.login != 'github-actions[bot]')) && + (github.event_name != 'schedule' || + github.event.schedule == '17 * * * *') + name: publish-coordination-claim-status runs-on: ubuntu-latest timeout-minutes: 10 permissions: - actions: write issues: read pull-requests: read + statuses: write steps: - - name: Reconcile claim-check runs + - name: Publish current claim status for PR heads env: COORDINATION_MODE: reconcile GITHUB_TOKEN: ${{ github.token }} @@ -36,10 +47,7 @@ jobs: import os import re import sys - from datetime import timedelta - import time import urllib.error - import urllib.parse import urllib.request from collections import defaultdict from datetime import datetime, timezone @@ -83,9 +91,9 @@ jobs: raw = response.read() return json.loads(raw) if raw else {} except urllib.error.HTTPError as error: - stop(f"GitHub API request failed (HTTP {error.code}); the activity comment was not changed.") + stop(f"GitHub API request failed (HTTP {error.code}); this coordination update may be incomplete.") except (urllib.error.URLError, TimeoutError): - stop("Cannot reach GitHub; the activity comment was not changed.") + stop("Cannot reach GitHub; this coordination update may be incomplete.") def get_collection(path, label): @@ -105,6 +113,13 @@ jobs: return {value.upper() for value in WORK_ID_RE.findall(text or "")} + def work_id_list(text): + listed = ID_LIST_RE.match(text) + if listed and re.match(r"^\s*,", text[listed.end():]): + return None + return listed + + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -113,7 +128,7 @@ jobs: if not match: continue tail = match.group(1).strip() - listed = ID_LIST_RE.match(tail) + listed = work_id_list(tail) if listed: found.update(ids_from_text(listed.group(1))) continue @@ -131,7 +146,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - first_ids = ID_LIST_RE.match( + first_ids = work_id_list( bullet.group(1).strip().strip(BACKTICK) ) if not first_ids: @@ -258,41 +273,28 @@ jobs: for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) } return bool(comment_id and comment_id in linked_ids) - def list_claim_workflow_runs(): - workflow = urllib.parse.quote("coordination-claim.yml", safe="") - result = [] - for page in range(1, 101): - response = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/workflows/{workflow}/runs" - f"?event=pull_request&per_page=100&page={page}" - ) - batch = response.get("workflow_runs") - if not isinstance(batch, list): - stop("GitHub returned an invalid Coordination claim workflow-runs response.") - result.extend(batch) - if len(batch) < 100: - return result - stop("There are too many Coordination claim runs to reconcile safely.") - - - def run_matches_pull(run, pull): + def workflow_run_matches_pull(run, pull): head = pull.get("head") or {} base = pull.get("base") or {} source_repo = head.get("repo") or {} run_source_repo = run.get("head_repository") or {} + run_created = parse_time(run.get("created_at")) + pull_created = parse_time(pull.get("created_at")) if ( run.get("event") != "pull_request" or base.get("ref") != "main" or not source_repo.get("id") or not run_source_repo.get("id") or str(source_repo.get("id")) != str(run_source_repo.get("id")) + or run_created is None + or pull_created is None + or run_created < pull_created ): return False associated = run.get("pull_requests") or [] if associated: matches = [ - item - for item in associated + item for item in associated if str(item.get("number")) == str(pull.get("number")) ] if not matches: @@ -300,141 +302,103 @@ jobs: associated_head = ((matches[0].get("head") or {}).get("sha") or "") if associated_head: return associated_head == head.get("sha") - return ( - run.get("head_sha") == head.get("sha") - and run.get("head_branch") == head.get("ref") - ) - def latest_runs_by_pull(pulls, runs): - latest = {} - for run in runs: - for pull in pulls: - if not run_matches_pull(run, pull): - continue - key = str(pull.get("number")) - sort_key = ( - run.get("created_at") or "", - int(run.get("run_attempt") or 1), - run.get("updated_at") or "", - ) - old = latest.get(key) - if old is None or sort_key > old[0]: - latest[key] = (sort_key, run) - return {key: value[1] for key, value in latest.items()} - + return run.get("head_sha") == head.get("sha") + return run.get("head_sha") == head.get("sha") and run.get("head_branch") == head.get("ref") - def latest_claim_update(candidates, claims_by_id): - timestamps = [] - for item_id in candidates: - for comment in claims_by_id.get(item_id, []): - updated = parse_time(comment.get("updated_at") or comment.get("created_at")) - if updated is not None: - timestamps.append(updated) - return max(timestamps) if timestamps else None - - - def wait_for_run_completion(run): - if run.get("status") == "completed": - return run - current = run - for _ in range(24): - time.sleep(10) - current = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" - ) - if current.get("status") == "completed": - return current - return current - - - def reconcile_claim_checks( - event_name, - event, - pulls, - activity_rows, - claims_by_id, - comments_by_id, - ): - runs = list_claim_workflow_runs() - latest = latest_runs_by_pull(pulls, runs) - changed_ids, changed_comment_id = changed_claim_ids(event) - rerun_count = 0 - now = datetime.now(timezone.utc) - for pull, status, candidates, _owner, _links in activity_rows: - if ((pull.get("base") or {}).get("ref")) != "main": - continue - run = latest.get(str(pull.get("number"))) - if run is None: - continue - force = ( - event_name == "issue_comment" - and comment_change_targets_pull( - pull, - changed_ids, - changed_comment_id, - comments_by_id, - ) - ) - if run.get("status") != "completed": - if not force: - continue - run = wait_for_run_completion(run) - if run.get("status") != "completed": - print( - f"::warning::Claim check for PR #{pull.get('number')} is still running; the next sync will reconcile it." - ) - continue - expected = "success" if status == "claimed" else "failure" - if run.get("conclusion") == expected: - continue - attempt = int(run.get("run_attempt") or 1) - created_at = parse_time(run.get("created_at")) - if created_at is not None and now - created_at > timedelta(days=30): - print( - f"::warning::Claim check for PR #{pull.get('number')} is outside GitHub's 30-day rerun window. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation; push a new PR commit to create a PR-associated check." - ) - continue - run_started = parse_time(run.get("run_started_at") or run.get("created_at")) - last_claim_change = latest_claim_update(candidates, claims_by_id) - changed_after_run = ( - run_started is not None - and last_claim_change is not None - and last_claim_change > run_started - ) + def status_target_pulls(event_name, event, pulls, comments_by_id): + if event_name == "issue_comment": if ( - expected == "success" - and run.get("conclusion") != "success" - and attempt >= 2 - and not force - and not changed_after_run + str((event.get("issue") or {}).get("number")) != str(ISSUE_NUMBER) + or ((event.get("comment") or {}).get("user") or {}).get("login") == "github-actions[bot]" ): - print( - f"::warning::Claim check for PR #{pull.get('number')} remains failing after retry; inspect the run." - ) - continue - if attempt >= 51: - print( - f"::warning::Claim check for PR #{pull.get('number')} reached 50 reruns. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation, or push a new PR commit." - ) + return [] + changed_ids, comment_id = changed_claim_ids(event) + if event.get("action") == "deleted" and not changed_ids: + return pulls + return [ + pull for pull in pulls + if comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id) + ] + if event_name == "workflow_run": + run = event.get("workflow_run") or {} + associated = run.get("pull_requests") or [] + if associated: + numbers = {str(item.get("number")) for item in associated} + return [ + pull for pull in pulls + if str(pull.get("number")) in numbers and workflow_run_matches_pull(run, pull) + ] + return [pull for pull in pulls if workflow_run_matches_pull(run, pull)] + if event_name == "workflow_dispatch": + try: + target_number = int((event.get("inputs") or {}).get("pr_number") or 0) + except (TypeError, ValueError): + target_number = 0 + return [pull for pull in pulls if str(pull.get("number")) == str(target_number)] + if event_name == "schedule" and event.get("schedule") == "17 * * * *": + return pulls + return [] + + + def publish_claim_statuses(event_name, event, pulls, activity_rows, comments_by_id): + targets = status_target_pulls(event_name, event, pulls, comments_by_id) + target_shas = { + ((pull.get("head") or {}).get("sha") or "") + for pull in targets + if ((pull.get("base") or {}).get("ref")) == "main" + } + by_sha = defaultdict(list) + for pull, status, _items, _owner, _links in activity_rows: + if ((pull.get("base") or {}).get("ref")) != "main": continue + sha = ((pull.get("head") or {}).get("sha") or "") + if sha and sha in target_shas: + by_sha[sha].append(status) + updated = 0 + failures = [] + for sha, statuses in by_sha.items(): + invalid_count = sum(status != "claimed" for status in statuses) + state = "failure" if invalid_count else "success" + description = ( + f"{invalid_count} of {len(statuses)} open PR(s) have missing or invalid claims" + if invalid_count + else f"Claims valid for {len(statuses)} open PR(s)" + ) try: - fresh = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" + combined = api_json(f"/repos/{OWNER}/{REPOSITORY}/commits/{sha}/status") + existing = [ + item for item in (combined.get("statuses") or []) + if item.get("context") == "coordination-claim" + ] + latest = max( + existing, + key=lambda item: item.get("created_at") or "", + default=None, ) - if fresh.get("status") != "completed": - continue - if fresh.get("conclusion") == expected: + if latest and latest.get("state") == state and latest.get("description") == description: continue api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}/rerun", + f"/repos/{OWNER}/{REPOSITORY}/statuses/{sha}", method="POST", + payload={ + "state": state, + "context": "coordination-claim", + "description": description, + "target_url": f"https://github.com/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", + }, ) - rerun_count += 1 + updated += 1 except SystemExit: - print( - f"::warning::Could not re-run claim check for PR #{pull.get('number')}; check its current head or use manual validation." - ) - return rerun_count + failures.append(sha) + print(f"::warning::Could not publish coordination-claim status for head {sha}.") + if failures: + stop("Could not publish claim status for " + ", ".join(failures) + ".") + if not targets: + print("No PR heads were selected for claim-status publication.") + return updated + + issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", @@ -450,7 +414,7 @@ jobs: for comment in comments: for item_id in ids_from_claim_comment(comment.get("body") or ""): claims_by_id[item_id].append(comment) - allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + allowed_ids = open_work_ids(issue.get("body") or "") event_name = os.environ.get("GITHUB_EVENT_NAME") with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: @@ -466,17 +430,11 @@ jobs: groups[author].append((pull, status, item_ids, owner, links)) mode = os.environ.get("COORDINATION_MODE", "sync") - rerun_count = 0 if mode == "reconcile": - rerun_count = reconcile_claim_checks( - event_name, - event, - pulls, - activity_rows, - claims_by_id, - comments_by_id, + updated_statuses = publish_claim_statuses( + event_name, event, pulls, activity_rows, comments_by_id ) - print(f"Reconciled claim checks; requested {rerun_count} reruns.") + print(f"Published {updated_statuses} current-head coordination-claim status(es).") sys.exit(0) if mode != "sync": stop("Unknown coordination workflow mode.") @@ -555,7 +513,7 @@ jobs: if len(new_body) > 65536: stop("The activity comment would exceed GitHub's comment limit; the previous comment was kept.") if normalize(new_body) == normalize(current_body): - print(f"Activity comment is already current ({len(pulls)} open PRs; {rerun_count} checks re-run).") + print(f"Activity comment is already current ({len(pulls)} open PRs; {updated_statuses} statuses updated).") else: api_json( f"/repos/{OWNER}/{REPOSITORY}/issues/comments/{comment.get('id')}", @@ -600,10 +558,7 @@ jobs: import os import re import sys - from datetime import timedelta - import time import urllib.error - import urllib.parse import urllib.request from collections import defaultdict from datetime import datetime, timezone @@ -647,9 +602,9 @@ jobs: raw = response.read() return json.loads(raw) if raw else {} except urllib.error.HTTPError as error: - stop(f"GitHub API request failed (HTTP {error.code}); the activity comment was not changed.") + stop(f"GitHub API request failed (HTTP {error.code}); this coordination update may be incomplete.") except (urllib.error.URLError, TimeoutError): - stop("Cannot reach GitHub; the activity comment was not changed.") + stop("Cannot reach GitHub; this coordination update may be incomplete.") def get_collection(path, label): @@ -669,6 +624,13 @@ jobs: return {value.upper() for value in WORK_ID_RE.findall(text or "")} + def work_id_list(text): + listed = ID_LIST_RE.match(text) + if listed and re.match(r"^\s*,", text[listed.end():]): + return None + return listed + + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -677,7 +639,7 @@ jobs: if not match: continue tail = match.group(1).strip() - listed = ID_LIST_RE.match(tail) + listed = work_id_list(tail) if listed: found.update(ids_from_text(listed.group(1))) continue @@ -695,7 +657,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - first_ids = ID_LIST_RE.match( + first_ids = work_id_list( bullet.group(1).strip().strip(BACKTICK) ) if not first_ids: @@ -822,41 +784,28 @@ jobs: for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) } return bool(comment_id and comment_id in linked_ids) - def list_claim_workflow_runs(): - workflow = urllib.parse.quote("coordination-claim.yml", safe="") - result = [] - for page in range(1, 101): - response = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/workflows/{workflow}/runs" - f"?event=pull_request&per_page=100&page={page}" - ) - batch = response.get("workflow_runs") - if not isinstance(batch, list): - stop("GitHub returned an invalid Coordination claim workflow-runs response.") - result.extend(batch) - if len(batch) < 100: - return result - stop("There are too many Coordination claim runs to reconcile safely.") - - - def run_matches_pull(run, pull): + def workflow_run_matches_pull(run, pull): head = pull.get("head") or {} base = pull.get("base") or {} source_repo = head.get("repo") or {} run_source_repo = run.get("head_repository") or {} + run_created = parse_time(run.get("created_at")) + pull_created = parse_time(pull.get("created_at")) if ( run.get("event") != "pull_request" or base.get("ref") != "main" or not source_repo.get("id") or not run_source_repo.get("id") or str(source_repo.get("id")) != str(run_source_repo.get("id")) + or run_created is None + or pull_created is None + or run_created < pull_created ): return False associated = run.get("pull_requests") or [] if associated: matches = [ - item - for item in associated + item for item in associated if str(item.get("number")) == str(pull.get("number")) ] if not matches: @@ -864,141 +813,103 @@ jobs: associated_head = ((matches[0].get("head") or {}).get("sha") or "") if associated_head: return associated_head == head.get("sha") - return ( - run.get("head_sha") == head.get("sha") - and run.get("head_branch") == head.get("ref") - ) - def latest_runs_by_pull(pulls, runs): - latest = {} - for run in runs: - for pull in pulls: - if not run_matches_pull(run, pull): - continue - key = str(pull.get("number")) - sort_key = ( - run.get("created_at") or "", - int(run.get("run_attempt") or 1), - run.get("updated_at") or "", - ) - old = latest.get(key) - if old is None or sort_key > old[0]: - latest[key] = (sort_key, run) - return {key: value[1] for key, value in latest.items()} + return run.get("head_sha") == head.get("sha") + return run.get("head_sha") == head.get("sha") and run.get("head_branch") == head.get("ref") - def latest_claim_update(candidates, claims_by_id): - timestamps = [] - for item_id in candidates: - for comment in claims_by_id.get(item_id, []): - updated = parse_time(comment.get("updated_at") or comment.get("created_at")) - if updated is not None: - timestamps.append(updated) - return max(timestamps) if timestamps else None - - - def wait_for_run_completion(run): - if run.get("status") == "completed": - return run - current = run - for _ in range(24): - time.sleep(10) - current = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" - ) - if current.get("status") == "completed": - return current - return current - - - def reconcile_claim_checks( - event_name, - event, - pulls, - activity_rows, - claims_by_id, - comments_by_id, - ): - runs = list_claim_workflow_runs() - latest = latest_runs_by_pull(pulls, runs) - changed_ids, changed_comment_id = changed_claim_ids(event) - rerun_count = 0 - now = datetime.now(timezone.utc) - for pull, status, candidates, _owner, _links in activity_rows: - if ((pull.get("base") or {}).get("ref")) != "main": - continue - run = latest.get(str(pull.get("number"))) - if run is None: - continue - force = ( - event_name == "issue_comment" - and comment_change_targets_pull( - pull, - changed_ids, - changed_comment_id, - comments_by_id, - ) - ) - if run.get("status") != "completed": - if not force: - continue - run = wait_for_run_completion(run) - if run.get("status") != "completed": - print( - f"::warning::Claim check for PR #{pull.get('number')} is still running; the next sync will reconcile it." - ) - continue - - expected = "success" if status == "claimed" else "failure" - if run.get("conclusion") == expected: - continue - attempt = int(run.get("run_attempt") or 1) - created_at = parse_time(run.get("created_at")) - if created_at is not None and now - created_at > timedelta(days=30): - print( - f"::warning::Claim check for PR #{pull.get('number')} is outside GitHub's 30-day rerun window. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation; push a new PR commit to create a PR-associated check." - ) - continue - run_started = parse_time(run.get("run_started_at") or run.get("created_at")) - last_claim_change = latest_claim_update(candidates, claims_by_id) - changed_after_run = ( - run_started is not None - and last_claim_change is not None - and last_claim_change > run_started - ) + def status_target_pulls(event_name, event, pulls, comments_by_id): + if event_name == "issue_comment": if ( - expected == "success" - and run.get("conclusion") != "success" - and attempt >= 2 - and not force - and not changed_after_run + str((event.get("issue") or {}).get("number")) != str(ISSUE_NUMBER) + or ((event.get("comment") or {}).get("user") or {}).get("login") == "github-actions[bot]" ): - print( - f"::warning::Claim check for PR #{pull.get('number')} remains failing after retry; inspect the run." - ) - continue - if attempt >= 51: - print( - f"::warning::Claim check for PR #{pull.get('number')} reached 50 reruns. Dispatch Coordination claim with pr_number={pull.get('number')} for a fresh live validation, or push a new PR commit." - ) + return [] + changed_ids, comment_id = changed_claim_ids(event) + if event.get("action") == "deleted" and not changed_ids: + return pulls + return [ + pull for pull in pulls + if comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id) + ] + if event_name == "workflow_run": + run = event.get("workflow_run") or {} + associated = run.get("pull_requests") or [] + if associated: + numbers = {str(item.get("number")) for item in associated} + return [ + pull for pull in pulls + if str(pull.get("number")) in numbers and workflow_run_matches_pull(run, pull) + ] + return [pull for pull in pulls if workflow_run_matches_pull(run, pull)] + if event_name == "workflow_dispatch": + try: + target_number = int((event.get("inputs") or {}).get("pr_number") or 0) + except (TypeError, ValueError): + target_number = 0 + return [pull for pull in pulls if str(pull.get("number")) == str(target_number)] + if event_name == "schedule" and event.get("schedule") == "17 * * * *": + return pulls + return [] + + + def publish_claim_statuses(event_name, event, pulls, activity_rows, comments_by_id): + targets = status_target_pulls(event_name, event, pulls, comments_by_id) + target_shas = { + ((pull.get("head") or {}).get("sha") or "") + for pull in targets + if ((pull.get("base") or {}).get("ref")) == "main" + } + by_sha = defaultdict(list) + for pull, status, _items, _owner, _links in activity_rows: + if ((pull.get("base") or {}).get("ref")) != "main": continue + sha = ((pull.get("head") or {}).get("sha") or "") + if sha and sha in target_shas: + by_sha[sha].append(status) + updated = 0 + failures = [] + for sha, statuses in by_sha.items(): + invalid_count = sum(status != "claimed" for status in statuses) + state = "failure" if invalid_count else "success" + description = ( + f"{invalid_count} of {len(statuses)} open PR(s) have missing or invalid claims" + if invalid_count + else f"Claims valid for {len(statuses)} open PR(s)" + ) try: - fresh = api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}" + combined = api_json(f"/repos/{OWNER}/{REPOSITORY}/commits/{sha}/status") + existing = [ + item for item in (combined.get("statuses") or []) + if item.get("context") == "coordination-claim" + ] + latest = max( + existing, + key=lambda item: item.get("created_at") or "", + default=None, ) - if fresh.get("status") != "completed": - continue - if fresh.get("conclusion") == expected: + if latest and latest.get("state") == state and latest.get("description") == description: continue api_json( - f"/repos/{OWNER}/{REPOSITORY}/actions/runs/{run.get('id')}/rerun", + f"/repos/{OWNER}/{REPOSITORY}/statuses/{sha}", method="POST", + payload={ + "state": state, + "context": "coordination-claim", + "description": description, + "target_url": f"https://github.com/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", + }, ) - rerun_count += 1 + updated += 1 except SystemExit: - print( - f"::warning::Could not re-run claim check for PR #{pull.get('number')}; check its current head or use manual validation." - ) - return rerun_count + failures.append(sha) + print(f"::warning::Could not publish coordination-claim status for head {sha}.") + if failures: + stop("Could not publish claim status for " + ", ".join(failures) + ".") + if not targets: + print("No PR heads were selected for claim-status publication.") + return updated + + issue = api_json(f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}") comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", @@ -1014,7 +925,7 @@ jobs: for comment in comments: for item_id in ids_from_claim_comment(comment.get("body") or ""): claims_by_id[item_id].append(comment) - allowed_ids = open_work_ids(issue.get("body") or "") | set(claims_by_id) + allowed_ids = open_work_ids(issue.get("body") or "") event_name = os.environ.get("GITHUB_EVENT_NAME") with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file: @@ -1030,17 +941,11 @@ jobs: groups[author].append((pull, status, item_ids, owner, links)) mode = os.environ.get("COORDINATION_MODE", "sync") - rerun_count = 0 if mode == "reconcile": - rerun_count = reconcile_claim_checks( - event_name, - event, - pulls, - activity_rows, - claims_by_id, - comments_by_id, + updated_statuses = publish_claim_statuses( + event_name, event, pulls, activity_rows, comments_by_id ) - print(f"Reconciled claim checks; requested {rerun_count} reruns.") + print(f"Published {updated_statuses} current-head coordination-claim status(es).") sys.exit(0) if mode != "sync": stop("Unknown coordination workflow mode.") @@ -1119,7 +1024,7 @@ jobs: if len(new_body) > 65536: stop("The activity comment would exceed GitHub's comment limit; the previous comment was kept.") if normalize(new_body) == normalize(current_body): - print(f"Activity comment is already current ({len(pulls)} open PRs; {rerun_count} checks re-run).") + print(f"Activity comment is already current ({len(pulls)} open PRs; {updated_statuses} statuses updated).") else: api_json( f"/repos/{OWNER}/{REPOSITORY}/issues/comments/{comment.get('id')}", From 766b3bdf18d35d19edeef65b4cc7c7b54721397e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:20:22 -0300 Subject: [PATCH 20/53] fix: remove stale status count from activity log --- .github/workflows/coordination-activity.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index ee984e317e..b1c1406e96 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -513,7 +513,7 @@ jobs: if len(new_body) > 65536: stop("The activity comment would exceed GitHub's comment limit; the previous comment was kept.") if normalize(new_body) == normalize(current_body): - print(f"Activity comment is already current ({len(pulls)} open PRs; {updated_statuses} statuses updated).") + print(f"Activity comment is already current ({len(pulls)} open PRs).") else: api_json( f"/repos/{OWNER}/{REPOSITORY}/issues/comments/{comment.get('id')}", @@ -1024,7 +1024,7 @@ jobs: if len(new_body) > 65536: stop("The activity comment would exceed GitHub's comment limit; the previous comment was kept.") if normalize(new_body) == normalize(current_body): - print(f"Activity comment is already current ({len(pulls)} open PRs; {updated_statuses} statuses updated).") + print(f"Activity comment is already current ({len(pulls)} open PRs).") else: api_json( f"/repos/{OWNER}/{REPOSITORY}/issues/comments/{comment.get('id')}", From fe9588fc2ac2b8b38b0cbb00a1c3ab99861d231c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:27:35 -0300 Subject: [PATCH 21/53] fix: reconcile issue edits and shared PR heads --- .github/workflows/coordination-activity.yml | 61 +++++++++++++++++++-- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index b1c1406e96..95d4ad3b67 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -3,6 +3,10 @@ name: Coordination activity on: issue_comment: types: [created, edited, deleted] + issues: + types: [edited] + pull_request_target: + types: [closed] workflow_run: workflows: ["Coordination claim"] types: [completed] @@ -22,11 +26,14 @@ jobs: reconcile-claims: concurrency: group: coordination-claim-status + queue: max cancel-in-progress: false if: >- (github.event_name != 'issue_comment' || (github.event.issue.number == 14 && github.event.comment.user.login != 'github-actions[bot]')) && + (github.event_name != 'issues' || + github.event.issue.number == 14) && (github.event_name != 'schedule' || github.event.schedule == '17 * * * *') name: publish-coordination-claim-status @@ -320,14 +327,34 @@ jobs: pull for pull in pulls if comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id) ] + if event_name == "issues": + if str((event.get("issue") or {}).get("number")) == str(ISSUE_NUMBER): + return pulls + return [] + if event_name == "pull_request_target": + closed_pull = event.get("pull_request") or {} + if ((closed_pull.get("base") or {}).get("ref")) != "main": + return [] + closed_sha = ((closed_pull.get("head") or {}).get("sha") or "") + return [ + pull for pull in pulls + if ((pull.get("base") or {}).get("ref")) == "main" + and ((pull.get("head") or {}).get("sha") or "") == closed_sha + ] if event_name == "workflow_run": run = event.get("workflow_run") or {} associated = run.get("pull_requests") or [] if associated: - numbers = {str(item.get("number")) for item in associated} + associated_shas = { + ((item.get("head") or {}).get("sha") or "") + for item in associated + if (item.get("head") or {}).get("sha") + } + if run.get("head_sha"): + associated_shas.add(run.get("head_sha")) return [ pull for pull in pulls - if str(pull.get("number")) in numbers and workflow_run_matches_pull(run, pull) + if ((pull.get("head") or {}).get("sha") or "") in associated_shas ] return [pull for pull in pulls if workflow_run_matches_pull(run, pull)] if event_name == "workflow_dispatch": @@ -538,9 +565,11 @@ jobs: group: coordination-activity-comment cancel-in-progress: false if: >- - github.event_name != 'issue_comment' || + (github.event_name != 'issue_comment' || (github.event.issue.number == 14 && - github.event.comment.user.login != 'github-actions[bot]') + github.event.comment.user.login != 'github-actions[bot]')) && + (github.event_name != 'issues' || + github.event.issue.number == 14) name: sync-issue-activity runs-on: ubuntu-latest timeout-minutes: 5 @@ -831,14 +860,34 @@ jobs: pull for pull in pulls if comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id) ] + if event_name == "issues": + if str((event.get("issue") or {}).get("number")) == str(ISSUE_NUMBER): + return pulls + return [] + if event_name == "pull_request_target": + closed_pull = event.get("pull_request") or {} + if ((closed_pull.get("base") or {}).get("ref")) != "main": + return [] + closed_sha = ((closed_pull.get("head") or {}).get("sha") or "") + return [ + pull for pull in pulls + if ((pull.get("base") or {}).get("ref")) == "main" + and ((pull.get("head") or {}).get("sha") or "") == closed_sha + ] if event_name == "workflow_run": run = event.get("workflow_run") or {} associated = run.get("pull_requests") or [] if associated: - numbers = {str(item.get("number")) for item in associated} + associated_shas = { + ((item.get("head") or {}).get("sha") or "") + for item in associated + if (item.get("head") or {}).get("sha") + } + if run.get("head_sha"): + associated_shas.add(run.get("head_sha")) return [ pull for pull in pulls - if str(pull.get("number")) in numbers and workflow_run_matches_pull(run, pull) + if ((pull.get("head") or {}).get("sha") or "") in associated_shas ] return [pull for pull in pulls if workflow_run_matches_pull(run, pull)] if event_name == "workflow_dispatch": From 38122eeef8b51b5144e931ce0ec7ac5f45c48c1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:35:27 -0300 Subject: [PATCH 22/53] ci: reconcile coordination status across PR lifecycle changes --- .github/workflows/coordination-activity.yml | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 95d4ad3b67..20b5ec4004 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -6,7 +6,7 @@ on: issues: types: [edited] pull_request_target: - types: [closed] + types: [opened, reopened, synchronize, edited, ready_for_review, closed] workflow_run: workflows: ["Coordination claim"] types: [completed] @@ -332,15 +332,14 @@ jobs: return pulls return [] if event_name == "pull_request_target": - closed_pull = event.get("pull_request") or {} - if ((closed_pull.get("base") or {}).get("ref")) != "main": + changed_pull = event.get("pull_request") or {} + action = event.get("action") + base_ref = ((changed_pull.get("base") or {}).get("ref")) + if base_ref != "main" and action != "edited": return [] - closed_sha = ((closed_pull.get("head") or {}).get("sha") or "") - return [ - pull for pull in pulls - if ((pull.get("base") or {}).get("ref")) == "main" - and ((pull.get("head") or {}).get("sha") or "") == closed_sha - ] + # Recompute every open main-targeting head so shared-SHA statuses + # recover when a PR opens, changes commits, changes base, or closes. + return [pull for pull in pulls if ((pull.get("base") or {}).get("ref")) == "main"] if event_name == "workflow_run": run = event.get("workflow_run") or {} associated = run.get("pull_requests") or [] From 5231a7f9d0b62ec282e1384d5a1c6b41f7dc3727 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:43:46 -0300 Subject: [PATCH 23/53] ci: reject partial malformed claim batches --- .github/workflows/coordination-activity.yml | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 20b5ec4004..be0ef1b9a8 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -149,17 +149,23 @@ jobs: cursor = index + 1 while cursor < len(lines) and not lines[cursor].strip(): cursor += 1 + batch_ids = set() + batch_valid = True while cursor < len(lines): bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - first_ids = work_id_list( - bullet.group(1).strip().strip(BACKTICK) - ) + bullet_text = bullet.group(1).strip().strip(BACKTICK) + first_ids = work_id_list(bullet_text) if not first_ids: + leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) + if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): + batch_valid = False break - found.update(ids_from_text(first_ids.group(1))) + batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 + if batch_valid: + found.update(batch_ids) return found def open_work_ids(body): in_open_work = False From 36ed793918d6ec47929d789a8ada703e3096d8d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:43:50 -0300 Subject: [PATCH 24/53] ci: reject partial malformed claim batches --- .github/workflows/coordination-claim.yml | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 475274b32b..037ca92402 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -112,17 +112,23 @@ jobs: cursor = index + 1 while cursor < len(lines) and not lines[cursor].strip(): cursor += 1 + batch_ids = set() + batch_valid = True while cursor < len(lines): bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - first_ids = work_id_list( - bullet.group(1).strip().strip(BACKTICK) - ) + bullet_text = bullet.group(1).strip().strip(BACKTICK) + first_ids = work_id_list(bullet_text) if not first_ids: + leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) + if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): + batch_valid = False break - found.update(ids_from_text(first_ids.group(1))) + batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 + if batch_valid: + found.update(batch_ids) return found def open_work_ids(body): in_open_work = False From 0624f608fad7b4f5e226eb5101e975a8e4fca9b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:45:03 -0300 Subject: [PATCH 25/53] ci: reject partial malformed claim batches --- .github/workflows/coordination-activity.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index be0ef1b9a8..15e9f6fe71 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -167,6 +167,7 @@ jobs: if batch_valid: found.update(batch_ids) return found + def open_work_ids(body): in_open_work = False result = set() From cb16a722b626dc82a9f7977afb23e22d393f5fe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:45:07 -0300 Subject: [PATCH 26/53] ci: reject partial malformed claim batches --- .github/workflows/coordination-claim.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 037ca92402..1c85d8c94b 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -130,6 +130,7 @@ jobs: if batch_valid: found.update(batch_ids) return found + def open_work_ids(body): in_open_work = False result = set() From e011a775c80fd340f9ea3835a93b00ca5e8868a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:51:15 -0300 Subject: [PATCH 27/53] ci: align roster claim parsing with validator --- .github/workflows/coordination-activity.yml | 33 ++++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 15e9f6fe71..13c023e398 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -230,8 +230,13 @@ jobs: for item_id in sorted(candidates): prior = [] for comment in claims_by_id.get(item_id, []): - effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) - if effective_at is not None and effective_at < opened_at: + created_at = parse_time(comment.get("created_at")) + updated_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + if ( + created_at is not None + and updated_at == created_at + and created_at < opened_at + ): prior.append(comment) claim_owners = { ((comment.get("user") or {}).get("login") or "").casefold() @@ -688,18 +693,25 @@ jobs: cursor = index + 1 while cursor < len(lines) and not lines[cursor].strip(): cursor += 1 + batch_ids = set() + batch_valid = True while cursor < len(lines): bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - first_ids = work_id_list( - bullet.group(1).strip().strip(BACKTICK) - ) + bullet_text = bullet.group(1).strip().strip(BACKTICK) + first_ids = work_id_list(bullet_text) if not first_ids: + leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) + if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): + batch_valid = False break - found.update(ids_from_text(first_ids.group(1))) + batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 + if batch_valid: + found.update(batch_ids) return found + def open_work_ids(body): in_open_work = False result = set() @@ -762,8 +774,13 @@ jobs: for item_id in sorted(candidates): prior = [] for comment in claims_by_id.get(item_id, []): - effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) - if effective_at is not None and effective_at < opened_at: + created_at = parse_time(comment.get("created_at")) + updated_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + if ( + created_at is not None + and updated_at == created_at + and created_at < opened_at + ): prior.append(comment) claim_owners = { ((comment.get("user") or {}).get("login") or "").casefold() From 7e80ba14e955c174fe5066bf5bb7e39bd04d340b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:51:35 -0300 Subject: [PATCH 28/53] ci: reject edited claims in validator --- .github/workflows/coordination-claim.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 1c85d8c94b..ffb82b7ead 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -224,8 +224,13 @@ jobs: for item_id in sorted(candidates): prior_claims = [] for comment in claims_by_id.get(item_id, []): - effective_at = parse_time(comment.get("updated_at") or comment.get("created_at")) - if effective_at is not None and effective_at < opened_at: + created_at = parse_time(comment.get("created_at")) + updated_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + if ( + created_at is not None + and updated_at == created_at + and created_at < opened_at + ): prior_claims.append(comment) claim_owners = { ((comment.get("user") or {}).get("login") or "").casefold() From 3349d430efa8402b2fa694d9b615ef7ab39dcae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:55:13 -0300 Subject: [PATCH 29/53] ci: normalize markdown IDs and require update timestamps --- .github/workflows/coordination-activity.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 13c023e398..97edc9c3dc 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -155,7 +155,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullet_text = bullet.group(1).strip().strip(BACKTICK) + bullet_text = bullet.group(1).replace(BACKTICK, "").strip() first_ids = work_id_list(bullet_text) if not first_ids: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) @@ -231,7 +231,7 @@ jobs: prior = [] for comment in claims_by_id.get(item_id, []): created_at = parse_time(comment.get("created_at")) - updated_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + updated_at = parse_time(comment.get("updated_at")) if ( created_at is not None and updated_at == created_at @@ -699,7 +699,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullet_text = bullet.group(1).strip().strip(BACKTICK) + bullet_text = bullet.group(1).replace(BACKTICK, "").strip() first_ids = work_id_list(bullet_text) if not first_ids: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) @@ -775,7 +775,7 @@ jobs: prior = [] for comment in claims_by_id.get(item_id, []): created_at = parse_time(comment.get("created_at")) - updated_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + updated_at = parse_time(comment.get("updated_at")) if ( created_at is not None and updated_at == created_at From 762931f21e6202c1fb8b1a644e31d31c85cd5f9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 02:55:18 -0300 Subject: [PATCH 30/53] ci: normalize markdown IDs and require update timestamps --- .github/workflows/coordination-claim.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index ffb82b7ead..bb115c4990 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -118,7 +118,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullet_text = bullet.group(1).strip().strip(BACKTICK) + bullet_text = bullet.group(1).replace(BACKTICK, "").strip() first_ids = work_id_list(bullet_text) if not first_ids: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) @@ -225,7 +225,7 @@ jobs: prior_claims = [] for comment in claims_by_id.get(item_id, []): created_at = parse_time(comment.get("created_at")) - updated_at = parse_time(comment.get("updated_at") or comment.get("created_at")) + updated_at = parse_time(comment.get("updated_at")) if ( created_at is not None and updated_at == created_at From f6c26884a91689b4bd07af14deea7e18693b612d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:01:11 -0300 Subject: [PATCH 31/53] ci: verify issue-comment edit history --- .github/workflows/coordination-activity.yml | 66 +++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 97edc9c3dc..bf61877f75 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -116,6 +116,37 @@ jobs: stop(f"The {label} collection is too large to sync safely.") + def attach_comment_edit_metadata(comments): + query = ( + "query($ids: [ID!]!) { nodes(ids: $ids) { " + "... on IssueComment { fullDatabaseId lastEditedAt } } }" + ) + for offset in range(0, len(comments), 100): + batch = comments[offset : offset + 100] + node_ids = [comment.get("node_id") for comment in batch] + if any(not node_id for node_id in node_ids): + stop("Cannot verify issue comment edit history.") + result = api_json( + "/graphql", + method="POST", + payload={"query": query, "variables": {"ids": node_ids}}, + ) + if result.get("errors"): + stop("Cannot verify issue comment edit history.") + nodes = ((result.get("data") or {}).get("nodes")) + if not isinstance(nodes, list) or len(nodes) != len(batch): + stop("GitHub returned invalid issue comment edit metadata.") + edited_at_by_id = {} + for node in nodes: + if not isinstance(node, dict) or node.get("fullDatabaseId") is None: + stop("GitHub returned invalid issue comment edit metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node.get("lastEditedAt") + for comment in batch: + comment_id = str(comment.get("id") or "") + if comment_id not in edited_at_by_id: + stop("Could not match issue comment edit metadata.") + comment["_last_edited_at"] = edited_at_by_id[comment_id] + def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -235,6 +266,7 @@ jobs: if ( created_at is not None and updated_at == created_at + and comment.get("_last_edited_at") is None and created_at < opened_at ): prior.append(comment) @@ -442,6 +474,7 @@ jobs: f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", "issue #14 comments", ) + attach_comment_edit_metadata(comments) pulls = get_collection( f"/repos/{OWNER}/{REPOSITORY}/pulls?state=open", "open pull requests", @@ -660,6 +693,37 @@ jobs: stop(f"The {label} collection is too large to sync safely.") + def attach_comment_edit_metadata(comments): + query = ( + "query($ids: [ID!]!) { nodes(ids: $ids) { " + "... on IssueComment { fullDatabaseId lastEditedAt } } }" + ) + for offset in range(0, len(comments), 100): + batch = comments[offset : offset + 100] + node_ids = [comment.get("node_id") for comment in batch] + if any(not node_id for node_id in node_ids): + stop("Cannot verify issue comment edit history.") + result = api_json( + "/graphql", + method="POST", + payload={"query": query, "variables": {"ids": node_ids}}, + ) + if result.get("errors"): + stop("Cannot verify issue comment edit history.") + nodes = ((result.get("data") or {}).get("nodes")) + if not isinstance(nodes, list) or len(nodes) != len(batch): + stop("GitHub returned invalid issue comment edit metadata.") + edited_at_by_id = {} + for node in nodes: + if not isinstance(node, dict) or node.get("fullDatabaseId") is None: + stop("GitHub returned invalid issue comment edit metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node.get("lastEditedAt") + for comment in batch: + comment_id = str(comment.get("id") or "") + if comment_id not in edited_at_by_id: + stop("Could not match issue comment edit metadata.") + comment["_last_edited_at"] = edited_at_by_id[comment_id] + def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -779,6 +843,7 @@ jobs: if ( created_at is not None and updated_at == created_at + and comment.get("_last_edited_at") is None and created_at < opened_at ): prior.append(comment) @@ -987,6 +1052,7 @@ jobs: f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", "issue #14 comments", ) + attach_comment_edit_metadata(comments) pulls = get_collection( f"/repos/{OWNER}/{REPOSITORY}/pulls?state=open", "open pull requests", From 5fe606fe9627923e2669c01ac256f0c9c6d9cbf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:01:51 -0300 Subject: [PATCH 32/53] ci: reject edited issue claims by GraphQL metadata --- .github/workflows/coordination-claim.yml | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index bb115c4990..d956bc5b4d 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -79,6 +79,53 @@ jobs: fail("Issue #14 has too many comments to verify safely.") + def graphql_json(payload): + request = urllib.request.Request( + API + "/graphql", + data=json.dumps(payload).encode("utf-8"), + method="POST", + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(request, timeout=20) as response: + return json.load(response) + except urllib.error.HTTPError as error: + fail(f"Cannot verify issue comment edit history (HTTP {error.code}).") + except (urllib.error.URLError, TimeoutError): + fail("Cannot reach GitHub to verify issue comment edit history.") + + def attach_comment_edit_metadata(comments): + query = ( + "query($ids: [ID!]!) { nodes(ids: $ids) { " + "... on IssueComment { fullDatabaseId lastEditedAt } } }" + ) + for offset in range(0, len(comments), 100): + batch = comments[offset : offset + 100] + node_ids = [comment.get("node_id") for comment in batch] + if any(not node_id for node_id in node_ids): + fail("Cannot verify issue comment edit history.") + result = graphql_json({"query": query, "variables": {"ids": node_ids}}) + if result.get("errors"): + fail("Cannot verify issue comment edit history.") + nodes = ((result.get("data") or {}).get("nodes")) + if not isinstance(nodes, list) or len(nodes) != len(batch): + fail("GitHub returned invalid issue comment edit metadata.") + edited_at_by_id = {} + for node in nodes: + if not isinstance(node, dict) or node.get("fullDatabaseId") is None: + fail("GitHub returned invalid issue comment edit metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node.get("lastEditedAt") + for comment in batch: + comment_id = str(comment.get("id") or "") + if comment_id not in edited_at_by_id: + fail("Could not match issue comment edit metadata.") + comment["_last_edited_at"] = edited_at_by_id[comment_id] + def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -199,6 +246,7 @@ jobs: comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" ) + attach_comment_edit_metadata(comments) comments_by_id = {str(comment.get("id")): comment for comment in comments} claims_by_id = {} for comment in comments: @@ -229,6 +277,7 @@ jobs: if ( created_at is not None and updated_at == created_at + and comment.get("_last_edited_at") is None and created_at < opened_at ): prior_claims.append(comment) From a9c053247695c7d3f9fedd4846e57143e2a98a0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:09:00 -0300 Subject: [PATCH 33/53] ci: scope and harden claim comment metadata checks --- .github/workflows/coordination-activity.yml | 242 ++++++++++++++++---- 1 file changed, 202 insertions(+), 40 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index bf61877f75..a76442100d 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -54,6 +54,7 @@ jobs: import os import re import sys + import time import urllib.error import urllib.request from collections import defaultdict @@ -116,36 +117,106 @@ jobs: stop(f"The {label} collection is too large to sync safely.") - def attach_comment_edit_metadata(comments): + def graphql_json(payload): + for attempt in range(2): + request = urllib.request.Request( + API + "/graphql", + data=json.dumps(payload).encode("utf-8"), + method="POST", + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(request, timeout=25) as response: + result = json.load(response) + errors = result.get("errors") or [] + limited = any( + isinstance(error, dict) + and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in (error.get("message") or "").casefold() + ) + for error in errors + ) + retry_after = response.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if limited and attempt == 0 and delay is not None and 0 <= delay <= 20: + time.sleep(delay) + continue + return result + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace")[:300] + retry_after = error.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if error.code in (403, 429) and attempt == 0 and delay is not None and 0 <= delay <= 20: + time.sleep(delay) + continue + stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") + except (urllib.error.URLError, TimeoutError) as error: + stop(f"Cannot reach GitHub GraphQL API: {error}") + + def attach_comment_edit_metadata(comments, retry=True): + claim_comments = [ + comment for comment in comments + if ids_from_claim_comment(comment.get("body") or "") + ] + if not claim_comments: + return comments query = ( "query($ids: [ID!]!) { nodes(ids: $ids) { " "... on IssueComment { fullDatabaseId lastEditedAt } } }" ) - for offset in range(0, len(comments), 100): - batch = comments[offset : offset + 100] + edited_at_by_id = {} + for offset in range(0, len(claim_comments), 100): + batch = claim_comments[offset : offset + 100] node_ids = [comment.get("node_id") for comment in batch] if any(not node_id for node_id in node_ids): - stop("Cannot verify issue comment edit history.") - result = api_json( - "/graphql", - method="POST", - payload={"query": query, "variables": {"ids": node_ids}}, + stop("Cannot verify issue comment edit history: missing GraphQL node ID.") + result = graphql_json( + {"query": query, "variables": {"ids": node_ids}} ) - if result.get("errors"): - stop("Cannot verify issue comment edit history.") + errors = result.get("errors") or [] + if errors: + details = "; ".join( + str(error.get("message") or "GraphQL error") + for error in errors[:3] + if isinstance(error, dict) + ) + stop("Cannot verify issue comment edit history: " + details) nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): stop("GitHub returned invalid issue comment edit metadata.") - edited_at_by_id = {} for node in nodes: if not isinstance(node, dict) or node.get("fullDatabaseId") is None: - stop("GitHub returned invalid issue comment edit metadata.") - edited_at_by_id[str(node["fullDatabaseId"])] = node.get("lastEditedAt") - for comment in batch: - comment_id = str(comment.get("id") or "") - if comment_id not in edited_at_by_id: - stop("Could not match issue comment edit metadata.") - comment["_last_edited_at"] = edited_at_by_id[comment_id] + continue + if "lastEditedAt" not in node: + stop("GitHub omitted lastEditedAt from issue comment metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] + missing = [ + comment for comment in claim_comments + if str(comment.get("id") or "") not in edited_at_by_id + ] + if missing: + if retry: + refreshed = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + "issue #14 comments", + ) + return attach_comment_edit_metadata(refreshed, retry=False) + stop("Could not verify claim comment metadata after one fresh read.") + for comment in claim_comments: + comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] + return comments def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -158,6 +229,16 @@ jobs: return listed + def unwrap_work_id_code(text): + text = (text or "").strip() + quote = re.escape(BACKTICK) + inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) + if inline_code: + code_text = inline_code.group(1).strip() + if ID_LIST_RE.fullmatch(code_text): + return code_text + inline_code.group(2) + return text + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -186,7 +267,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullet_text = bullet.group(1).replace(BACKTICK, "").strip() + bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) if not first_ids: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) @@ -474,7 +555,7 @@ jobs: f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", "issue #14 comments", ) - attach_comment_edit_metadata(comments) + comments = attach_comment_edit_metadata(comments) pulls = get_collection( f"/repos/{OWNER}/{REPOSITORY}/pulls?state=open", "open pull requests", @@ -631,6 +712,7 @@ jobs: import os import re import sys + import time import urllib.error import urllib.request from collections import defaultdict @@ -693,36 +775,106 @@ jobs: stop(f"The {label} collection is too large to sync safely.") - def attach_comment_edit_metadata(comments): + def graphql_json(payload): + for attempt in range(2): + request = urllib.request.Request( + API + "/graphql", + data=json.dumps(payload).encode("utf-8"), + method="POST", + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(request, timeout=25) as response: + result = json.load(response) + errors = result.get("errors") or [] + limited = any( + isinstance(error, dict) + and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in (error.get("message") or "").casefold() + ) + for error in errors + ) + retry_after = response.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if limited and attempt == 0 and delay is not None and 0 <= delay <= 20: + time.sleep(delay) + continue + return result + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace")[:300] + retry_after = error.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if error.code in (403, 429) and attempt == 0 and delay is not None and 0 <= delay <= 20: + time.sleep(delay) + continue + stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") + except (urllib.error.URLError, TimeoutError) as error: + stop(f"Cannot reach GitHub GraphQL API: {error}") + + def attach_comment_edit_metadata(comments, retry=True): + claim_comments = [ + comment for comment in comments + if ids_from_claim_comment(comment.get("body") or "") + ] + if not claim_comments: + return comments query = ( "query($ids: [ID!]!) { nodes(ids: $ids) { " "... on IssueComment { fullDatabaseId lastEditedAt } } }" ) - for offset in range(0, len(comments), 100): - batch = comments[offset : offset + 100] + edited_at_by_id = {} + for offset in range(0, len(claim_comments), 100): + batch = claim_comments[offset : offset + 100] node_ids = [comment.get("node_id") for comment in batch] if any(not node_id for node_id in node_ids): - stop("Cannot verify issue comment edit history.") - result = api_json( - "/graphql", - method="POST", - payload={"query": query, "variables": {"ids": node_ids}}, + stop("Cannot verify issue comment edit history: missing GraphQL node ID.") + result = graphql_json( + {"query": query, "variables": {"ids": node_ids}} ) - if result.get("errors"): - stop("Cannot verify issue comment edit history.") + errors = result.get("errors") or [] + if errors: + details = "; ".join( + str(error.get("message") or "GraphQL error") + for error in errors[:3] + if isinstance(error, dict) + ) + stop("Cannot verify issue comment edit history: " + details) nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): stop("GitHub returned invalid issue comment edit metadata.") - edited_at_by_id = {} for node in nodes: if not isinstance(node, dict) or node.get("fullDatabaseId") is None: - stop("GitHub returned invalid issue comment edit metadata.") - edited_at_by_id[str(node["fullDatabaseId"])] = node.get("lastEditedAt") - for comment in batch: - comment_id = str(comment.get("id") or "") - if comment_id not in edited_at_by_id: - stop("Could not match issue comment edit metadata.") - comment["_last_edited_at"] = edited_at_by_id[comment_id] + continue + if "lastEditedAt" not in node: + stop("GitHub omitted lastEditedAt from issue comment metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] + missing = [ + comment for comment in claim_comments + if str(comment.get("id") or "") not in edited_at_by_id + ] + if missing: + if retry: + refreshed = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + "issue #14 comments", + ) + return attach_comment_edit_metadata(refreshed, retry=False) + stop("Could not verify claim comment metadata after one fresh read.") + for comment in claim_comments: + comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] + return comments def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -735,6 +887,16 @@ jobs: return listed + def unwrap_work_id_code(text): + text = (text or "").strip() + quote = re.escape(BACKTICK) + inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) + if inline_code: + code_text = inline_code.group(1).strip() + if ID_LIST_RE.fullmatch(code_text): + return code_text + inline_code.group(2) + return text + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -763,7 +925,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullet_text = bullet.group(1).replace(BACKTICK, "").strip() + bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) if not first_ids: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) @@ -1052,7 +1214,7 @@ jobs: f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", "issue #14 comments", ) - attach_comment_edit_metadata(comments) + comments = attach_comment_edit_metadata(comments) pulls = get_collection( f"/repos/{OWNER}/{REPOSITORY}/pulls?state=open", "open pull requests", From 1a9863999f43408aac72f0f045c13120532b8c91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:09:54 -0300 Subject: [PATCH 34/53] ci: scope and harden claim comment metadata checks --- .github/workflows/coordination-claim.yml | 134 +++++++++++++++++------ 1 file changed, 99 insertions(+), 35 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index d956bc5b4d..5ff98fde1d 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -26,6 +26,7 @@ jobs: import os import re import sys + import time import urllib.error import urllib.request from datetime import datetime @@ -80,51 +81,104 @@ jobs: def graphql_json(payload): - request = urllib.request.Request( - API + "/graphql", - data=json.dumps(payload).encode("utf-8"), - method="POST", - headers={ - "Accept": "application/vnd.github+json", - "Authorization": f"Bearer {TOKEN}", - "X-GitHub-Api-Version": "2022-11-28", - "Content-Type": "application/json", - }, - ) - try: - with urllib.request.urlopen(request, timeout=20) as response: - return json.load(response) - except urllib.error.HTTPError as error: - fail(f"Cannot verify issue comment edit history (HTTP {error.code}).") - except (urllib.error.URLError, TimeoutError): - fail("Cannot reach GitHub to verify issue comment edit history.") + for attempt in range(2): + request = urllib.request.Request( + API + "/graphql", + data=json.dumps(payload).encode("utf-8"), + method="POST", + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {TOKEN}", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(request, timeout=20) as response: + result = json.load(response) + errors = result.get("errors") or [] + limited = any( + isinstance(error, dict) + and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in (error.get("message") or "").casefold() + ) + for error in errors + ) + retry_after = response.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if limited and attempt == 0 and delay is not None and 0 <= delay <= 20: + time.sleep(delay) + continue + return result + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace")[:300] + retry_after = error.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if error.code in (403, 429) and attempt == 0 and delay is not None and 0 <= delay <= 20: + time.sleep(delay) + continue + fail(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") + except (urllib.error.URLError, TimeoutError) as error: + fail(f"Cannot reach GitHub GraphQL API: {error}") - def attach_comment_edit_metadata(comments): + def attach_comment_edit_metadata(comments, retry=True): + claim_comments = [ + comment for comment in comments + if ids_from_claim_comment(comment.get("body") or "") + ] + if not claim_comments: + return comments query = ( "query($ids: [ID!]!) { nodes(ids: $ids) { " "... on IssueComment { fullDatabaseId lastEditedAt } } }" ) - for offset in range(0, len(comments), 100): - batch = comments[offset : offset + 100] + edited_at_by_id = {} + for offset in range(0, len(claim_comments), 100): + batch = claim_comments[offset : offset + 100] node_ids = [comment.get("node_id") for comment in batch] if any(not node_id for node_id in node_ids): - fail("Cannot verify issue comment edit history.") - result = graphql_json({"query": query, "variables": {"ids": node_ids}}) - if result.get("errors"): - fail("Cannot verify issue comment edit history.") + fail("Cannot verify issue comment edit history: missing GraphQL node ID.") + result = graphql_json( + {"query": query, "variables": {"ids": node_ids}} + ) + errors = result.get("errors") or [] + if errors: + details = "; ".join( + str(error.get("message") or "GraphQL error") + for error in errors[:3] + if isinstance(error, dict) + ) + fail("Cannot verify issue comment edit history: " + details) nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): fail("GitHub returned invalid issue comment edit metadata.") - edited_at_by_id = {} for node in nodes: if not isinstance(node, dict) or node.get("fullDatabaseId") is None: - fail("GitHub returned invalid issue comment edit metadata.") - edited_at_by_id[str(node["fullDatabaseId"])] = node.get("lastEditedAt") - for comment in batch: - comment_id = str(comment.get("id") or "") - if comment_id not in edited_at_by_id: - fail("Could not match issue comment edit metadata.") - comment["_last_edited_at"] = edited_at_by_id[comment_id] + continue + if "lastEditedAt" not in node: + fail("GitHub omitted lastEditedAt from issue comment metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] + missing = [ + comment for comment in claim_comments + if str(comment.get("id") or "") not in edited_at_by_id + ] + if missing: + if retry: + refreshed = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" + ) + return attach_comment_edit_metadata(refreshed, retry=False) + fail("Could not verify claim comment metadata after one fresh read.") + for comment in claim_comments: + comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] + return comments def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -137,6 +191,16 @@ jobs: return listed + def unwrap_work_id_code(text): + text = (text or "").strip() + quote = re.escape(BACKTICK) + inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) + if inline_code: + code_text = inline_code.group(1).strip() + if ID_LIST_RE.fullmatch(code_text): + return code_text + inline_code.group(2) + return text + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -165,7 +229,7 @@ jobs: bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) if not bullet: break - bullet_text = bullet.group(1).replace(BACKTICK, "").strip() + bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) if not first_ids: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) @@ -246,7 +310,7 @@ jobs: comments = get_collection( f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" ) - attach_comment_edit_metadata(comments) + comments = attach_comment_edit_metadata(comments) comments_by_id = {str(comment.get("id")): comment for comment in comments} claims_by_id = {} for comment in comments: From 1759e1f4d55c1ca4bdb0be7e537d08d15d5d375d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:12:23 -0300 Subject: [PATCH 35/53] ci: filter issue comments and parse complete code spans --- .github/workflows/coordination-activity.yml | 51 +++++++++++++++------ 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index a76442100d..24645e2ced 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -822,6 +822,7 @@ jobs: stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") except (urllib.error.URLError, TimeoutError) as error: stop(f"Cannot reach GitHub GraphQL API: {error}") + stop("GitHub GraphQL retry loop ended unexpectedly.") def attach_comment_edit_metadata(comments, retry=True): claim_comments = [ @@ -830,6 +831,16 @@ jobs: ] if not claim_comments: return comments + + def refresh_comments(): + if not retry: + stop("Could not verify claim metadata after one fresh issue-comment read.") + refreshed = get_collection( + f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", + "issue #14 comments", + ) + return attach_comment_edit_metadata(refreshed, retry=False) + query = ( "query($ids: [ID!]!) { nodes(ids: $ids) { " "... on IssueComment { fullDatabaseId lastEditedAt } } }" @@ -845,6 +856,26 @@ jobs: ) errors = result.get("errors") or [] if errors: + node_error = any( + isinstance(error, dict) + and ( + ( + isinstance(error.get("path"), list) + and error["path"] + and error["path"][0] == "nodes" + ) + or ( + "node" in (error.get("message") or "").casefold() + and ( + "resolve" in (error.get("message") or "").casefold() + or "not found" in (error.get("message") or "").casefold() + ) + ) + ) + for error in errors + ) + if node_error: + return refresh_comments() details = "; ".join( str(error.get("message") or "GraphQL error") for error in errors[:3] @@ -865,13 +896,7 @@ jobs: if str(comment.get("id") or "") not in edited_at_by_id ] if missing: - if retry: - refreshed = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", - "issue #14 comments", - ) - return attach_comment_edit_metadata(refreshed, retry=False) - stop("Could not verify claim comment metadata after one fresh read.") + return refresh_comments() for comment in claim_comments: comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] return comments @@ -889,13 +914,13 @@ jobs: def unwrap_work_id_code(text): text = (text or "").strip() - quote = re.escape(BACKTICK) - inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) - if inline_code: - code_text = inline_code.group(1).strip() + pattern = re.escape(BACKTICK) + "([^" + BACKTICK + "]*)" + re.escape(BACKTICK) + def replace_code_span(match): + code_text = match.group(1).strip() if ID_LIST_RE.fullmatch(code_text): - return code_text + inline_code.group(2) - return text + return code_text + return match.group(0) + return re.sub(pattern, replace_code_span, text) def ids_from_claim_comment(body): lines = (body or "").splitlines() From c74003a3f048f966176bccf94e2dd7798a0a7e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:19:19 -0300 Subject: [PATCH 36/53] ci: retry transient claim comment lookups --- .github/workflows/coordination-activity.yml | 266 ++++++++++---------- 1 file changed, 136 insertions(+), 130 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 24645e2ced..36579a105f 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -165,59 +165,74 @@ jobs: except (urllib.error.URLError, TimeoutError) as error: stop(f"Cannot reach GitHub GraphQL API: {error}") - def attach_comment_edit_metadata(comments, retry=True): - claim_comments = [ - comment for comment in comments - if ids_from_claim_comment(comment.get("body") or "") - ] - if not claim_comments: - return comments - query = ( - "query($ids: [ID!]!) { nodes(ids: $ids) { " - "... on IssueComment { fullDatabaseId lastEditedAt } } }" - ) - edited_at_by_id = {} - for offset in range(0, len(claim_comments), 100): - batch = claim_comments[offset : offset + 100] - node_ids = [comment.get("node_id") for comment in batch] - if any(not node_id for node_id in node_ids): - stop("Cannot verify issue comment edit history: missing GraphQL node ID.") - result = graphql_json( - {"query": query, "variables": {"ids": node_ids}} - ) - errors = result.get("errors") or [] - if errors: - details = "; ".join( - str(error.get("message") or "GraphQL error") - for error in errors[:3] - if isinstance(error, dict) - ) - stop("Cannot verify issue comment edit history: " + details) - nodes = ((result.get("data") or {}).get("nodes")) - if not isinstance(nodes, list) or len(nodes) != len(batch): - stop("GitHub returned invalid issue comment edit metadata.") - for node in nodes: - if not isinstance(node, dict) or node.get("fullDatabaseId") is None: - continue - if "lastEditedAt" not in node: - stop("GitHub omitted lastEditedAt from issue comment metadata.") - edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] - missing = [ - comment for comment in claim_comments - if str(comment.get("id") or "") not in edited_at_by_id - ] - if missing: - if retry: - refreshed = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", - "issue #14 comments", - ) - return attach_comment_edit_metadata(refreshed, retry=False) - stop("Could not verify claim comment metadata after one fresh read.") - for comment in claim_comments: - comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] - return comments - + def attach_comment_edit_metadata(comments, retry=True): + claim_comments = [ + comment for comment in comments + if ids_from_claim_comment(comment.get("body") or "") + ] + if not claim_comments: + return comments + + def retry_after_fresh_read(reason): + if retry: + refreshed = get_collection( + "/repos/" + OWNER + "/" + REPOSITORY + "/issues/" + str(ISSUE_NUMBER) + "/comments", + "issue #14 comments", + ) + return attach_comment_edit_metadata(refreshed, retry=False) + stop("Could not verify issue comment edit history after one fresh read: " + reason) + + query = ( + "query($ids: [ID!]!) { nodes(ids: $ids) { " + "... on IssueComment { fullDatabaseId lastEditedAt } } }" + ) + edited_at_by_id = {} + for offset in range(0, len(claim_comments), 100): + batch = claim_comments[offset : offset + 100] + node_ids = [comment.get("node_id") for comment in batch] + if any(not node_id for node_id in node_ids): + stop("Cannot verify issue comment edit history: missing GraphQL node ID.") + result = graphql_json( + {"query": query, "variables": {"ids": node_ids}} + ) + errors = result.get("errors") or [] + node_errors = [ + error for error in errors + if isinstance(error, dict) + and (error.get("path") or [None])[0] == "nodes" + ] + if node_errors: + details = "; ".join( + str(error.get("message") or "GraphQL node lookup error") + for error in node_errors[:3] + ) + return retry_after_fresh_read(details) + if errors: + details = "; ".join( + str(error.get("message") or "GraphQL error") + for error in errors[:3] + if isinstance(error, dict) + ) + stop("Cannot verify issue comment edit history: " + details) + nodes = ((result.get("data") or {}).get("nodes")) + if not isinstance(nodes, list) or len(nodes) != len(batch): + stop("GitHub returned invalid issue comment edit metadata.") + for node in nodes: + if not isinstance(node, dict) or node.get("fullDatabaseId") is None: + continue + if "lastEditedAt" not in node: + stop("GitHub omitted lastEditedAt from issue comment metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] + missing = [ + comment for comment in claim_comments + if str(comment.get("id") or "") not in edited_at_by_id + ] + if missing: + return retry_after_fresh_read("one or more claim comments disappeared from the GraphQL lookup") + for comment in claim_comments: + comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] + return comments + def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} @@ -824,83 +839,74 @@ jobs: stop(f"Cannot reach GitHub GraphQL API: {error}") stop("GitHub GraphQL retry loop ended unexpectedly.") - def attach_comment_edit_metadata(comments, retry=True): - claim_comments = [ - comment for comment in comments - if ids_from_claim_comment(comment.get("body") or "") - ] - if not claim_comments: - return comments - - def refresh_comments(): - if not retry: - stop("Could not verify claim metadata after one fresh issue-comment read.") - refreshed = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments", - "issue #14 comments", - ) - return attach_comment_edit_metadata(refreshed, retry=False) - - query = ( - "query($ids: [ID!]!) { nodes(ids: $ids) { " - "... on IssueComment { fullDatabaseId lastEditedAt } } }" - ) - edited_at_by_id = {} - for offset in range(0, len(claim_comments), 100): - batch = claim_comments[offset : offset + 100] - node_ids = [comment.get("node_id") for comment in batch] - if any(not node_id for node_id in node_ids): - stop("Cannot verify issue comment edit history: missing GraphQL node ID.") - result = graphql_json( - {"query": query, "variables": {"ids": node_ids}} - ) - errors = result.get("errors") or [] - if errors: - node_error = any( - isinstance(error, dict) - and ( - ( - isinstance(error.get("path"), list) - and error["path"] - and error["path"][0] == "nodes" - ) - or ( - "node" in (error.get("message") or "").casefold() - and ( - "resolve" in (error.get("message") or "").casefold() - or "not found" in (error.get("message") or "").casefold() - ) - ) - ) - for error in errors - ) - if node_error: - return refresh_comments() - details = "; ".join( - str(error.get("message") or "GraphQL error") - for error in errors[:3] - if isinstance(error, dict) - ) - stop("Cannot verify issue comment edit history: " + details) - nodes = ((result.get("data") or {}).get("nodes")) - if not isinstance(nodes, list) or len(nodes) != len(batch): - stop("GitHub returned invalid issue comment edit metadata.") - for node in nodes: - if not isinstance(node, dict) or node.get("fullDatabaseId") is None: - continue - if "lastEditedAt" not in node: - stop("GitHub omitted lastEditedAt from issue comment metadata.") - edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] - missing = [ - comment for comment in claim_comments - if str(comment.get("id") or "") not in edited_at_by_id - ] - if missing: - return refresh_comments() - for comment in claim_comments: - comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] - return comments - + def attach_comment_edit_metadata(comments, retry=True): + claim_comments = [ + comment for comment in comments + if ids_from_claim_comment(comment.get("body") or "") + ] + if not claim_comments: + return comments + + def retry_after_fresh_read(reason): + if retry: + refreshed = get_collection( + "/repos/" + OWNER + "/" + REPOSITORY + "/issues/" + str(ISSUE_NUMBER) + "/comments", + "issue #14 comments", + ) + return attach_comment_edit_metadata(refreshed, retry=False) + stop("Could not verify issue comment edit history after one fresh read: " + reason) + + query = ( + "query($ids: [ID!]!) { nodes(ids: $ids) { " + "... on IssueComment { fullDatabaseId lastEditedAt } } }" + ) + edited_at_by_id = {} + for offset in range(0, len(claim_comments), 100): + batch = claim_comments[offset : offset + 100] + node_ids = [comment.get("node_id") for comment in batch] + if any(not node_id for node_id in node_ids): + stop("Cannot verify issue comment edit history: missing GraphQL node ID.") + result = graphql_json( + {"query": query, "variables": {"ids": node_ids}} + ) + errors = result.get("errors") or [] + node_errors = [ + error for error in errors + if isinstance(error, dict) + and (error.get("path") or [None])[0] == "nodes" + ] + if node_errors: + details = "; ".join( + str(error.get("message") or "GraphQL node lookup error") + for error in node_errors[:3] + ) + return retry_after_fresh_read(details) + if errors: + details = "; ".join( + str(error.get("message") or "GraphQL error") + for error in errors[:3] + if isinstance(error, dict) + ) + stop("Cannot verify issue comment edit history: " + details) + nodes = ((result.get("data") or {}).get("nodes")) + if not isinstance(nodes, list) or len(nodes) != len(batch): + stop("GitHub returned invalid issue comment edit metadata.") + for node in nodes: + if not isinstance(node, dict) or node.get("fullDatabaseId") is None: + continue + if "lastEditedAt" not in node: + stop("GitHub omitted lastEditedAt from issue comment metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] + missing = [ + comment for comment in claim_comments + if str(comment.get("id") or "") not in edited_at_by_id + ] + if missing: + return retry_after_fresh_read("one or more claim comments disappeared from the GraphQL lookup") + for comment in claim_comments: + comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] + return comments + def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} From 5eb6845e88c2aa89fe498164a64ef61326df133c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:19:59 -0300 Subject: [PATCH 37/53] ci: retry transient claim comment lookups --- .github/workflows/coordination-claim.yml | 119 +++++++++++++---------- 1 file changed, 67 insertions(+), 52 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 5ff98fde1d..bff12fa5ad 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -128,58 +128,73 @@ jobs: except (urllib.error.URLError, TimeoutError) as error: fail(f"Cannot reach GitHub GraphQL API: {error}") - def attach_comment_edit_metadata(comments, retry=True): - claim_comments = [ - comment for comment in comments - if ids_from_claim_comment(comment.get("body") or "") - ] - if not claim_comments: - return comments - query = ( - "query($ids: [ID!]!) { nodes(ids: $ids) { " - "... on IssueComment { fullDatabaseId lastEditedAt } } }" - ) - edited_at_by_id = {} - for offset in range(0, len(claim_comments), 100): - batch = claim_comments[offset : offset + 100] - node_ids = [comment.get("node_id") for comment in batch] - if any(not node_id for node_id in node_ids): - fail("Cannot verify issue comment edit history: missing GraphQL node ID.") - result = graphql_json( - {"query": query, "variables": {"ids": node_ids}} - ) - errors = result.get("errors") or [] - if errors: - details = "; ".join( - str(error.get("message") or "GraphQL error") - for error in errors[:3] - if isinstance(error, dict) - ) - fail("Cannot verify issue comment edit history: " + details) - nodes = ((result.get("data") or {}).get("nodes")) - if not isinstance(nodes, list) or len(nodes) != len(batch): - fail("GitHub returned invalid issue comment edit metadata.") - for node in nodes: - if not isinstance(node, dict) or node.get("fullDatabaseId") is None: - continue - if "lastEditedAt" not in node: - fail("GitHub omitted lastEditedAt from issue comment metadata.") - edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] - missing = [ - comment for comment in claim_comments - if str(comment.get("id") or "") not in edited_at_by_id - ] - if missing: - if retry: - refreshed = get_collection( - f"/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}/comments" - ) - return attach_comment_edit_metadata(refreshed, retry=False) - fail("Could not verify claim comment metadata after one fresh read.") - for comment in claim_comments: - comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] - return comments - + def attach_comment_edit_metadata(comments, retry=True): + claim_comments = [ + comment for comment in comments + if ids_from_claim_comment(comment.get("body") or "") + ] + if not claim_comments: + return comments + + def retry_after_fresh_read(reason): + if retry: + refreshed = get_collection( + "/repos/" + OWNER + "/" + REPOSITORY + "/issues/" + str(ISSUE_NUMBER) + "/comments" + ) + return attach_comment_edit_metadata(refreshed, retry=False) + fail("Could not verify issue comment edit history after one fresh read: " + reason) + + query = ( + "query($ids: [ID!]!) { nodes(ids: $ids) { " + "... on IssueComment { fullDatabaseId lastEditedAt } } }" + ) + edited_at_by_id = {} + for offset in range(0, len(claim_comments), 100): + batch = claim_comments[offset : offset + 100] + node_ids = [comment.get("node_id") for comment in batch] + if any(not node_id for node_id in node_ids): + fail("Cannot verify issue comment edit history: missing GraphQL node ID.") + result = graphql_json( + {"query": query, "variables": {"ids": node_ids}} + ) + errors = result.get("errors") or [] + node_errors = [ + error for error in errors + if isinstance(error, dict) + and (error.get("path") or [None])[0] == "nodes" + ] + if node_errors: + details = "; ".join( + str(error.get("message") or "GraphQL node lookup error") + for error in node_errors[:3] + ) + return retry_after_fresh_read(details) + if errors: + details = "; ".join( + str(error.get("message") or "GraphQL error") + for error in errors[:3] + if isinstance(error, dict) + ) + fail("Cannot verify issue comment edit history: " + details) + nodes = ((result.get("data") or {}).get("nodes")) + if not isinstance(nodes, list) or len(nodes) != len(batch): + fail("GitHub returned invalid issue comment edit metadata.") + for node in nodes: + if not isinstance(node, dict) or node.get("fullDatabaseId") is None: + continue + if "lastEditedAt" not in node: + fail("GitHub omitted lastEditedAt from issue comment metadata.") + edited_at_by_id[str(node["fullDatabaseId"])] = node["lastEditedAt"] + missing = [ + comment for comment in claim_comments + if str(comment.get("id") or "") not in edited_at_by_id + ] + if missing: + return retry_after_fresh_read("one or more claim comments disappeared from the GraphQL lookup") + for comment in claim_comments: + comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] + return comments + def ids_from_text(text): return {value.upper() for value in WORK_ID_RE.findall(text or "")} From 3339dededf5b737154e0492d3e257bc671bb759e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:22:08 -0300 Subject: [PATCH 38/53] ci: prevent joining inline work id suffixes --- .github/workflows/coordination-activity.yml | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 36579a105f..20541d3e5f 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -250,8 +250,12 @@ jobs: inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) if inline_code: code_text = inline_code.group(1).strip() - if ID_LIST_RE.fullmatch(code_text): - return code_text + inline_code.group(2) + suffix = inline_code.group(2) + if ( + ID_LIST_RE.fullmatch(code_text) + and not re.match(r"^[A-Za-z0-9-]", suffix) + ): + return code_text + suffix return text def ids_from_claim_comment(body): @@ -923,7 +927,13 @@ jobs: pattern = re.escape(BACKTICK) + "([^" + BACKTICK + "]*)" + re.escape(BACKTICK) def replace_code_span(match): code_text = match.group(1).strip() - if ID_LIST_RE.fullmatch(code_text): + before = match.string[match.start() - 1:match.start()] + after = match.string[match.end():match.end() + 1] + if ( + ID_LIST_RE.fullmatch(code_text) + and not re.match(r"^[A-Za-z0-9-]", before) + and not re.match(r"^[A-Za-z0-9-]", after) + ): return code_text return match.group(0) return re.sub(pattern, replace_code_span, text) From 686ebbb8dba9924cee67cb6fbfb271d40f76a1bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:22:27 -0300 Subject: [PATCH 39/53] ci: prevent joining inline work id suffixes --- .github/workflows/coordination-claim.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index bff12fa5ad..da083a6719 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -212,8 +212,12 @@ jobs: inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) if inline_code: code_text = inline_code.group(1).strip() - if ID_LIST_RE.fullmatch(code_text): - return code_text + inline_code.group(2) + suffix = inline_code.group(2) + if ( + ID_LIST_RE.fullmatch(code_text) + and not re.match(r"^[A-Za-z0-9-]", suffix) + ): + return code_text + suffix return text def ids_from_claim_comment(body): From 2a4c51145e65c5535659badf2eb8cf2eb25b015a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:28:42 -0300 Subject: [PATCH 40/53] ci: reject mixed graphql errors and malformed claim batches --- .github/workflows/coordination-activity.yml | 108 +++++++++++++------- 1 file changed, 72 insertions(+), 36 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 20541d3e5f..601130deba 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -196,25 +196,33 @@ jobs: {"query": query, "variables": {"ids": node_ids}} ) errors = result.get("errors") or [] - node_errors = [ - error for error in errors - if isinstance(error, dict) - and (error.get("path") or [None])[0] == "nodes" - ] - if node_errors: - details = "; ".join( - str(error.get("message") or "GraphQL node lookup error") - for error in node_errors[:3] + node_errors = [] + other_errors = [] + for error in errors: + path = error.get("path") if isinstance(error, dict) else None + message = error.get("message") or "" if isinstance(error, dict) else str(error) + is_node_error = bool(path and path[0] == "nodes") + is_rate_limited = isinstance(error, dict) and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in message.casefold() ) - return retry_after_fresh_read(details) - if errors: + if is_node_error and not is_rate_limited: + node_errors.append(error) + else: + other_errors.append(error) + if other_errors: details = "; ".join( str(error.get("message") or "GraphQL error") - for error in errors[:3] - if isinstance(error, dict) + if isinstance(error, dict) else str(error) + for error in errors ) stop("Cannot verify issue comment edit history: " + details) - nodes = ((result.get("data") or {}).get("nodes")) + if node_errors: + details = "; ".join( + str(error.get("message") or "GraphQL node lookup error") + for error in node_errors + ) + return retry_after_fresh_read(details) nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): stop("GitHub returned invalid issue comment edit metadata.") for node in nodes: @@ -288,10 +296,20 @@ jobs: break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) - if not first_ids: - leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) - if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): - batch_valid = False + if not first_ids: + malformed_inline_id = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + + re.escape(BACKTICK) + r"[A-Za-z0-9-]", + bullet_text, + ) + if ( + malformed_inline_id + and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) + ): + batch_valid = False + leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) + if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): + batch_valid = False break batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 @@ -874,25 +892,33 @@ jobs: {"query": query, "variables": {"ids": node_ids}} ) errors = result.get("errors") or [] - node_errors = [ - error for error in errors - if isinstance(error, dict) - and (error.get("path") or [None])[0] == "nodes" - ] - if node_errors: - details = "; ".join( - str(error.get("message") or "GraphQL node lookup error") - for error in node_errors[:3] + node_errors = [] + other_errors = [] + for error in errors: + path = error.get("path") if isinstance(error, dict) else None + message = error.get("message") or "" if isinstance(error, dict) else str(error) + is_node_error = bool(path and path[0] == "nodes") + is_rate_limited = isinstance(error, dict) and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in message.casefold() ) - return retry_after_fresh_read(details) - if errors: + if is_node_error and not is_rate_limited: + node_errors.append(error) + else: + other_errors.append(error) + if other_errors: details = "; ".join( str(error.get("message") or "GraphQL error") - for error in errors[:3] - if isinstance(error, dict) + if isinstance(error, dict) else str(error) + for error in errors ) stop("Cannot verify issue comment edit history: " + details) - nodes = ((result.get("data") or {}).get("nodes")) + if node_errors: + details = "; ".join( + str(error.get("message") or "GraphQL node lookup error") + for error in node_errors + ) + return retry_after_fresh_read(details) nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): stop("GitHub returned invalid issue comment edit metadata.") for node in nodes: @@ -968,10 +994,20 @@ jobs: break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) - if not first_ids: - leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) - if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): - batch_valid = False + if not first_ids: + malformed_inline_id = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + + re.escape(BACKTICK) + r"[A-Za-z0-9-]", + bullet_text, + ) + if ( + malformed_inline_id + and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) + ): + batch_valid = False + leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) + if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): + batch_valid = False break batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 From 349b1b0e8570a01576455801f893ba2db74dd72a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:29:08 -0300 Subject: [PATCH 41/53] ci: reject mixed graphql errors and malformed claim batches --- .github/workflows/coordination-claim.yml | 54 ++++++++++++++++-------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index da083a6719..e2b41f4a1a 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -158,25 +158,33 @@ jobs: {"query": query, "variables": {"ids": node_ids}} ) errors = result.get("errors") or [] - node_errors = [ - error for error in errors - if isinstance(error, dict) - and (error.get("path") or [None])[0] == "nodes" - ] - if node_errors: - details = "; ".join( - str(error.get("message") or "GraphQL node lookup error") - for error in node_errors[:3] + node_errors = [] + other_errors = [] + for error in errors: + path = error.get("path") if isinstance(error, dict) else None + message = error.get("message") or "" if isinstance(error, dict) else str(error) + is_node_error = bool(path and path[0] == "nodes") + is_rate_limited = isinstance(error, dict) and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in message.casefold() ) - return retry_after_fresh_read(details) - if errors: + if is_node_error and not is_rate_limited: + node_errors.append(error) + else: + other_errors.append(error) + if other_errors: details = "; ".join( str(error.get("message") or "GraphQL error") - for error in errors[:3] - if isinstance(error, dict) + if isinstance(error, dict) else str(error) + for error in errors ) fail("Cannot verify issue comment edit history: " + details) - nodes = ((result.get("data") or {}).get("nodes")) + if node_errors: + details = "; ".join( + str(error.get("message") or "GraphQL node lookup error") + for error in node_errors + ) + return retry_after_fresh_read(details) nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): fail("GitHub returned invalid issue comment edit metadata.") for node in nodes: @@ -250,10 +258,20 @@ jobs: break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) - if not first_ids: - leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) - if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): - batch_valid = False + if not first_ids: + malformed_inline_id = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + + re.escape(BACKTICK) + r"[A-Za-z0-9-]", + bullet_text, + ) + if ( + malformed_inline_id + and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) + ): + batch_valid = False + leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) + if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): + batch_valid = False break batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 From 5e1cf67ca4906da1fc882c8faf49f8dab8b99826 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:34:15 -0300 Subject: [PATCH 42/53] ci: preserve mixed errors and align claim parsing --- .github/workflows/coordination-activity.yml | 84 +++++++++++---------- 1 file changed, 44 insertions(+), 40 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 601130deba..cd2e4571d1 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -134,14 +134,14 @@ jobs: with urllib.request.urlopen(request, timeout=25) as response: result = json.load(response) errors = result.get("errors") or [] - limited = any( - isinstance(error, dict) - and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in (error.get("message") or "").casefold() - ) - for error in errors - ) + limited = bool(errors) and all( + isinstance(error, dict) + and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in (error.get("message") or "").casefold() + ) + for error in errors + ) retry_after = response.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -152,7 +152,7 @@ jobs: continue return result except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", "replace")[:300] + detail = error.read().decode("utf-8", "replace") retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -222,7 +222,8 @@ jobs: str(error.get("message") or "GraphQL node lookup error") for error in node_errors ) - return retry_after_fresh_read(details) nodes = ((result.get("data") or {}).get("nodes")) + return retry_after_fresh_read(details) + nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): stop("GitHub returned invalid issue comment edit metadata.") for node in nodes: @@ -252,20 +253,22 @@ jobs: return listed - def unwrap_work_id_code(text): - text = (text or "").strip() - quote = re.escape(BACKTICK) - inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) - if inline_code: - code_text = inline_code.group(1).strip() - suffix = inline_code.group(2) + def unwrap_work_id_code(text): + text = (text or "").strip() + pattern = re.escape(BACKTICK) + "([^" + BACKTICK + "]*)" + re.escape(BACKTICK) + def replace_code_span(match): + code_text = match.group(1).strip() + before = match.string[match.start() - 1:match.start()] + after = match.string[match.end():match.end() + 1] if ( ID_LIST_RE.fullmatch(code_text) - and not re.match(r"^[A-Za-z0-9-]", suffix) + and not re.match(r"^[A-Za-z0-9-]", before) + and not re.match(r"^[A-Za-z0-9-]", after) ): - return code_text + suffix - return text - + return code_text + return match.group(0) + return re.sub(pattern, replace_code_span, text) + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() @@ -829,14 +832,14 @@ jobs: with urllib.request.urlopen(request, timeout=25) as response: result = json.load(response) errors = result.get("errors") or [] - limited = any( - isinstance(error, dict) - and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in (error.get("message") or "").casefold() - ) - for error in errors - ) + limited = bool(errors) and all( + isinstance(error, dict) + and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in (error.get("message") or "").casefold() + ) + for error in errors + ) retry_after = response.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -847,7 +850,7 @@ jobs: continue return result except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", "replace")[:300] + detail = error.read().decode("utf-8", "replace") retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -918,7 +921,8 @@ jobs: str(error.get("message") or "GraphQL node lookup error") for error in node_errors ) - return retry_after_fresh_read(details) nodes = ((result.get("data") or {}).get("nodes")) + return retry_after_fresh_read(details) + nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): stop("GitHub returned invalid issue comment edit metadata.") for node in nodes: @@ -948,11 +952,11 @@ jobs: return listed - def unwrap_work_id_code(text): - text = (text or "").strip() - pattern = re.escape(BACKTICK) + "([^" + BACKTICK + "]*)" + re.escape(BACKTICK) - def replace_code_span(match): - code_text = match.group(1).strip() + def unwrap_work_id_code(text): + text = (text or "").strip() + pattern = re.escape(BACKTICK) + "([^" + BACKTICK + "]*)" + re.escape(BACKTICK) + def replace_code_span(match): + code_text = match.group(1).strip() before = match.string[match.start() - 1:match.start()] after = match.string[match.end():match.end() + 1] if ( @@ -960,10 +964,10 @@ jobs: and not re.match(r"^[A-Za-z0-9-]", before) and not re.match(r"^[A-Za-z0-9-]", after) ): - return code_text - return match.group(0) - return re.sub(pattern, replace_code_span, text) - + return code_text + return match.group(0) + return re.sub(pattern, replace_code_span, text) + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() From 43474e7b52a0685db302a2f0afa880eb809c3c3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:34:46 -0300 Subject: [PATCH 43/53] ci: preserve mixed errors and align claim parsing --- .github/workflows/coordination-claim.yml | 45 +++++++++++++----------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index e2b41f4a1a..b5ebc991d0 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -97,14 +97,14 @@ jobs: with urllib.request.urlopen(request, timeout=20) as response: result = json.load(response) errors = result.get("errors") or [] - limited = any( - isinstance(error, dict) - and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in (error.get("message") or "").casefold() - ) - for error in errors - ) + limited = bool(errors) and all( + isinstance(error, dict) + and ( + error.get("type") == "RATE_LIMITED" + or "rate limit" in (error.get("message") or "").casefold() + ) + for error in errors + ) retry_after = response.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -115,7 +115,7 @@ jobs: continue return result except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", "replace")[:300] + detail = error.read().decode("utf-8", "replace") retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -184,7 +184,8 @@ jobs: str(error.get("message") or "GraphQL node lookup error") for error in node_errors ) - return retry_after_fresh_read(details) nodes = ((result.get("data") or {}).get("nodes")) + return retry_after_fresh_read(details) + nodes = ((result.get("data") or {}).get("nodes")) if not isinstance(nodes, list) or len(nodes) != len(batch): fail("GitHub returned invalid issue comment edit metadata.") for node in nodes: @@ -214,20 +215,22 @@ jobs: return listed - def unwrap_work_id_code(text): - text = (text or "").strip() - quote = re.escape(BACKTICK) - inline_code = re.match("^" + quote + "([^" + BACKTICK + "]*)" + quote + "(.*)$", text) - if inline_code: - code_text = inline_code.group(1).strip() - suffix = inline_code.group(2) + def unwrap_work_id_code(text): + text = (text or "").strip() + pattern = re.escape(BACKTICK) + "([^" + BACKTICK + "]*)" + re.escape(BACKTICK) + def replace_code_span(match): + code_text = match.group(1).strip() + before = match.string[match.start() - 1:match.start()] + after = match.string[match.end():match.end() + 1] if ( ID_LIST_RE.fullmatch(code_text) - and not re.match(r"^[A-Za-z0-9-]", suffix) + and not re.match(r"^[A-Za-z0-9-]", before) + and not re.match(r"^[A-Za-z0-9-]", after) ): - return code_text + suffix - return text - + return code_text + return match.group(0) + return re.sub(pattern, replace_code_span, text) + def ids_from_claim_comment(body): lines = (body or "").splitlines() found = set() From f7b5a18e55ac87c665e7ad89aeb50380fc71f599 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:49:06 -0300 Subject: [PATCH 44/53] ci: bound claim parsing and target deletions --- .github/workflows/coordination-activity.yml | 110 +++++++++++++++----- 1 file changed, 84 insertions(+), 26 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index cd2e4571d1..900ed1e5d2 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -69,10 +69,11 @@ jobs: ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + CLAIM_FIELD_RE = re.compile( + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,65536})[ \t]{0,128}$" ) - BACKTICK = chr(96) + BACKTICK = chr(96) + MAX_CLAIM_BODY_CHARS = 65536 def stop(message): @@ -98,8 +99,9 @@ jobs: with urllib.request.urlopen(request, timeout=25) as response: raw = response.read() return json.loads(raw) if raw else {} - except urllib.error.HTTPError as error: - stop(f"GitHub API request failed (HTTP {error.code}); this coordination update may be incomplete.") + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace") + stop(f"GitHub API request failed (HTTP {error.code}): {detail}; this coordination update may be incomplete.") except (urllib.error.URLError, TimeoutError): stop("Cannot reach GitHub; this coordination update may be incomplete.") @@ -269,14 +271,17 @@ jobs: return match.group(0) return re.sub(pattern, replace_code_span, text) - def ids_from_claim_comment(body): - lines = (body or "").splitlines() + def ids_from_claim_comment(body): + body = body or "" + if len(body) > MAX_CLAIM_BODY_CHARS: + return set() + lines = body.splitlines() found = set() for index, line in enumerate(lines): - match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,65536})$", line, re.IGNORECASE) if not match: continue - tail = match.group(1).strip() + tail = unwrap_work_id_code(match.group(1).strip()) listed = work_id_list(tail) if listed: found.update(ids_from_text(listed.group(1))) @@ -294,8 +299,27 @@ jobs: batch_ids = set() batch_valid = True while cursor < len(lines): - bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) - if not bullet: + bullet = re.match(r"^[ \t]{0,128}[-*][ \t]{1,128}(.{1,512})[ \t]{0,128}$", lines[cursor]) + if not bullet: + stripped_bullet = lines[cursor].lstrip(" \t") + if stripped_bullet.startswith(("-", "*")): + candidate_text = stripped_bullet[1:].lstrip(" \t") + candidate_inline = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), + candidate_text, + ) + candidate_ids = ( + ID_LIST_RE.match(candidate_inline.group(1).strip()) + if candidate_inline else ID_LIST_RE.match(candidate_text) + ) + if ( + len(candidate_text) > 512 + and ( + candidate_ids + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_text) + ) + ): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -313,6 +337,12 @@ jobs: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): batch_valid = False + malformed_id_suffix = re.match( + r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", + bullet_text, + ) + if malformed_id_suffix: + batch_valid = False break batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 @@ -486,8 +516,7 @@ jobs: ): return [] changed_ids, comment_id = changed_claim_ids(event) - if event.get("action") == "deleted" and not changed_ids: - return pulls + return [ pull for pull in pulls if comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id) @@ -767,10 +796,11 @@ jobs: ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + CLAIM_FIELD_RE = re.compile( + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,65536})[ \t]{0,128}$" ) - BACKTICK = chr(96) + BACKTICK = chr(96) + MAX_CLAIM_BODY_CHARS = 65536 def stop(message): @@ -796,8 +826,9 @@ jobs: with urllib.request.urlopen(request, timeout=25) as response: raw = response.read() return json.loads(raw) if raw else {} - except urllib.error.HTTPError as error: - stop(f"GitHub API request failed (HTTP {error.code}); this coordination update may be incomplete.") + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace") + stop(f"GitHub API request failed (HTTP {error.code}): {detail}; this coordination update may be incomplete.") except (urllib.error.URLError, TimeoutError): stop("Cannot reach GitHub; this coordination update may be incomplete.") @@ -968,14 +999,17 @@ jobs: return match.group(0) return re.sub(pattern, replace_code_span, text) - def ids_from_claim_comment(body): - lines = (body or "").splitlines() + def ids_from_claim_comment(body): + body = body or "" + if len(body) > MAX_CLAIM_BODY_CHARS: + return set() + lines = body.splitlines() found = set() for index, line in enumerate(lines): - match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,65536})$", line, re.IGNORECASE) if not match: continue - tail = match.group(1).strip() + tail = unwrap_work_id_code(match.group(1).strip()) listed = work_id_list(tail) if listed: found.update(ids_from_text(listed.group(1))) @@ -993,8 +1027,27 @@ jobs: batch_ids = set() batch_valid = True while cursor < len(lines): - bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) - if not bullet: + bullet = re.match(r"^[ \t]{0,128}[-*][ \t]{1,128}(.{1,512})[ \t]{0,128}$", lines[cursor]) + if not bullet: + stripped_bullet = lines[cursor].lstrip(" \t") + if stripped_bullet.startswith(("-", "*")): + candidate_text = stripped_bullet[1:].lstrip(" \t") + candidate_inline = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), + candidate_text, + ) + candidate_ids = ( + ID_LIST_RE.match(candidate_inline.group(1).strip()) + if candidate_inline else ID_LIST_RE.match(candidate_text) + ) + if ( + len(candidate_text) > 512 + and ( + candidate_ids + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_text) + ) + ): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -1012,6 +1065,12 @@ jobs: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): batch_valid = False + malformed_id_suffix = re.match( + r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", + bullet_text, + ) + if malformed_id_suffix: + batch_valid = False break batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 @@ -1185,8 +1244,7 @@ jobs: ): return [] changed_ids, comment_id = changed_claim_ids(event) - if event.get("action") == "deleted" and not changed_ids: - return pulls + return [ pull for pull in pulls if comment_change_targets_pull(pull, changed_ids, comment_id, comments_by_id) From aea021b810b09ac8bed5ad3d79b11366d3326408 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:49:47 -0300 Subject: [PATCH 45/53] ci: bound claim parsing and report REST errors --- .github/workflows/coordination-claim.yml | 52 +++++++++++++++++++----- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index b5ebc991d0..95762bcba3 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -38,10 +38,11 @@ jobs: ID_PATTERN = r"(??\s*Claimed in the coordination issue as:\s*(.*?)\s*$" + CLAIM_FIELD_RE = re.compile( + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,65536})[ \t]{0,128}$" ) - BACKTICK = chr(96) + BACKTICK = chr(96) + MAX_CLAIM_BODY_CHARS = 65536 def fail(message): @@ -62,8 +63,9 @@ jobs: try: with urllib.request.urlopen(request, timeout=20) as response: return json.load(response) - except urllib.error.HTTPError as error: - fail(f"Cannot verify the claim against issue #14 (HTTP {error.code}).") + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace") + fail(f"Cannot verify the claim against issue #14 (HTTP {error.code}): {detail}") except (urllib.error.URLError, TimeoutError): fail("Cannot reach GitHub to verify the claim against issue #14.") @@ -231,14 +233,17 @@ jobs: return match.group(0) return re.sub(pattern, replace_code_span, text) - def ids_from_claim_comment(body): - lines = (body or "").splitlines() + def ids_from_claim_comment(body): + body = body or "" + if len(body) > MAX_CLAIM_BODY_CHARS: + return set() + lines = body.splitlines() found = set() for index, line in enumerate(lines): - match = re.match(r"^\s*claiming:\s*(.*)$", line, re.IGNORECASE) + match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,65536})$", line, re.IGNORECASE) if not match: continue - tail = match.group(1).strip() + tail = unwrap_work_id_code(match.group(1).strip()) listed = work_id_list(tail) if listed: found.update(ids_from_text(listed.group(1))) @@ -256,8 +261,27 @@ jobs: batch_ids = set() batch_valid = True while cursor < len(lines): - bullet = re.match(r"^\s*[-*]\s+(.+?)\s*$", lines[cursor]) - if not bullet: + bullet = re.match(r"^[ \t]{0,128}[-*][ \t]{1,128}(.{1,512})[ \t]{0,128}$", lines[cursor]) + if not bullet: + stripped_bullet = lines[cursor].lstrip(" \t") + if stripped_bullet.startswith(("-", "*")): + candidate_text = stripped_bullet[1:].lstrip(" \t") + candidate_inline = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), + candidate_text, + ) + candidate_ids = ( + ID_LIST_RE.match(candidate_inline.group(1).strip()) + if candidate_inline else ID_LIST_RE.match(candidate_text) + ) + if ( + len(candidate_text) > 512 + and ( + candidate_ids + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_text) + ) + ): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -275,6 +299,12 @@ jobs: leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): batch_valid = False + malformed_id_suffix = re.match( + r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", + bullet_text, + ) + if malformed_id_suffix: + batch_valid = False break batch_ids.update(ids_from_text(first_ids.group(1))) cursor += 1 From f2bbb2508425aa9f76c04d2f422aa51a39c815ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:51:24 -0300 Subject: [PATCH 46/53] ci: classify rate limits before retry --- .github/workflows/coordination-activity.yml | 126 +++++++++++++------- 1 file changed, 80 insertions(+), 46 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 900ed1e5d2..1db65a5d58 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -119,6 +119,14 @@ jobs: stop(f"The {label} collection is too large to sync safely.") + def is_rate_limit_error(error): + if not isinstance(error, dict): + return False + error_type = error.get("type") + if error_type is not None: + return error_type == "RATE_LIMITED" + return "rate limit" in (error.get("message") or "").casefold() + def graphql_json(payload): for attempt in range(2): request = urllib.request.Request( @@ -136,14 +144,7 @@ jobs: with urllib.request.urlopen(request, timeout=25) as response: result = json.load(response) errors = result.get("errors") or [] - limited = bool(errors) and all( - isinstance(error, dict) - and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in (error.get("message") or "").casefold() - ) - for error in errors - ) + limited = bool(errors) and all(is_rate_limit_error(error) for error in errors) retry_after = response.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -153,17 +154,36 @@ jobs: time.sleep(delay) continue return result - except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", "replace") - retry_after = error.headers.get("Retry-After") - try: - delay = float(retry_after) if retry_after is not None else None - except (TypeError, ValueError): - delay = None - if error.code in (403, 429) and attempt == 0 and delay is not None and 0 <= delay <= 20: - time.sleep(delay) - continue - stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace") + try: + error_payload = json.loads(detail) + except (TypeError, ValueError): + error_payload = {} + body_errors = error_payload.get("errors") if isinstance(error_payload, dict) else None + if body_errors: + rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) + else: + body_message = error_payload.get("message", "") if isinstance(error_payload, dict) else "" + rate_limited_http = error.code == 429 or ( + error.code == 403 + and "rate limit" in str(body_message or detail).casefold() + ) + retry_after = error.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if ( + error.code in (403, 429) + and rate_limited_http + and attempt == 0 + and delay is not None + and 0 <= delay <= 20 + ): + time.sleep(delay) + continue + stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") except (urllib.error.URLError, TimeoutError) as error: stop(f"Cannot reach GitHub GraphQL API: {error}") @@ -204,10 +224,7 @@ jobs: path = error.get("path") if isinstance(error, dict) else None message = error.get("message") or "" if isinstance(error, dict) else str(error) is_node_error = bool(path and path[0] == "nodes") - is_rate_limited = isinstance(error, dict) and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in message.casefold() - ) + is_rate_limited = is_rate_limit_error(error) if is_node_error and not is_rate_limited: node_errors.append(error) else: @@ -846,6 +863,14 @@ jobs: stop(f"The {label} collection is too large to sync safely.") + def is_rate_limit_error(error): + if not isinstance(error, dict): + return False + error_type = error.get("type") + if error_type is not None: + return error_type == "RATE_LIMITED" + return "rate limit" in (error.get("message") or "").casefold() + def graphql_json(payload): for attempt in range(2): request = urllib.request.Request( @@ -863,14 +888,7 @@ jobs: with urllib.request.urlopen(request, timeout=25) as response: result = json.load(response) errors = result.get("errors") or [] - limited = bool(errors) and all( - isinstance(error, dict) - and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in (error.get("message") or "").casefold() - ) - for error in errors - ) + limited = bool(errors) and all(is_rate_limit_error(error) for error in errors) retry_after = response.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -880,17 +898,36 @@ jobs: time.sleep(delay) continue return result - except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", "replace") - retry_after = error.headers.get("Retry-After") - try: - delay = float(retry_after) if retry_after is not None else None - except (TypeError, ValueError): - delay = None - if error.code in (403, 429) and attempt == 0 and delay is not None and 0 <= delay <= 20: - time.sleep(delay) - continue - stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace") + try: + error_payload = json.loads(detail) + except (TypeError, ValueError): + error_payload = {} + body_errors = error_payload.get("errors") if isinstance(error_payload, dict) else None + if body_errors: + rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) + else: + body_message = error_payload.get("message", "") if isinstance(error_payload, dict) else "" + rate_limited_http = error.code == 429 or ( + error.code == 403 + and "rate limit" in str(body_message or detail).casefold() + ) + retry_after = error.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if ( + error.code in (403, 429) + and rate_limited_http + and attempt == 0 + and delay is not None + and 0 <= delay <= 20 + ): + time.sleep(delay) + continue + stop(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") except (urllib.error.URLError, TimeoutError) as error: stop(f"Cannot reach GitHub GraphQL API: {error}") stop("GitHub GraphQL retry loop ended unexpectedly.") @@ -932,10 +969,7 @@ jobs: path = error.get("path") if isinstance(error, dict) else None message = error.get("message") or "" if isinstance(error, dict) else str(error) is_node_error = bool(path and path[0] == "nodes") - is_rate_limited = isinstance(error, dict) and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in message.casefold() - ) + is_rate_limited = is_rate_limit_error(error) if is_node_error and not is_rate_limited: node_errors.append(error) else: From c9707cdd9ff1a3455f42c9e6147fd12926144baa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:51:52 -0300 Subject: [PATCH 47/53] ci: classify rate limits before retry --- .github/workflows/coordination-claim.yml | 63 +++++++++++++++--------- 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index 95762bcba3..cc624a94d0 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -82,6 +82,14 @@ jobs: fail("Issue #14 has too many comments to verify safely.") + def is_rate_limit_error(error): + if not isinstance(error, dict): + return False + error_type = error.get("type") + if error_type is not None: + return error_type == "RATE_LIMITED" + return "rate limit" in (error.get("message") or "").casefold() + def graphql_json(payload): for attempt in range(2): request = urllib.request.Request( @@ -99,14 +107,7 @@ jobs: with urllib.request.urlopen(request, timeout=20) as response: result = json.load(response) errors = result.get("errors") or [] - limited = bool(errors) and all( - isinstance(error, dict) - and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in (error.get("message") or "").casefold() - ) - for error in errors - ) + limited = bool(errors) and all(is_rate_limit_error(error) for error in errors) retry_after = response.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None @@ -116,17 +117,36 @@ jobs: time.sleep(delay) continue return result - except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", "replace") - retry_after = error.headers.get("Retry-After") - try: - delay = float(retry_after) if retry_after is not None else None - except (TypeError, ValueError): - delay = None - if error.code in (403, 429) and attempt == 0 and delay is not None and 0 <= delay <= 20: - time.sleep(delay) - continue - fail(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") + except urllib.error.HTTPError as error: + detail = error.read().decode("utf-8", "replace") + try: + error_payload = json.loads(detail) + except (TypeError, ValueError): + error_payload = {} + body_errors = error_payload.get("errors") if isinstance(error_payload, dict) else None + if body_errors: + rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) + else: + body_message = error_payload.get("message", "") if isinstance(error_payload, dict) else "" + rate_limited_http = error.code == 429 or ( + error.code == 403 + and "rate limit" in str(body_message or detail).casefold() + ) + retry_after = error.headers.get("Retry-After") + try: + delay = float(retry_after) if retry_after is not None else None + except (TypeError, ValueError): + delay = None + if ( + error.code in (403, 429) + and rate_limited_http + and attempt == 0 + and delay is not None + and 0 <= delay <= 20 + ): + time.sleep(delay) + continue + fail(f"GitHub GraphQL request failed (HTTP {error.code}): {detail}") except (urllib.error.URLError, TimeoutError) as error: fail(f"Cannot reach GitHub GraphQL API: {error}") @@ -166,10 +186,7 @@ jobs: path = error.get("path") if isinstance(error, dict) else None message = error.get("message") or "" if isinstance(error, dict) else str(error) is_node_error = bool(path and path[0] == "nodes") - is_rate_limited = isinstance(error, dict) and ( - error.get("type") == "RATE_LIMITED" - or "rate limit" in message.casefold() - ) + is_rate_limited = is_rate_limit_error(error) if is_node_error and not is_rate_limited: node_errors.append(error) else: From 6a0f1669d79ab2a97ab00071f7a8330863481916 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:56:23 -0300 Subject: [PATCH 48/53] ci: cap claim fields and parser input --- .github/workflows/coordination-activity.yml | 106 +++++++++++--------- 1 file changed, 58 insertions(+), 48 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 1db65a5d58..050a2d590d 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -70,10 +70,13 @@ jobs: WORK_ID_RE = re.compile(ID_PATTERN) ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)(?![A-Za-z0-9-])") CLAIM_FIELD_RE = re.compile( - r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,65536})[ \t]{0,128}$" - ) - BACKTICK = chr(96) - MAX_CLAIM_BODY_CHARS = 65536 + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,4096})[ \t]{0,128}$" + ) + CLAIM_FIELD_HEADER_RE = re.compile( + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" + ) BACKTICK = chr(96) + MAX_CLAIM_BODY_CHARS = 65536 + MAX_CLAIM_VALUE_CHARS = 4096 def stop(message): @@ -295,7 +298,9 @@ jobs: lines = body.splitlines() found = set() for index, line in enumerate(lines): - match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,65536})$", line, re.IGNORECASE) + if len(line) > MAX_CLAIM_VALUE_CHARS + 265 and line.lstrip(" \t").casefold().startswith("claiming:"): + return set() + match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,4096})$", line, re.IGNORECASE) if not match: continue tail = unwrap_work_id_code(match.group(1).strip()) @@ -321,22 +326,15 @@ jobs: stripped_bullet = lines[cursor].lstrip(" \t") if stripped_bullet.startswith(("-", "*")): candidate_text = stripped_bullet[1:].lstrip(" \t") - candidate_inline = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), - candidate_text, - ) - candidate_ids = ( - ID_LIST_RE.match(candidate_inline.group(1).strip()) - if candidate_inline else ID_LIST_RE.match(candidate_text) - ) - if ( - len(candidate_text) > 512 - and ( - candidate_ids - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_text) - ) - ): - batch_valid = False + if len(candidate_text) > 512: + candidate_prefix = candidate_text[:512] + if candidate_prefix.startswith(BACKTICK): + candidate_prefix = candidate_prefix[1:] + if ( + ID_LIST_RE.match(candidate_prefix) + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) + ): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -399,9 +397,16 @@ jobs: def pull_claim_ids(pull, comments_by_id): found = ids_from_text(pull.get("title") or "") - unresolved_links = [] - body = re.sub(r"", "", pull.get("body") or "") - for field in CLAIM_FIELD_RE.finditer(body): + unresolved_links = [] + raw_body = pull.get("body") or "" + if len(raw_body) > MAX_CLAIM_BODY_CHARS: + return found, ["PR body exceeds the claim parser size limit"] + body = re.sub(r"", "", raw_body) + field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) + fields = list(CLAIM_FIELD_RE.finditer(body)) + if len(field_headers) != len(fields): + unresolved_links.append("Claimed in the coordination issue field exceeds the parser limit") + for field in fields: value = field.group(1) found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): @@ -814,10 +819,13 @@ jobs: WORK_ID_RE = re.compile(ID_PATTERN) ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)(?![A-Za-z0-9-])") CLAIM_FIELD_RE = re.compile( - r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,65536})[ \t]{0,128}$" - ) - BACKTICK = chr(96) - MAX_CLAIM_BODY_CHARS = 65536 + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,4096})[ \t]{0,128}$" + ) + CLAIM_FIELD_HEADER_RE = re.compile( + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" + ) BACKTICK = chr(96) + MAX_CLAIM_BODY_CHARS = 65536 + MAX_CLAIM_VALUE_CHARS = 4096 def stop(message): @@ -1040,7 +1048,9 @@ jobs: lines = body.splitlines() found = set() for index, line in enumerate(lines): - match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,65536})$", line, re.IGNORECASE) + if len(line) > MAX_CLAIM_VALUE_CHARS + 265 and line.lstrip(" \t").casefold().startswith("claiming:"): + return set() + match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,4096})$", line, re.IGNORECASE) if not match: continue tail = unwrap_work_id_code(match.group(1).strip()) @@ -1066,22 +1076,15 @@ jobs: stripped_bullet = lines[cursor].lstrip(" \t") if stripped_bullet.startswith(("-", "*")): candidate_text = stripped_bullet[1:].lstrip(" \t") - candidate_inline = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), - candidate_text, - ) - candidate_ids = ( - ID_LIST_RE.match(candidate_inline.group(1).strip()) - if candidate_inline else ID_LIST_RE.match(candidate_text) - ) - if ( - len(candidate_text) > 512 - and ( - candidate_ids - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_text) - ) - ): - batch_valid = False + if len(candidate_text) > 512: + candidate_prefix = candidate_text[:512] + if candidate_prefix.startswith(BACKTICK): + candidate_prefix = candidate_prefix[1:] + if ( + ID_LIST_RE.match(candidate_prefix) + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) + ): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -1144,9 +1147,16 @@ jobs: def pull_claim_ids(pull, comments_by_id): found = ids_from_text(pull.get("title") or "") - unresolved_links = [] - body = re.sub(r"", "", pull.get("body") or "") - for field in CLAIM_FIELD_RE.finditer(body): + unresolved_links = [] + raw_body = pull.get("body") or "" + if len(raw_body) > MAX_CLAIM_BODY_CHARS: + return found, ["PR body exceeds the claim parser size limit"] + body = re.sub(r"", "", raw_body) + field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) + fields = list(CLAIM_FIELD_RE.finditer(body)) + if len(field_headers) != len(fields): + unresolved_links.append("Claimed in the coordination issue field exceeds the parser limit") + for field in fields: value = field.group(1) found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): From 07007fd81d4ed89dd57fb0bc8a30f5a6c1b7a6c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:56:55 -0300 Subject: [PATCH 49/53] ci: cap claim fields and parser input --- .github/workflows/coordination-claim.yml | 53 +++++++++++++----------- 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index cc624a94d0..ce3da44d7f 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -39,10 +39,13 @@ jobs: WORK_ID_RE = re.compile(ID_PATTERN) ID_LIST_RE = re.compile(rf"^({ID_PATTERN}(?:\s*,\s*{ID_PATTERN})*)(?![A-Za-z0-9-])") CLAIM_FIELD_RE = re.compile( - r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,65536})[ \t]{0,128}$" - ) - BACKTICK = chr(96) - MAX_CLAIM_BODY_CHARS = 65536 + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,4096})[ \t]{0,128}$" + ) + CLAIM_FIELD_HEADER_RE = re.compile( + r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" + ) BACKTICK = chr(96) + MAX_CLAIM_BODY_CHARS = 65536 + MAX_CLAIM_VALUE_CHARS = 4096 def fail(message): @@ -257,7 +260,9 @@ jobs: lines = body.splitlines() found = set() for index, line in enumerate(lines): - match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,65536})$", line, re.IGNORECASE) + if len(line) > MAX_CLAIM_VALUE_CHARS + 265 and line.lstrip(" \t").casefold().startswith("claiming:"): + return set() + match = re.match(r"^[ \t]{0,128}claiming:[ \t]{0,128}([^\r\n]{0,4096})$", line, re.IGNORECASE) if not match: continue tail = unwrap_work_id_code(match.group(1).strip()) @@ -283,22 +288,15 @@ jobs: stripped_bullet = lines[cursor].lstrip(" \t") if stripped_bullet.startswith(("-", "*")): candidate_text = stripped_bullet[1:].lstrip(" \t") - candidate_inline = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), - candidate_text, - ) - candidate_ids = ( - ID_LIST_RE.match(candidate_inline.group(1).strip()) - if candidate_inline else ID_LIST_RE.match(candidate_text) - ) - if ( - len(candidate_text) > 512 - and ( - candidate_ids - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_text) - ) - ): - batch_valid = False + if len(candidate_text) > 512: + candidate_prefix = candidate_text[:512] + if candidate_prefix.startswith(BACKTICK): + candidate_prefix = candidate_prefix[1:] + if ( + ID_LIST_RE.match(candidate_prefix) + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) + ): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -361,9 +359,16 @@ jobs: def pull_claim_ids(pull, comments_by_id): found = ids_from_text(pull.get("title") or "") - unresolved_links = [] - body = re.sub(r"", "", pull.get("body") or "") - for field in CLAIM_FIELD_RE.finditer(body): + unresolved_links = [] + raw_body = pull.get("body") or "" + if len(raw_body) > MAX_CLAIM_BODY_CHARS: + return found, ["PR body exceeds the claim parser size limit"] + body = re.sub(r"", "", raw_body) + field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) + fields = list(CLAIM_FIELD_RE.finditer(body)) + if len(field_headers) != len(fields): + unresolved_links.append("Claimed in the coordination issue field exceeds the parser limit") + for field in fields: value = field.group(1) found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): From 877314681bf2df163bd325085c030fb58d0569b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 03:59:55 -0300 Subject: [PATCH 50/53] fix: separate claim regex constants --- .github/workflows/coordination-activity.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 050a2d590d..d69dd37dab 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -74,7 +74,8 @@ jobs: ) CLAIM_FIELD_HEADER_RE = re.compile( r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" - ) BACKTICK = chr(96) + ) + BACKTICK = chr(96) MAX_CLAIM_BODY_CHARS = 65536 MAX_CLAIM_VALUE_CHARS = 4096 @@ -823,7 +824,8 @@ jobs: ) CLAIM_FIELD_HEADER_RE = re.compile( r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" - ) BACKTICK = chr(96) + ) + BACKTICK = chr(96) MAX_CLAIM_BODY_CHARS = 65536 MAX_CLAIM_VALUE_CHARS = 4096 From 1d7d4d67c9efda88b4f07840766aa4ce5a697902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 04:00:09 -0300 Subject: [PATCH 51/53] fix: separate claim regex constants --- .github/workflows/coordination-claim.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index ce3da44d7f..b593137957 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -43,7 +43,8 @@ jobs: ) CLAIM_FIELD_HEADER_RE = re.compile( r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" - ) BACKTICK = chr(96) + ) + BACKTICK = chr(96) MAX_CLAIM_BODY_CHARS = 65536 MAX_CLAIM_VALUE_CHARS = 4096 From 1f5d89e931d6a0294bdd42885d1278438c89924b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 04:04:49 -0300 Subject: [PATCH 52/53] ci: reject malformed batches and bound comment targeting --- .github/workflows/coordination-activity.yml | 152 +++++++++++++++----- 1 file changed, 120 insertions(+), 32 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index d69dd37dab..1e5a98dd45 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -165,15 +165,22 @@ jobs: except (TypeError, ValueError): error_payload = {} body_errors = error_payload.get("errors") if isinstance(error_payload, dict) else None - if body_errors: + top_level_type = error_payload.get("type") if isinstance(error_payload, dict) else None + if top_level_type is not None: + if top_level_type != "RATE_LIMITED": + rate_limited_http = False + elif body_errors: + rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) + else: + rate_limited_http = True + elif body_errors: rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) else: body_message = error_payload.get("message", "") if isinstance(error_payload, dict) else "" rate_limited_http = error.code == 429 or ( error.code == 403 and "rate limit" in str(body_message or detail).casefold() - ) - retry_after = error.headers.get("Retry-After") + ) retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None except (TypeError, ValueError): @@ -265,8 +272,29 @@ jobs: comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] return comments - def ids_from_text(text): - return {value.upper() for value in WORK_ID_RE.findall(text or "")} + def ids_from_text(text): + text = text or "" + if len(text) > MAX_CLAIM_BODY_CHARS: + return set() + return {value.upper() for value in WORK_ID_RE.findall(text)} + + def strip_html_comments(text): + text = text or "" + if len(text) > MAX_CLAIM_BODY_CHARS: + return "" + visible = [] + cursor = 0 + while cursor < len(text): + start = text.find("", start + 4) + if end < 0: + break + cursor = end + 3 + return "".join(visible) def work_id_list(text): @@ -326,16 +354,17 @@ jobs: if not bullet: stripped_bullet = lines[cursor].lstrip(" \t") if stripped_bullet.startswith(("-", "*")): + indent = len(lines[cursor]) - len(stripped_bullet) candidate_text = stripped_bullet[1:].lstrip(" \t") - if len(candidate_text) > 512: - candidate_prefix = candidate_text[:512] - if candidate_prefix.startswith(BACKTICK): - candidate_prefix = candidate_prefix[1:] - if ( - ID_LIST_RE.match(candidate_prefix) - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) - ): - batch_valid = False + candidate_prefix = candidate_text[:512] + if candidate_prefix.startswith(BACKTICK): + candidate_prefix = candidate_prefix[1:] + candidate_id_like = ( + ID_LIST_RE.match(candidate_prefix) + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) + ) + if candidate_id_like and (indent > 128 or len(candidate_text) > 512): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -350,6 +379,18 @@ jobs: and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) ): batch_valid = False + malformed_code_span = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), + bullet_text, + ) + if malformed_code_span and any( + re.match( + r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", + code_item.strip(), + ) + for code_item in malformed_code_span.group(1).split(",") + ): + batch_valid = False leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): batch_valid = False @@ -402,7 +443,7 @@ jobs: raw_body = pull.get("body") or "" if len(raw_body) > MAX_CLAIM_BODY_CHARS: return found, ["PR body exceeds the claim parser size limit"] - body = re.sub(r"", "", raw_body) + body = strip_html_comments(raw_body) field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) fields = list(CLAIM_FIELD_RE.finditer(body)) if len(field_headers) != len(fields): @@ -491,7 +532,10 @@ jobs: candidates, _unresolved = pull_claim_ids(pull, comments_by_id) if candidates & changed_ids: return True - body = re.sub(r"", "", pull.get("body") or "") + raw_body = pull.get("body") or "" + if len(raw_body) > MAX_CLAIM_BODY_CHARS: + return False + body = strip_html_comments(raw_body) linked_ids = { linked_id for field in CLAIM_FIELD_RE.finditer(body) @@ -915,15 +959,22 @@ jobs: except (TypeError, ValueError): error_payload = {} body_errors = error_payload.get("errors") if isinstance(error_payload, dict) else None - if body_errors: + top_level_type = error_payload.get("type") if isinstance(error_payload, dict) else None + if top_level_type is not None: + if top_level_type != "RATE_LIMITED": + rate_limited_http = False + elif body_errors: + rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) + else: + rate_limited_http = True + elif body_errors: rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) else: body_message = error_payload.get("message", "") if isinstance(error_payload, dict) else "" rate_limited_http = error.code == 429 or ( error.code == 403 and "rate limit" in str(body_message or detail).casefold() - ) - retry_after = error.headers.get("Retry-After") + ) retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None except (TypeError, ValueError): @@ -1016,8 +1067,29 @@ jobs: comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] return comments - def ids_from_text(text): - return {value.upper() for value in WORK_ID_RE.findall(text or "")} + def ids_from_text(text): + text = text or "" + if len(text) > MAX_CLAIM_BODY_CHARS: + return set() + return {value.upper() for value in WORK_ID_RE.findall(text)} + + def strip_html_comments(text): + text = text or "" + if len(text) > MAX_CLAIM_BODY_CHARS: + return "" + visible = [] + cursor = 0 + while cursor < len(text): + start = text.find("", start + 4) + if end < 0: + break + cursor = end + 3 + return "".join(visible) def work_id_list(text): @@ -1077,16 +1149,17 @@ jobs: if not bullet: stripped_bullet = lines[cursor].lstrip(" \t") if stripped_bullet.startswith(("-", "*")): + indent = len(lines[cursor]) - len(stripped_bullet) candidate_text = stripped_bullet[1:].lstrip(" \t") - if len(candidate_text) > 512: - candidate_prefix = candidate_text[:512] - if candidate_prefix.startswith(BACKTICK): - candidate_prefix = candidate_prefix[1:] - if ( - ID_LIST_RE.match(candidate_prefix) - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) - ): - batch_valid = False + candidate_prefix = candidate_text[:512] + if candidate_prefix.startswith(BACKTICK): + candidate_prefix = candidate_prefix[1:] + candidate_id_like = ( + ID_LIST_RE.match(candidate_prefix) + or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) + ) + if candidate_id_like and (indent > 128 or len(candidate_text) > 512): + batch_valid = False break bullet_text = unwrap_work_id_code(bullet.group(1)) first_ids = work_id_list(bullet_text) @@ -1101,6 +1174,18 @@ jobs: and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) ): batch_valid = False + malformed_code_span = re.match( + "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), + bullet_text, + ) + if malformed_code_span and any( + re.match( + r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", + code_item.strip(), + ) + for code_item in malformed_code_span.group(1).split(",") + ): + batch_valid = False leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): batch_valid = False @@ -1153,7 +1238,7 @@ jobs: raw_body = pull.get("body") or "" if len(raw_body) > MAX_CLAIM_BODY_CHARS: return found, ["PR body exceeds the claim parser size limit"] - body = re.sub(r"", "", raw_body) + body = strip_html_comments(raw_body) field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) fields = list(CLAIM_FIELD_RE.finditer(body)) if len(field_headers) != len(fields): @@ -1242,7 +1327,10 @@ jobs: candidates, _unresolved = pull_claim_ids(pull, comments_by_id) if candidates & changed_ids: return True - body = re.sub(r"", "", pull.get("body") or "") + raw_body = pull.get("body") or "" + if len(raw_body) > MAX_CLAIM_BODY_CHARS: + return False + body = strip_html_comments(raw_body) linked_ids = { linked_id for field in CLAIM_FIELD_RE.finditer(body) From ade227657e863b19765d64f1d3076e32dcb78a62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9LanD?= Date: Tue, 24 Nov 2026 04:16:56 -0300 Subject: [PATCH 53/53] ci: align claim parsing and fix activity script syntax --- .github/workflows/coordination-activity.yml | 268 ++++++++------------ .github/workflows/coordination-claim.yml | 136 +++++----- 2 files changed, 190 insertions(+), 214 deletions(-) diff --git a/.github/workflows/coordination-activity.yml b/.github/workflows/coordination-activity.yml index 1e5a98dd45..8dde556eff 100644 --- a/.github/workflows/coordination-activity.yml +++ b/.github/workflows/coordination-activity.yml @@ -69,12 +69,6 @@ jobs: ID_PATTERN = r"(??[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,4096})[ \t]{0,128}$" - ) - CLAIM_FIELD_HEADER_RE = re.compile( - r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" - ) BACKTICK = chr(96) MAX_CLAIM_BODY_CHARS = 65536 MAX_CLAIM_VALUE_CHARS = 4096 @@ -180,7 +174,8 @@ jobs: rate_limited_http = error.code == 429 or ( error.code == 403 and "rate limit" in str(body_message or detail).casefold() - ) retry_after = error.headers.get("Retry-After") + ) + retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None except (TypeError, ValueError): @@ -349,60 +344,29 @@ jobs: cursor += 1 batch_ids = set() batch_valid = True - while cursor < len(lines): - bullet = re.match(r"^[ \t]{0,128}[-*][ \t]{1,128}(.{1,512})[ \t]{0,128}$", lines[cursor]) - if not bullet: - stripped_bullet = lines[cursor].lstrip(" \t") - if stripped_bullet.startswith(("-", "*")): - indent = len(lines[cursor]) - len(stripped_bullet) - candidate_text = stripped_bullet[1:].lstrip(" \t") - candidate_prefix = candidate_text[:512] - if candidate_prefix.startswith(BACKTICK): - candidate_prefix = candidate_prefix[1:] - candidate_id_like = ( - ID_LIST_RE.match(candidate_prefix) - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) - ) - if candidate_id_like and (indent > 128 or len(candidate_text) > 512): - batch_valid = False - break - bullet_text = unwrap_work_id_code(bullet.group(1)) - first_ids = work_id_list(bullet_text) - if not first_ids: - malformed_inline_id = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + - re.escape(BACKTICK) + r"[A-Za-z0-9-]", - bullet_text, - ) - if ( - malformed_inline_id - and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) - ): - batch_valid = False - malformed_code_span = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), - bullet_text, - ) - if malformed_code_span and any( - re.match( - r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", - code_item.strip(), - ) - for code_item in malformed_code_span.group(1).split(",") - ): - batch_valid = False - leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) - if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): - batch_valid = False - malformed_id_suffix = re.match( - r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", - bullet_text, - ) - if malformed_id_suffix: - batch_valid = False - break - batch_ids.update(ids_from_text(first_ids.group(1))) - cursor += 1 + while cursor < len(lines): + line = lines[cursor] + bullet = line.lstrip(" \t") + if not bullet.startswith(("-", "*")): + break + item = bullet[1:] + text = item.lstrip(" \t") + candidate = text.rstrip(" \t") + indent = len(line) - len(bullet) + gap = len(item) - len(text) + if indent <= 128 and 1 <= gap <= 128 and len(candidate) <= 512: + first_ids = work_id_list(unwrap_work_id_code(candidate)) + if first_ids: + batch_ids.update(ids_from_text(first_ids.group(1))) + cursor += 1 + continue + # A malformed ID-like bullet invalidates the batch. Other bullets end it. + prefix = candidate[:512] + if prefix.startswith(BACKTICK): + prefix = prefix[1:].lstrip(" \t") + if re.match(r"^[A-Z0-9]+-", prefix): + batch_valid = False + break if batch_valid: found.update(batch_ids) return found @@ -437,19 +401,34 @@ jobs: return None - def pull_claim_ids(pull, comments_by_id): - found = ids_from_text(pull.get("title") or "") + def claim_fields(body): + values = [] + field_too_long = False + label = "claimed in the coordination issue as:" + for line in strip_html_comments(body).splitlines(): + line = line.lstrip(" \t") + if line.startswith(">"): + line = line[1:].lstrip(" \t") + if line[:len(label)].lower() != label: + continue + value = line[len(label):].strip(" \t") + if len(value) > MAX_CLAIM_VALUE_CHARS: + field_too_long = True + else: + values.append(value) + return values, field_too_long + + + def pull_claim_ids(pull, comments_by_id): + found = ids_from_text(pull.get("title") or "") unresolved_links = [] raw_body = pull.get("body") or "" if len(raw_body) > MAX_CLAIM_BODY_CHARS: return found, ["PR body exceeds the claim parser size limit"] - body = strip_html_comments(raw_body) - field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) - fields = list(CLAIM_FIELD_RE.finditer(body)) - if len(field_headers) != len(fields): + fields, field_too_long = claim_fields(raw_body) + if field_too_long: unresolved_links.append("Claimed in the coordination issue field exceeds the parser limit") - for field in fields: - value = field.group(1) + for value in fields: found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): linked = comments_by_id.get(comment_id) @@ -532,16 +511,15 @@ jobs: candidates, _unresolved = pull_claim_ids(pull, comments_by_id) if candidates & changed_ids: return True - raw_body = pull.get("body") or "" - if len(raw_body) > MAX_CLAIM_BODY_CHARS: + if not comment_id: return False - body = strip_html_comments(raw_body) - linked_ids = { - linked_id - for field in CLAIM_FIELD_RE.finditer(body) - for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) - } - return bool(comment_id and comment_id in linked_ids) + fields, _field_too_long = claim_fields(pull.get("body") or "") + return any( + comment_id in re.findall(r"#issuecomment-(\d+)", value) + for value in fields + ) + + def workflow_run_matches_pull(run, pull): head = pull.get("head") or {} base = pull.get("base") or {} @@ -863,12 +841,6 @@ jobs: ID_PATTERN = r"(??[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,4096})[ \t]{0,128}$" - ) - CLAIM_FIELD_HEADER_RE = re.compile( - r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" - ) BACKTICK = chr(96) MAX_CLAIM_BODY_CHARS = 65536 MAX_CLAIM_VALUE_CHARS = 4096 @@ -974,7 +946,8 @@ jobs: rate_limited_http = error.code == 429 or ( error.code == 403 and "rate limit" in str(body_message or detail).casefold() - ) retry_after = error.headers.get("Retry-After") + ) + retry_after = error.headers.get("Retry-After") try: delay = float(retry_after) if retry_after is not None else None except (TypeError, ValueError): @@ -1144,60 +1117,29 @@ jobs: cursor += 1 batch_ids = set() batch_valid = True - while cursor < len(lines): - bullet = re.match(r"^[ \t]{0,128}[-*][ \t]{1,128}(.{1,512})[ \t]{0,128}$", lines[cursor]) - if not bullet: - stripped_bullet = lines[cursor].lstrip(" \t") - if stripped_bullet.startswith(("-", "*")): - indent = len(lines[cursor]) - len(stripped_bullet) - candidate_text = stripped_bullet[1:].lstrip(" \t") - candidate_prefix = candidate_text[:512] - if candidate_prefix.startswith(BACKTICK): - candidate_prefix = candidate_prefix[1:] - candidate_id_like = ( - ID_LIST_RE.match(candidate_prefix) - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) - ) - if candidate_id_like and (indent > 128 or len(candidate_text) > 512): - batch_valid = False - break - bullet_text = unwrap_work_id_code(bullet.group(1)) - first_ids = work_id_list(bullet_text) - if not first_ids: - malformed_inline_id = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + - re.escape(BACKTICK) + r"[A-Za-z0-9-]", - bullet_text, - ) - if ( - malformed_inline_id - and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) - ): - batch_valid = False - malformed_code_span = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + re.escape(BACKTICK), - bullet_text, - ) - if malformed_code_span and any( - re.match( - r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", - code_item.strip(), - ) - for code_item in malformed_code_span.group(1).split(",") - ): - batch_valid = False - leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) - if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): - batch_valid = False - malformed_id_suffix = re.match( - r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", - bullet_text, - ) - if malformed_id_suffix: - batch_valid = False - break - batch_ids.update(ids_from_text(first_ids.group(1))) - cursor += 1 + while cursor < len(lines): + line = lines[cursor] + bullet = line.lstrip(" \t") + if not bullet.startswith(("-", "*")): + break + item = bullet[1:] + text = item.lstrip(" \t") + candidate = text.rstrip(" \t") + indent = len(line) - len(bullet) + gap = len(item) - len(text) + if indent <= 128 and 1 <= gap <= 128 and len(candidate) <= 512: + first_ids = work_id_list(unwrap_work_id_code(candidate)) + if first_ids: + batch_ids.update(ids_from_text(first_ids.group(1))) + cursor += 1 + continue + # A malformed ID-like bullet invalidates the batch. Other bullets end it. + prefix = candidate[:512] + if prefix.startswith(BACKTICK): + prefix = prefix[1:].lstrip(" \t") + if re.match(r"^[A-Z0-9]+-", prefix): + batch_valid = False + break if batch_valid: found.update(batch_ids) return found @@ -1232,19 +1174,34 @@ jobs: return None - def pull_claim_ids(pull, comments_by_id): - found = ids_from_text(pull.get("title") or "") + def claim_fields(body): + values = [] + field_too_long = False + label = "claimed in the coordination issue as:" + for line in strip_html_comments(body).splitlines(): + line = line.lstrip(" \t") + if line.startswith(">"): + line = line[1:].lstrip(" \t") + if line[:len(label)].lower() != label: + continue + value = line[len(label):].strip(" \t") + if len(value) > MAX_CLAIM_VALUE_CHARS: + field_too_long = True + else: + values.append(value) + return values, field_too_long + + + def pull_claim_ids(pull, comments_by_id): + found = ids_from_text(pull.get("title") or "") unresolved_links = [] raw_body = pull.get("body") or "" if len(raw_body) > MAX_CLAIM_BODY_CHARS: return found, ["PR body exceeds the claim parser size limit"] - body = strip_html_comments(raw_body) - field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) - fields = list(CLAIM_FIELD_RE.finditer(body)) - if len(field_headers) != len(fields): + fields, field_too_long = claim_fields(raw_body) + if field_too_long: unresolved_links.append("Claimed in the coordination issue field exceeds the parser limit") - for field in fields: - value = field.group(1) + for value in fields: found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): linked = comments_by_id.get(comment_id) @@ -1327,16 +1284,15 @@ jobs: candidates, _unresolved = pull_claim_ids(pull, comments_by_id) if candidates & changed_ids: return True - raw_body = pull.get("body") or "" - if len(raw_body) > MAX_CLAIM_BODY_CHARS: + if not comment_id: return False - body = strip_html_comments(raw_body) - linked_ids = { - linked_id - for field in CLAIM_FIELD_RE.finditer(body) - for linked_id in re.findall(r"#issuecomment-(\d+)", field.group(1)) - } - return bool(comment_id and comment_id in linked_ids) + fields, _field_too_long = claim_fields(pull.get("body") or "") + return any( + comment_id in re.findall(r"#issuecomment-(\d+)", value) + for value in fields + ) + + def workflow_run_matches_pull(run, pull): head = pull.get("head") or {} base = pull.get("base") or {} diff --git a/.github/workflows/coordination-claim.yml b/.github/workflows/coordination-claim.yml index b593137957..3b6188d565 100644 --- a/.github/workflows/coordination-claim.yml +++ b/.github/workflows/coordination-claim.yml @@ -38,12 +38,6 @@ jobs: ID_PATTERN = r"(??[ \t]{0,128}Claimed in the coordination issue as:[ \t]{0,128}([^\r\n]{0,4096})[ \t]{0,128}$" - ) - CLAIM_FIELD_HEADER_RE = re.compile( - r"(?im)^[ \t]{0,128}>?[ \t]{0,128}Claimed in the coordination issue as:" - ) BACKTICK = chr(96) MAX_CLAIM_BODY_CHARS = 65536 MAX_CLAIM_VALUE_CHARS = 4096 @@ -128,7 +122,15 @@ jobs: except (TypeError, ValueError): error_payload = {} body_errors = error_payload.get("errors") if isinstance(error_payload, dict) else None - if body_errors: + top_level_type = error_payload.get("type") if isinstance(error_payload, dict) else None + if top_level_type is not None: + if top_level_type != "RATE_LIMITED": + rate_limited_http = False + elif body_errors: + rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) + else: + rate_limited_http = True + elif body_errors: rate_limited_http = all(is_rate_limit_error(item) for item in body_errors) else: body_message = error_payload.get("message", "") if isinstance(error_payload, dict) else "" @@ -227,8 +229,29 @@ jobs: comment["_last_edited_at"] = edited_at_by_id[str(comment["id"])] return comments - def ids_from_text(text): - return {value.upper() for value in WORK_ID_RE.findall(text or "")} + def ids_from_text(text): + text = text or "" + if len(text) > MAX_CLAIM_BODY_CHARS: + return set() + return {value.upper() for value in WORK_ID_RE.findall(text)} + + def strip_html_comments(text): + text = text or "" + if len(text) > MAX_CLAIM_BODY_CHARS: + return "" + visible = [] + cursor = 0 + while cursor < len(text): + start = text.find("", start + 4) + if end < 0: + break + cursor = end + 3 + return "".join(visible) def work_id_list(text): @@ -283,47 +306,29 @@ jobs: cursor += 1 batch_ids = set() batch_valid = True - while cursor < len(lines): - bullet = re.match(r"^[ \t]{0,128}[-*][ \t]{1,128}(.{1,512})[ \t]{0,128}$", lines[cursor]) - if not bullet: - stripped_bullet = lines[cursor].lstrip(" \t") - if stripped_bullet.startswith(("-", "*")): - candidate_text = stripped_bullet[1:].lstrip(" \t") - if len(candidate_text) > 512: - candidate_prefix = candidate_text[:512] - if candidate_prefix.startswith(BACKTICK): - candidate_prefix = candidate_prefix[1:] - if ( - ID_LIST_RE.match(candidate_prefix) - or re.match(r"^[A-Z0-9]+(?:-[A-Z0-9]+)+", candidate_prefix) - ): - batch_valid = False - break - bullet_text = unwrap_work_id_code(bullet.group(1)) - first_ids = work_id_list(bullet_text) - if not first_ids: - malformed_inline_id = re.match( - "^" + re.escape(BACKTICK) + "([^" + BACKTICK + "]+)" + - re.escape(BACKTICK) + r"[A-Za-z0-9-]", - bullet_text, - ) - if ( - malformed_inline_id - and ID_LIST_RE.fullmatch(malformed_inline_id.group(1).strip()) - ): - batch_valid = False - leading_id = re.match(rf"^{ID_PATTERN}", bullet_text) - if leading_id and re.match(r"^\s*,", bullet_text[leading_id.end():]): - batch_valid = False - malformed_id_suffix = re.match( - r"^[A-Z0-9]+(?:-[A-Z0-9]+)+[A-Za-z0-9-]", - bullet_text, - ) - if malformed_id_suffix: - batch_valid = False - break - batch_ids.update(ids_from_text(first_ids.group(1))) - cursor += 1 + while cursor < len(lines): + line = lines[cursor] + bullet = line.lstrip(" \t") + if not bullet.startswith(("-", "*")): + break + item = bullet[1:] + text = item.lstrip(" \t") + candidate = text.rstrip(" \t") + indent = len(line) - len(bullet) + gap = len(item) - len(text) + if indent <= 128 and 1 <= gap <= 128 and len(candidate) <= 512: + first_ids = work_id_list(unwrap_work_id_code(candidate)) + if first_ids: + batch_ids.update(ids_from_text(first_ids.group(1))) + cursor += 1 + continue + # A malformed ID-like bullet invalidates the batch. Other bullets end it. + prefix = candidate[:512] + if prefix.startswith(BACKTICK): + prefix = prefix[1:].lstrip(" \t") + if re.match(r"^[A-Z0-9]+-", prefix): + batch_valid = False + break if batch_valid: found.update(batch_ids) return found @@ -358,19 +363,34 @@ jobs: return None - def pull_claim_ids(pull, comments_by_id): - found = ids_from_text(pull.get("title") or "") + def claim_fields(body): + values = [] + field_too_long = False + label = "claimed in the coordination issue as:" + for line in strip_html_comments(body).splitlines(): + line = line.lstrip(" \t") + if line.startswith(">"): + line = line[1:].lstrip(" \t") + if line[:len(label)].lower() != label: + continue + value = line[len(label):].strip(" \t") + if len(value) > MAX_CLAIM_VALUE_CHARS: + field_too_long = True + else: + values.append(value) + return values, field_too_long + + + def pull_claim_ids(pull, comments_by_id): + found = ids_from_text(pull.get("title") or "") unresolved_links = [] raw_body = pull.get("body") or "" if len(raw_body) > MAX_CLAIM_BODY_CHARS: return found, ["PR body exceeds the claim parser size limit"] - body = re.sub(r"", "", raw_body) - field_headers = list(CLAIM_FIELD_HEADER_RE.finditer(body)) - fields = list(CLAIM_FIELD_RE.finditer(body)) - if len(field_headers) != len(fields): + fields, field_too_long = claim_fields(raw_body) + if field_too_long: unresolved_links.append("Claimed in the coordination issue field exceeds the parser limit") - for field in fields: - value = field.group(1) + for value in fields: found.update(ids_from_text(value)) for comment_id in re.findall(r"#issuecomment-(\d+)", value): linked = comments_by_id.get(comment_id)