Skip to content

Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.

chore: automate issue triage (#48)

TamL.909644f3f21a
diff --git a/.github/ISSUE_TEMPLATE/contribution_intent.yml b/.github/ISSUE_TEMPLATE/contribution_intent.yml
new file mode 100644
index 0000000..94c4a31
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/contribution_intent.yml
@@ -0,0 +1,60 @@
+name: Contribution intent
+description: Propose a bounded fix or offer to work on an existing issue.
+title: "[Contribution]: "
+labels: ["contribution: proposed"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thank you for offering to contribute. This form records intent; it does not assign, reserve, or guarantee acceptance of the work. A maintainer will discuss the proposal before any claim is confirmed.
+
+ - type: dropdown
+ id: target_type
+ attributes:
+ label: What are you proposing?
+ options:
+ - Fix an existing issue
+ - A bounded new fix
+ validations:
+ required: true
+
+ - type: input
+ id: target_issue
+ attributes:
+ label: Target issue URL or number
+ description: Required when fixing an existing issue. Otherwise write "new bounded fix".
+ placeholder: "#123"
+ validations:
+ required: true
+
+ - type: textarea
+ id: scope
+ attributes:
+ label: Proposed scope
+ description: Explain the behavior you plan to change and what you will intentionally leave out.
+ validations:
+ required: true
+
+ - type: textarea
+ id: acceptance
+ attributes:
+ label: Acceptance criteria and validation plan
+ description: State how maintainers can tell the fix is complete, including relevant tests or visual evidence.
+ validations:
+ required: true
+
+ - type: textarea
+ id: availability
+ attributes:
+ label: Availability
+ description: Share any timing or capacity context that helps maintainers coordinate; no response-time commitment is implied.
+ validations:
+ required: true
+
+ - type: checkboxes
+ id: acknowledgement
+ attributes:
+ label: Acknowledgement
+ options:
+ - label: I understand this form does not assign or reserve the work, and I will reference the issue number in any implementation PR.
+ required: true
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 259fd35..1946890 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -4,7 +4,7 @@ Thanks for contributing to img2threejs. Keep the pull request focused and remove
## Summary
-<!-- What behavior or documentation changes? Why is it needed? Link related issues with "Fixes #123" where applicable. -->
+<!-- What behavior or documentation changes? Why is it needed? Link related issues with "Refs #123" where applicable. Do not use closing keywords: maintainers close issues manually after final verification. -->
## Changes
diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml
new file mode 100644
index 0000000..5060ebc
--- /dev/null
+++ b/.github/workflows/issue-triage.yml
@@ -0,0 +1,54 @@
+name: Issue Triage
+
+on:
+ schedule:
+ - cron: "17 9 * * *"
+ workflow_dispatch:
+ inputs:
+ mode:
+ description: "Dry-run lists all candidates; backfill writes notices for historical candidates."
+ required: true
+ default: dry-run
+ type: choice
+ options:
+ - dry-run
+ - backfill
+
+permissions:
+ contents: read
+ issues: write
+
+concurrency:
+ group: issue-triage-${{ github.repository }}
+ cancel-in-progress: false
+
+env:
+ TRIAGE_ROLLOUT_AFTER: "2026-07-28T00:00:00Z"
+
+jobs:
+ triage:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
+ with:
+ python-version: "3.10"
+ - name: Run issue triage
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ set -o pipefail
+ args=()
+ if [ "${{ github.event_name }}" = "schedule" ]; then
+ epoch_day=$(( $(date -u +%s) / 86400 ))
+ if [ $(( epoch_day % 2 )) -ne 0 ]; then
+ echo "Skipping today: the continuous two-day cadence runs on even UTC epoch days."
+ exit 0
+ fi
+ args+=(--rollout-after "$TRIAGE_ROLLOUT_AFTER")
+ elif [ "${{ inputs.mode }}" = "dry-run" ]; then
+ args+=(--dry-run)
+ fi
+ python3 scripts/issue_triage.py "${args[@]}" | tee -a "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/pr-issue-close-policy.yml b/.github/workflows/pr-issue-close-policy.yml
new file mode 100644
index 0000000..c40b230
--- /dev/null
+++ b/.github/workflows/pr-issue-close-policy.yml
@@ -0,0 +1,22 @@
+name: PR Issue Close Policy
+
+on:
+ pull_request:
+ types: [opened, edited, reopened, synchronize]
+
+permissions:
+ contents: read
+
+jobs:
+ reject-closing-keywords:
+ runs-on: ubuntu-latest
+ env:
+ PR_TITLE: ${{ github.event.pull_request.title }}
+ PR_BODY: ${{ github.event.pull_request.body }}
+ steps:
+ - name: Require manual issue closure
+ run: |
+ if printf '%s\n%s' "$PR_TITLE" "$PR_BODY" | grep -Eqi '\b(close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)\b[[:space:]]+([[:alnum:]_.-]+/[[:alnum:]_.-]+)?#[0-9]+'; then
+ echo "PR title/body must use Refs #123, not a closing keyword. Maintainers close issues manually after documented discussion and verification."
+ exit 1
+ fi
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6b792d3..131e6fd 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -38,12 +38,25 @@ explicit, flagged, opt-in mode.
- For a proposal, describe the problem, the observable outcome, and how it preserves the project's code-only procedural reconstruction contract.
- Use a discussion channel or another appropriate forum for usage questions when one is available; issues should be actionable bugs or focused proposals.
+## Triage and contributor intent
+
+- The issue itself is the triage discussion record. A `triage: needs-review` label means the issue
+ is waiting for maintainer review; a label is not a promise that it will be implemented.
+- Maintainers record a decision comment before setting priority, contributor state, or closure.
+ `priority: low` keeps an issue open and must include a reason and a revisit trigger.
+- To offer a fix, use the **Contribution intent** form. It records your proposed scope and does not
+ reserve or assign the work. A maintainer will discuss and, if appropriate, mark the target issue
+ `contribution: claimed`.
+- Link implementation PRs with `Refs #<number>` or `Related to #<number>`. Do not use closing
+ keywords. A maintainer manually closes an issue only after recording the merged PR, verification,
+ and closure rationale in a final comment.
+
## Pull requests
- Keep PRs focused and describe the behavior change plus how you verified it.
- Add or update tests for new gates, schema fields, or templates.
- Update `docs/UPGRADE_PLAN.md` status when you land a roadmap item.
-- Link the issue with `Fixes #<number>` when applicable.
+- Link the issue with `Refs #<number>` when applicable.
- For changes that affect visual fidelity, include the relevant render or comparison-sheet evidence and the result of its review.
- Do not include private reference images, credentials, or other sensitive material in the PR description, commits, or attachments.
diff --git a/docs/issue-triage.md b/docs/issue-triage.md
new file mode 100644
index 0000000..c554885
--- /dev/null
+++ b/docs/issue-triage.md
@@ -0,0 +1,30 @@
+# Issue triage
+
+The triage workflow starts daily at 09:17 UTC and runs its helper on every second UTC epoch day, so
+the cadence stays continuous across month boundaries. It is best effort, not an exact 48-hour
+service level. A maintainer can use **Run workflow** in dry-run mode to see every zero-label
+candidate, then use backfill only after reviewing that result. Scheduled runs consider only issues
+created after `TRIAGE_ROLLOUT_AFTER` in `.github/workflows/issue-triage.yml`.
+
+## Labels
+
+| Axis | Labels | Owner |
+| --- | --- | --- |
+| Queue | `triage: needs-review`, `triage: discussed` | Bot adds only `needs-review`; maintainers transition it after discussion. |
+| Priority | `priority: high`, `priority: medium`, `priority: low` | Maintainer, after a decision comment. |
+| Contribution | `contribution: proposed`, `contribution: available`, `contribution: claimed` | The form adds `proposed`; maintainers control target-issue availability and claims. |
+
+Existing labels such as `bug`, `enhancement`, and `documentation` remain independent. The bot never
+removes labels, closes issues, locks them, assigns people, or applies terminal labels.
+
+The scheduled candidate set is open non-PR issues with zero labels. The only exception is recovery
+of an issue carrying exactly `triage: needs-review` when a prior bot run added that label but failed
+before it could create the notice. A bot notice marker is accepted only from `github-actions[bot]`.
+
+## Maintainer decision record
+
+Before changing priority, contributor state, or closure, comment with the decision, rationale, next
+action, and a revisit trigger if the issue becomes low priority. Low-priority issues remain open.
+
+Implementation PRs use `Refs #<number>`. After merge, a maintainer records the merged PR,
+verification, and closure rationale in the issue, then closes manually when appropriate.
diff --git a/forge/tests/test_issue_triage.py b/forge/tests/test_issue_triage.py
new file mode 100644
index 0000000..d5d43cb
--- /dev/null
+++ b/forge/tests/test_issue_triage.py
@@ -0,0 +1,320 @@
+from __future__ import annotations
+
+import unittest
+import urllib.error
+from unittest.mock import patch
+
+from scripts.issue_triage import (
+ MissingQueueLabelError,
+ NOTICE_MARKER,
+ TRIAGE_BOT_LOGIN,
+ GitHubIssueApi,
+ QUEUE_LABEL,
+ Issue,
+ TriageOptions,
+ run_triage,
+)
+
+
+class FakeIssueApi:
+ def __init__(self, issues: dict[int, Issue], markers: set[int] | None = None) -> None:
+ self.issues = issues
+ self.markers = set() if markers is None else markers
+ self.operations: list[tuple[str, int]] = []
+
+ def list_open_issues(self) -> tuple[Issue, ...]:
+ return tuple(self.issues.values())
+
+ def queue_label_exists(self) -> bool:
+ return True
+
+ def get_issue(self, number: int) -> Issue | None:
+ return self.issues.get(number)
+
+ def has_notice_marker(self, number: int) -> bool:
+ return number in self.markers
+
+ def add_label(self, number: int, label: str) -> None:
+ self.operations.append((f"label:{label}", number))
+ issue = self.issues[number]
+ self.issues[number] = Issue(issue.number, issue.is_open, issue.is_pull_request, issue.labels + (label,))
+
+ def create_notice(self, number: int, notice: str) -> None:
+ self.operations.append(("comment", number))
+ if NOTICE_MARKER in notice:
+ self.markers.add(number)
+
+
+class MarkerFailingApi(FakeIssueApi):
+ def has_notice_marker(self, number: int) -> bool:
+ raise urllib.error.URLError("temporary GitHub failure")
+
+
+class NoticeFailingApi(FakeIssueApi):
+ def create_notice(self, number: int, notice: str) -> None:
+ self.operations.append(("comment", number))
+ raise urllib.error.URLError("temporary GitHub failure")
+
+
+class MissingQueueLabelApi(FakeIssueApi):
+ def queue_label_exists(self) -> bool:
+ return False
+
+
+class FakeResponse:
+ def __init__(self, body: str) -> None:
+ self._body = body.encode("utf-8")
+
+ def __enter__(self) -> "FakeResponse":
+ return self
+
+ def __exit__(self, exception_type, exception, traceback) -> bool:
+ return False
+
+ def read(self) -> bytes:
+ return self._body
+
+
+class IssueTriageTests(unittest.TestCase):
+ def test_notices_unlabeled_open_issue_once(self) -> None:
+ # Given: one unlabeled open issue.
+ api = FakeIssueApi({7: Issue(7, True, False, ())})
+
+ # When: the scheduled triage runs.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: the queue label and one notice are created.
+ self.assertEqual(result.noticed, (7,))
+ self.assertEqual(api.operations, [(f"label:{QUEUE_LABEL}", 7), ("comment", 7)])
+
+ def test_recovers_labelled_issue_when_notice_is_missing(self) -> None:
+ # Given: a previous run added the queue label but did not create its notice.
+ api = FakeIssueApi({8: Issue(8, True, False, (QUEUE_LABEL,))})
+
+ # When: triage runs again.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: it creates only the missing notice.
+ self.assertEqual(result.reconciled, (8,))
+ self.assertEqual(api.operations, [("comment", 8)])
+
+ def test_skips_pull_requests_and_type_labelled_issues(self) -> None:
+ # Given: a pull request and an issue already classified by its form.
+ api = FakeIssueApi(
+ {
+ 9: Issue(9, True, True, ()),
+ 10: Issue(10, True, False, ("bug",)),
+ }
+ )
+
+ # When: triage runs.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: neither record is mutated.
+ self.assertEqual(result.noticed, ())
+ self.assertEqual(api.operations, [])
+
+ def test_skips_human_labelled_queue_issue_without_notice(self) -> None:
+ # Given: a human has classified an issue after a previous partial bot write.
+ api = FakeIssueApi({10: Issue(10, True, False, (QUEUE_LABEL, "bug"))})
+
+ # When: triage runs again.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: it leaves human-classified issues for maintainer discussion.
+ self.assertEqual(result.skipped, (10,))
+ self.assertEqual(api.operations, [])
+
+ def test_dry_run_reports_candidates_without_mutation(self) -> None:
+ # Given: an unlabeled open issue.
+ api = FakeIssueApi({11: Issue(11, True, False, ())})
+
+ # When: a maintainer requests dry-run mode.
+ result = run_triage(api, TriageOptions(dry_run=True))
+
+ # Then: the candidate is reported but no issue write occurs.
+ self.assertEqual(result.would_notice, (11,))
+ self.assertEqual(api.operations, [])
+
+ def test_marker_prevents_duplicate_notice(self) -> None:
+ # Given: an issue already has the signed notice marker.
+ api = FakeIssueApi({12: Issue(12, True, False, (QUEUE_LABEL,))}, markers={12})
+
+ # When: triage runs again.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: it leaves the issue unchanged.
+ self.assertEqual(result.skipped, (12,))
+ self.assertEqual(api.operations, [])
+
+ def test_ignores_notice_marker_from_untrusted_commenter(self) -> None:
+ # Given: a user copies the marker into an issue comment.
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+ comments = FakeResponse(
+ '[{"body":"' + NOTICE_MARKER + '","user":{"login":"someone","type":"User"}}]'
+ )
+
+ # When: the helper checks whether it previously wrote the notice.
+ with patch("scripts.issue_triage.urllib.request.urlopen", side_effect=[comments, FakeResponse("[]")]):
+ marked = api.has_notice_marker(12)
+
+ # Then: an untrusted commenter cannot suppress triage.
+ self.assertFalse(marked)
+
+ def test_trusted_bot_marker_prevents_duplicate_notice(self) -> None:
+ # Given: GitHub Actions previously wrote the marker.
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+ comments = FakeResponse(
+ '[{"body":"' + NOTICE_MARKER + '","user":{"login":"' + TRIAGE_BOT_LOGIN + '","type":"Bot"}}]'
+ )
+
+ # When: the helper checks the issue comments.
+ with patch("scripts.issue_triage.urllib.request.urlopen", return_value=comments):
+ marked = api.has_notice_marker(12)
+
+ # Then: it recognizes only the bot's own marker.
+ self.assertTrue(marked)
+
+ def test_rechecks_for_notice_before_retrying_ambiguous_comment_write(self) -> None:
+ # Given: a comment POST gets a transient response after GitHub accepted it.
+ transient = urllib.error.HTTPError("https://api.github.test", 503, "unavailable", None, None)
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+ comments = FakeResponse(
+ '[{"body":"' + NOTICE_MARKER + '","user":{"login":"' + TRIAGE_BOT_LOGIN + '","type":"Bot"}}]'
+ )
+
+ # When: the helper handles the ambiguous write result.
+ with patch("scripts.issue_triage.urllib.request.urlopen", side_effect=[transient, comments]) as request:
+ api.create_notice(12, NOTICE_MARKER)
+ transient.close()
+
+ # Then: it reads the marker instead of repeating the POST.
+ self.assertEqual(request.call_count, 2)
+ self.assertIn("/issues/12/comments?", request.call_args_list[1].args[0].full_url)
+
+ def test_reads_every_page_of_issue_comments_for_a_trusted_marker(self) -> None:
+ # Given: the trusted notice is beyond the first GitHub comments page.
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+ first_page = FakeResponse('[{"body":"discussion","user":{"login":"someone","type":"User"}}]')
+ second_page = FakeResponse(
+ '[{"body":"' + NOTICE_MARKER + '","user":{"login":"' + TRIAGE_BOT_LOGIN + '","type":"Bot"}}]'
+ )
+
+ # When: it searches the issue comments.
+ with patch("scripts.issue_triage.urllib.request.urlopen", side_effect=[first_page, second_page]) as request:
+ marked = api.has_notice_marker(12)
+
+ # Then: the later trusted marker is found.
+ self.assertTrue(marked)
+ self.assertIn("page=2", request.call_args_list[1].args[0].full_url)
+
+ def test_reads_every_page_of_open_issues(self) -> None:
+ # Given: GitHub has more than one page of open records.
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+ first_page = FakeResponse('[{"number":18,"state":"open","labels":[],"created_at":"2026-07-28T00:00:00Z"}]')
+ second_page = FakeResponse('[{"number":19,"state":"open","labels":[],"created_at":"2026-07-28T00:00:00Z"}]')
+
+ # When: it lists open issues.
+ with patch(
+ "scripts.issue_triage.urllib.request.urlopen",
+ side_effect=[first_page, second_page, FakeResponse("[]")],
+ ):
+ issues = api.list_open_issues()
+
+ # Then: both pages are included for triage filtering.
+ self.assertEqual(tuple(issue.number for issue in issues), (18, 19))
+
+ def test_isolates_marker_lookup_failure(self) -> None:
+ # Given: a GitHub request fails for one candidate.
+ api = MarkerFailingApi({13: Issue(13, True, False, ())})
+
+ # When: triage processes the issue.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: it reports the issue as failed without mutation.
+ self.assertEqual(result.failed, (13,))
+ self.assertEqual(api.operations, [])
+
+ def test_scheduled_rollout_excludes_historical_issue(self) -> None:
+ # Given: an unlabeled issue created before the rollout cutoff.
+ api = FakeIssueApi({14: Issue(14, True, False, (), "2026-07-27T00:00:00Z")})
+
+ # When: the scheduled mode uses the rollout cutoff.
+ result = run_triage(api, TriageOptions(dry_run=False, rollout_after="2026-07-28T00:00:00Z"))
+
+ # Then: the historical issue is not changed until a maintainer backfill.
+ self.assertEqual(result.skipped, (14,))
+ self.assertEqual(api.operations, [])
+
+ def test_partial_write_is_failed_and_recoverable(self) -> None:
+ # Given: adding the queue label succeeds but creating the notice fails.
+ api = NoticeFailingApi({15: Issue(15, True, False, ())})
+
+ # When: triage attempts the candidate.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: it reports failure instead of a successful notice.
+ self.assertEqual(result.noticed, ())
+ self.assertEqual(result.failed, (15,))
+ self.assertEqual(api.operations, [(f"label:{QUEUE_LABEL}", 15), ("comment", 15)])
+
+ def test_missing_queue_label_fails_before_issue_mutation(self) -> None:
+ # Given: the required queue label has not been provisioned.
+ api = MissingQueueLabelApi({16: Issue(16, True, False, ())})
+
+ # When: triage starts.
+ with self.assertRaises(MissingQueueLabelError):
+ run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: the candidate remains untouched.
+ self.assertEqual(api.operations, [])
+
+ def test_non_transient_github_errors_are_not_retried(self) -> None:
+ # Given: GitHub rejects the request with an authorization or validation error.
+ for status in (401, 403, 422):
+ with self.subTest(status=status):
+ error = urllib.error.HTTPError("https://api.github.test", status, "failure", None, None)
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+
+ # When: the helper validates the queue label.
+ with patch("scripts.issue_triage.urllib.request.urlopen", side_effect=error) as request:
+ with self.assertRaises(urllib.error.HTTPError):
+ api.queue_label_exists()
+ error.close()
+
+ # Then: it makes one request and leaves retry to no non-transient path.
+ self.assertEqual(request.call_count, 1)
+
+ def test_rate_limit_is_retried_before_success(self) -> None:
+ # Given: GitHub returns a transient rate limit once, then the issue response.
+ rate_limit = urllib.error.HTTPError("https://api.github.test", 429, "rate limit", None, None)
+ response = FakeResponse('{"number":17,"state":"open","labels":[],"created_at":"2026-07-28T00:00:00Z"}')
+ api = GitHubIssueApi("img2threejs/img2threejs", "token")
+
+ # When: the helper fetches the issue.
+ with patch("scripts.issue_triage.urllib.request.urlopen", side_effect=[rate_limit, response]):
+ with patch("scripts.issue_triage.time.sleep") as sleep:
+ issue = api.get_issue(17)
+ rate_limit.close()
+
+ # Then: it retries and returns the parsed issue.
+ self.assertEqual(issue, Issue(17, True, False, (), "2026-07-28T00:00:00Z"))
+ sleep.assert_called_once_with(1)
+
+ def test_empty_issue_list_has_an_empty_summary(self) -> None:
+ # Given: no open issues returned by GitHub.
+ api = FakeIssueApi({})
+
+ # When: triage runs.
+ result = run_triage(api, TriageOptions(dry_run=False))
+
+ # Then: every result bucket is empty.
+ self.assertEqual(result.noticed, ())
+ self.assertEqual(result.reconciled, ())
+ self.assertEqual(result.would_notice, ())
+ self.assertEqual(result.skipped, ())
+ self.assertEqual(result.failed, ())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/issue_triage.py b/scripts/issue_triage.py
new file mode 100644
index 0000000..020a7a1
--- /dev/null
+++ b/scripts/issue_triage.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python3
+"""Queue newly opened, unlabeled GitHub issues for maintainer triage."""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import asdict, dataclass
+from typing import Final, Protocol
+
+
+API_ROOT: Final = "https://api.github.com"
+NOTICE_MARKER: Final = "<!-- img2threejs-triage-notice:v1 -->"
+QUEUE_LABEL: Final = "triage: needs-review"
+TRIAGE_BOT_LOGIN: Final = "github-actions[bot]"
+NOTICE: Final = (
+ f"{NOTICE_MARKER}\n"
+ "Thanks for opening this issue. It is in the maintainer triage queue. "
+ "Please add any missing reproduction steps, expected outcome, or scope here; "
+ "a label is not a promise of implementation."
+)
+TRANSIENT_STATUSES: Final = frozenset({429, 500, 502, 503, 504})
+
+
+@dataclass(frozen=True, slots=True)
+class Issue:
+ number: int
+ is_open: bool
+ is_pull_request: bool
+ labels: tuple[str, ...]
+ created_at: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class TriageOptions:
+ dry_run: bool
+ rollout_after: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class TriageResult:
+ noticed: tuple[int, ...]
+ reconciled: tuple[int, ...]
+ would_notice: tuple[int, ...]
+ skipped: tuple[int, ...]
+ failed: tuple[int, ...]
+
+
+class IssueApi(Protocol):
+ def queue_label_exists(self) -> bool: ...
+
+ def list_open_issues(self) -> tuple[Issue, ...]: ...
+
+ def get_issue(self, number: int) -> Issue | None: ...
+
+ def has_notice_marker(self, number: int) -> bool: ...
+
+ def add_label(self, number: int, label: str) -> None: ...
+
+ def create_notice(self, number: int, notice: str) -> None: ...
+
+
+class MissingQueueLabelError(RuntimeError):
+ def __init__(self) -> None:
+ super().__init__(f"Required label is missing: {QUEUE_LABEL}")
+
+
+class GitHubIssueApi:
+ def __init__(self, repository: str, token: str) -> None:
+ self._repository = repository
+ self._token = token
+
+ def list_open_issues(self) -> tuple[Issue, ...]:
+ issues: list[Issue] = []
+ page = 1
+ while True:
+ payload = self._request(f"/repos/{self._repository}/issues?state=open&per_page=100&page={page}")
+ if not payload:
+ return tuple(issues)
+ issues.extend(parse_issue(item) for item in payload)
+ page += 1
+
+ def queue_label_exists(self) -> bool:
+ label = urllib.parse.quote(QUEUE_LABEL, safe="")
+ try:
+ self._request(f"/repos/{self._repository}/labels/{label}")
+ except urllib.error.HTTPError as error:
+ if error.code == 404:
+ return False
+ raise
+ return True
+
+ def get_issue(self, number: int) -> Issue | None:
+ try:
+ return parse_issue(self._request(f"/repos/{self._repository}/issues/{number}"))
+ except urllib.error.HTTPError as error:
+ if error.code == 404:
+ return None
+ raise
+
+ def has_notice_marker(self, number: int) -> bool:
+ page = 1
+ while True:
+ comments = self._request(f"/repos/{self._repository}/issues/{number}/comments?per_page=100&page={page}")
+ if any(
+ NOTICE_MARKER in comment.get("body", "")
+ and comment.get("user", {}).get("login") == TRIAGE_BOT_LOGIN
+ and comment.get("user", {}).get("type") == "Bot"
+ for comment in comments
+ ):
+ return True
+ if not comments:
+ return False
+ page += 1
+
+ def add_label(self, number: int, label: str) -> None:
+ self._request(f"/repos/{self._repository}/issues/{number}/labels", {"labels": [label]})
+
+ def create_notice(self, number: int, notice: str) -> None:
+ path = f"/repos/{self._repository}/issues/{number}/comments"
+ try:
+ self._request(path, {"body": notice}, retry=False)
+ except (urllib.error.HTTPError, urllib.error.URLError) as error:
+ if isinstance(error, urllib.error.HTTPError) and error.code not in TRANSIENT_STATUSES:
+ raise
+ if self.has_notice_marker(number):
+ return
+ self._request(path, {"body": notice}, retry=False)
+
+ def _request(
+ self,
+ path: str,
+ payload: dict[str, list[str]] | dict[str, str] | None = None,
+ retry: bool = True,
+ ):
+ data = None if payload is None else json.dumps(payload).encode("utf-8")
+ request = urllib.request.Request(
+ f"{API_ROOT}{path}",
+ data=data,
+ headers={
+ "Accept": "application/vnd.github+json",
+ "Authorization": f"Bearer {self._token}",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ )
+ for attempt in range(3 if retry else 1):
+ try:
+ with urllib.request.urlopen(request, timeout=30) as response: # noqa: S310
+ return json.loads(response.read().decode("utf-8"))
+ except urllib.error.HTTPError as error:
+ if error.code not in TRANSIENT_STATUSES or attempt == (2 if retry else 0):
+ raise
+ except urllib.error.URLError:
+ if attempt == (2 if retry else 0):
+ raise
+ time.sleep(2**attempt)
+ raise AssertionError("unreachable retry loop")
+
+
+def parse_issue(payload) -> Issue:
+ return Issue(
+ number=payload["number"],
+ is_open=payload["state"] == "open",
+ is_pull_request="pull_request" in payload,
+ labels=tuple(label["name"] for label in payload["labels"]),
+ created_at=payload["created_at"],
+ )
+
+
+def is_rollout_candidate(issue: Issue, options: TriageOptions) -> bool:
+ return options.rollout_after is None or issue.created_at >= options.rollout_after
+
+
+def run_triage(api: IssueApi, options: TriageOptions) -> TriageResult:
+ noticed: list[int] = []
+ reconciled: list[int] = []
+ would_notice: list[int] = []
+ skipped: list[int] = []
+ failed: list[int] = []
+ if not api.queue_label_exists():
+ raise MissingQueueLabelError
+ for listed in api.list_open_issues():
+ if listed.is_pull_request or not listed.is_open:
+ skipped.append(listed.number)
+ continue
+ try:
+ current = api.get_issue(listed.number)
+ if current is None or current.is_pull_request or not current.is_open:
+ skipped.append(listed.number)
+ continue
+ is_recovery = current.labels == (QUEUE_LABEL,)
+ if not is_recovery and (current.labels or not is_rollout_candidate(current, options)):
+ skipped.append(current.number)
+ continue
+ if api.has_notice_marker(current.number):
+ skipped.append(current.number)
+ continue
+ if options.dry_run:
+ would_notice.append(current.number)
+ continue
+ if is_recovery:
+ api.create_notice(current.number, NOTICE)
+ reconciled.append(current.number)
+ else:
+ api.add_label(current.number, QUEUE_LABEL)
+ api.create_notice(current.number, NOTICE)
+ noticed.append(current.number)
+ except (urllib.error.HTTPError, urllib.error.URLError):
+ failed.append(listed.number)
+ return TriageResult(tuple(noticed), tuple(reconciled), tuple(would_notice), tuple(skipped), tuple(failed))
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY"))
+ parser.add_argument("--token", default=os.environ.get("GITHUB_TOKEN"))
+ parser.add_argument("--dry-run", action="store_true")
+ parser.add_argument("--rollout-after")
+ arguments = parser.parse_args()
+ if not arguments.repository or not arguments.token:
+ parser.error("--repository and --token (or GITHUB_REPOSITORY and GITHUB_TOKEN) are required")
+ result = run_triage(
+ GitHubIssueApi(arguments.repository, arguments.token),
+ TriageOptions(dry_run=arguments.dry_run, rollout_after=arguments.rollout_after),
+ )
+ print(json.dumps(asdict(result), sort_keys=True))
+ return 1 if result.failed else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())