diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md index 698955803..8af97ac46 100644 --- a/.agents/skills/code-review/SKILL.md +++ b/.agents/skills/code-review/SKILL.md @@ -13,11 +13,12 @@ All reviews are evaluated against the engineering conventions defined in [AGENTS ## Review Workflow -1. **Classify Changed Files & Scope**: - Group changed files according to the 3-tier architectural hierarchy and evaluate PR scoping: - - **Priority 1: Public Trait APIs & Consumer Contracts** (`roborock/devices/traits/`, `roborock/data/containers.py`) - - **Priority 2: Data Lifecycle & State Management** (trait state, callbacks, `RoborockDevice.close()`, map/render pipelines) - - **Priority 3: Wire Protocols, Codecs & Cryptography** (`roborock/protocols/`, `roborock/devices/transport/`, `roborock/devices/rpc/`) +1. **Fetch PR Context & Classify Scope**: + - **Fetch Metadata & Prior Thread History**: Fetch PR metadata, diff, and all prior reviews and inline threads (`gh pr view -R Python-roborock/python-roborock --json ...` and `gh api repos/Python-roborock/python-roborock/pulls//comments --paginate`). Note that `gh pr checks ` exits non-zero when a first-time contributor's workflow awaits approval—treat that as pending CI approval rather than a failure. When cleaning up or re-reviewing an existing PR, also inspect GraphQL `reviewThreads` to verify and resolve addressed threads (including Copilot comments). + - **Classify Changed Files**: Group changed files according to the 3-tier architectural hierarchy and evaluate PR scoping: + - **Priority 1: Public Trait APIs & Consumer Contracts** (`roborock/devices/traits/`, `roborock/data/containers.py`) + - **Priority 2: Data Lifecycle & State Management** (trait state, callbacks, `RoborockDevice.close()`, map/render pipelines) + - **Priority 3: Wire Protocols, Codecs & Cryptography** (`roborock/protocols/`, `roborock/devices/transport/`, `roborock/devices/rpc/`) - **PR Scoping**: Flag PRs that mix unrelated subsystems or combine large protocol/parser additions with trait consumption when they should be split into focused PRs. - **Automated Conformance**: Structural invariants (`RoborockBase` inheritance, `RoborockEnum` fallback members, `RoborockException` rooting, and trait boundary types) are enforced in `tests/conformance/`. Flag any unjustified allowlist exemptions added to `tests/conformance/` and focus deeper review energy on semantic, lifecycle, and design issues. @@ -47,22 +48,25 @@ All reviews are evaluated against the engineering conventions defined in [AGENTS 5. **Evaluate Tests & Fixtures**: - **Test Mirroring & Colocation**: Are tests colocated in the matching mirror path under `tests/` for the module being tested (e.g., tests for `roborock/devices/traits/v1/status.py` in `tests/devices/traits/v1/test_status.py`; new modules have corresponding new test suites under the mirror directory)? - **No One-Off Bugfix Test Files**: Flag any fragmented single-bug or single-PR test files (e.g., `tests/test_battery_low_voltage_fix.py`). Tests must be integrated into the module's corresponding test suite. - - Are tests using `fake_channel` and `@pytest.mark.parametrize` rather than hand-rolled mocks or duplicate methods? + - Are tests reusing shared module fixtures (`mock_rpc_channel`, `fake_channel`, `device_fixture`), `roborock.testing` simulators (`V1VacuumSimulator`, `Q10VacuumSimulator`, `DyadSimulator`, `ZeoSimulator`), and `@pytest.mark.parametrize` rather than hand-rolled inline command-dict fakes or duplicate test methods? - Do assertions verify public behavior rather than private `_state` variables? 6. **Adversarial Self-Check on Candidate Findings**: Before presenting or posting any review comment, subject every candidate finding and suggested diff to hostile adversarial scrutiny and discard any that fail: - **Baseline & History Check**: Trace concrete inputs across `upstream/main`, the PR, and your proposed fix (inspecting `git log` / blame when existing test or helper intent is non-obvious). Discard suggestions that silently regress `main` behavior on valid inputs or introduce magic-number/boundary duplication. - - **Verify Rationale Against Peer Cases**: Check sibling functions and enum codes in the same module to confirm your stated invariant actually holds across the codebase rather than inventing a stricter rule for the touched lines alone. - - **Independent Check of Prior Reviews**: When comparing competing PRs or prior review comments (human or AI), evaluate those claims with the same adversarial skepticism instead of carrying them forward uncritically. + - **Verify Rationale Against Peer Cases**: Check sibling functions, traits, and enum codes in the same module to confirm your stated invariant actually holds across the codebase rather than inventing a stricter rule for the touched lines alone. + - **Prior Review Continuity & Independent Check**: On re-reviews, verify candidate findings against earlier maintainer comments on the PR—never move the goalposts by flagging a pattern the maintainer previously asked the author to adopt (unless explicitly noting why we are reconsidering earlier guidance), and check whether prior maintainer questions were answered. Conversely, evaluate third-party or competing-PR claims with adversarial skepticism instead of carrying them forward uncritically. - **Drop Low-Value Nits & Allow Zero-Defect Approvals**: Drop trivial docstring or comment wording nits (especially in tests) unless factually harmful, and verify any suggested replacement text accurately reflects what the code/test asserts. If no findings survive adversarial scrutiny, report that the PR is clean and ready to approve rather than manufacturing filler comments. -7. **Format Review Output**: - Structure review comments with clear rationale and actionable code recommendations: - - **Priority Level & File Reference** - - **Issue / Anti-Pattern Identified** - - **Grounded Rationale** (citing protocol resilience, consumer stability, or maintainability) - - **Concrete Before / After Diff or Suggested Fix** - Keep feedback high-signal: focus on architectural violations, state/concurrency bugs, protocol safety, and test gaps; avoid nitpicking formatting or style already enforced by Ruff and Mypy. - - **Interactive / Summary Reviews**: Group findings by Priority Layer (1 → 3) with file references, the anti-pattern identified, grounded rationale (citing protocol resilience, consumer stability, or maintainability), and a concrete before/after diff or suggested fix. - - **Inline PR Review Comments**: State the issue, grounded rationale (citing `AGENTS.md` conventions), and suggested fix concisely right on the affected lines. +7. **Format Review Output & Calibrate Delivery**: + - **Lead with Verdict & Clickable Link**: Always open interactive and subagent review reports with a clickable PR link (`[#N](https://github.com/Python-roborock/python-roborock/pull/N)`) and an explicit 1-line bottom-line verdict (**Approve / LGTM — no changes needed**, **Comment with non-blocking question/simplification**, or **Request Changes**). + - **Structure Actionable Findings**: + - **Priority Level & File Reference** + - **Issue / Anti-Pattern Identified** + - **Grounded Rationale** (citing protocol resilience, consumer stability, or maintainability) + - **Concrete Before / After Diff or Suggested Fix** + Keep feedback high-signal: focus on architectural violations, state/concurrency bugs, protocol safety, and test gaps; avoid nitpicking formatting or style already enforced by Ruff and Mypy. + - **Calibrate GitHub Comment Style**: + - **Simplifications & Design Questions**: Frame optional simplifications as collaborative questions with a proposed `diff` (`COMMENT` review) rather than rigid blockers. + - **Fundamental Design Pushback**: When a PR addresses a real problem with an over-complicated design, prefer **one high-level review comment** acknowledging the real problem, listing the core failure modes, and sketching a simpler alternative instead of leaving inline nits on code that shouldn't stay. + - **Unanswered Prior Questions**: Restate unanswered questions from earlier reviews concisely in 2–3 sentences focused on the core consumer/design question rather than pasting long verbatim self-quotes. diff --git a/.agents/skills/pr-triage/SKILL.md b/.agents/skills/pr-triage/SKILL.md index 0d154d898..b9758bc4c 100644 --- a/.agents/skills/pr-triage/SKILL.md +++ b/.agents/skills/pr-triage/SKILL.md @@ -1,12 +1,12 @@ --- name: pr-triage description: >- - Assess open pull requests and review queue state in python-roborock, optionally syncing the local workspace with upstream/main. Use when asked what needs to be reviewed, to triage open PRs, or to sync and check the review backlog. + Assess open pull requests, incoming issues, and review queue state in python-roborock, optionally syncing the local workspace with upstream/main. Use when asked what needs to be reviewed, to triage open PRs or incoming issues, or to sync and check the review backlog. --- -# PR Triage & Review Queue Skill +# PR & Issue Triage Skill -Use this skill when assessing open pull requests, checking which PRs need initial review or re-review, or syncing the workspace before starting a review session. +Use this skill when assessing open pull requests, triaging incoming issues, checking which PRs need initial review or re-review, or syncing the workspace before starting a review session. Once the user selects a specific PR to review, switch to the [Code Review Skill](../code-review/SKILL.md). @@ -14,57 +14,35 @@ Once the user selects a specific PR to review, switch to the [Code Review Skill] ## Workflow -1. **Optional Workspace Sync**: - If the user asks to sync (e.g., "sync and check reviews") or the workspace is a clean review branch behind `upstream/main`: +1. **Workspace Fetch & Optional Sync**: + Always `git fetch upstream main` so local context reflects current `upstream/main`. If the user asks to sync (e.g., "sync and check reviews") or the workspace is a clean review branch behind `upstream/main`: - Verify clean working tree (`git status --short`). Do **not** fast-forward or rebase if uncommitted local changes exist unless asked. - Fetch remotes (`git fetch --all --prune`). - Fast-forward the local tracking branch to `upstream/main` (or `origin/main` if `upstream` is absent): `git merge --ff-only upstream/main`. -2. **Query Open PR & Review Metadata**: - Identify the current GitHub user and fetch open PR state in a single `gh` pass so no per-PR polling is needed: +2. **Run the Single-Pass Triage Script**: + Execute [`scripts/triage.py`](scripts/triage.py) with `prs`, `issues`, or `all` depending on what the user asked to triage. Each subcommand runs a single GraphQL call (up to 100 open PRs / 50 open issues) without hitting `gh pr list` node-count limits: ```bash - REVIEWER=$(gh api user --jq .login) - gh pr list --repo Python-roborock/python-roborock --state open --limit 30 \ - --json number,title,author,isDraft,createdAt,updatedAt,additions,deletions,mergeable,reviewDecision,headRefOid,reviews,commits,comments \ - | jq --arg me "$REVIEWER" ' - sort_by(.number) | reverse | .[] | .author.login as $pr_author | { - number, - title, - author: $pr_author, - isDraft, - mergeable, - size: "+\(.additions)/-\(.deletions)", - reviewDecision, - headRefOid, - lastCommit: (.commits | last | .committedDate), - myLastReview: ([.reviews[] | select(.author.login == $me)] | last | {state, submittedAt, commitOid: .commit.oid}), - otherLastReview: ([.reviews[] | select(.author.login != $me and .author.login != $pr_author and .author.login != "copilot-pull-request-reviewer")] | last | {author: .author.login, state, submittedAt}), - lastAuthorReplyAt: ( - [ - (.comments[] | select(.author.login == $pr_author) | .createdAt), - (.reviews[] | select(.author.login == $pr_author) | .submittedAt) - ] | max - ) - }' + # Triage open PRs only (review buckets + suggested 5-PR batch) + python3 .agents/skills/pr-triage/scripts/triage.py prs + + # Triage incoming open issues only (still cross-linking open PRs without dumping the PR queue) + python3 .agents/skills/pr-triage/scripts/triage.py issues + + # Triage both open PRs and open issues in a single pass + python3 .agents/skills/pr-triage/scripts/triage.py all ``` - *(Note: GitHub's GraphQL `reviews` array includes `COMMENTED` entries whenever an author replies in an inline review thread, so combining `.comments[]` and `.reviews[]` filtered to `$pr_author` captures both top-level PR comments and inline review-thread replies without extra API calls.)* + *(Pass `--json` if structured output is needed for custom filtering.)* -3. **Classify PRs into Actionable Buckets**: - Group open PRs in priority order for the reviewer (`$REVIEWER`): - - **1. New PRs Awaiting Initial Review**: - Non-draft PRs not authored by `$REVIEWER` where `myLastReview.submittedAt == null`. Flag competing/overlapping PRs targeting the same module/issue and note if another maintainer already commented/approved. - - **2. Re-reviews Needed (Updated Since Last Review)**: - Non-draft PRs not authored by `$REVIEWER` where `myLastReview.submittedAt != null` AND (`headRefOid != myLastReview.commitOid` OR `(lastAuthorReplyAt != null and lastAuthorReplyAt > myLastReview.submittedAt)`). Comparing `headRefOid != myLastReview.commitOid` catches amended, rebased, or cherry-picked commits whose `committedDate` precedes `myLastReview.submittedAt`. - - **3. Approved & Ready to Merge / Own PR Updates**: - - Non-draft PRs (authored by `$REVIEWER` or contributors) that are `APPROVED` (`reviewDecision == "APPROVED"`), `MERGEABLE`, and have no unreviewed commits since approval (`headRefOid == myLastReview.commitOid` or authored by `$REVIEWER`). - - Non-draft PRs authored by `$REVIEWER` with new review feedback or merge conflicts requiring action. - - **4. Waiting on Author / Drafts (Compact Summary)**: - - Non-draft PRs with `CHANGES_REQUESTED` or `COMMENTED` where `headRefOid == myLastReview.commitOid` and no new author replies (`lastAuthorReplyAt <= myLastReview.submittedAt`) have arrived. - - Draft PRs (`isDraft == true`), summarized compactly on 1–2 lines unless a draft has notable recent maintainer discussion. - - Conflicting (`mergeable == "CONFLICTING"`) or stale backlog items. +3. **Verify Actionable Buckets**: + The script classifies open PRs for the authenticated reviewer into four priority buckets: + - **1. New PRs Awaiting Initial Review**: Non-draft contributor PRs you have not yet reviewed, annotated with file overlaps (`overlaps #...`), referenced issues, CI state (`SUCCESS`, `FAILURE`, `PENDING_APPROVAL`), and other maintainer reviews. + - **2. Re-reviews Needed**: Non-draft PRs where `headRefOid != myLastReview.commitOid` (catches amended/rebased commits) or the author replied after `myLastReview.submittedAt`. + - **3. Ready to Merge / Own PRs**: Approved, mergeable PRs with no unreviewed commits, plus your own open PRs (highlighting merge conflicts or unresolved Copilot/review threads). + - **4. Waiting on Author & Drafts**: Compact summary of PRs awaiting contributor changes and draft PRs. 4. **Present Concise Triage Report**: - Report sync status in one line if a sync was performed (commit hash + any new release tags). - - List actionable PRs (`#number`, title, `@author`, `+additions/-deletions`, and why it needs attention—e.g., *opened Oct 31* or *updated Oct 22 after your Oct 17 review*). - - Keep "Waiting on Author / Drafts" brief so actionable reviews stand out. - - Ask which PR the user wants to review first. + - **Always preserve clickable Markdown links** (`[#number](url)`) for every PR and issue mentioned. + - Highlight high-signal relationships (e.g., competing PRs touching the same module, stacked PR series from the same author, or issues already addressed by an open PR). + - Conclude with the **Suggested Next Review Batch (3–5 non-overlapping PRs)** ordered from quick green-CI wins to high-impact bugfixes, noting any PRs awaiting first-time contributor CI approval. diff --git a/.agents/skills/pr-triage/scripts/triage.py b/.agents/skills/pr-triage/scripts/triage.py new file mode 100755 index 000000000..cbb3f4be6 --- /dev/null +++ b/.agents/skills/pr-triage/scripts/triage.py @@ -0,0 +1,594 @@ +#!/usr/bin/env python3 +"""Fetch and classify open PRs and/or open issues for python-roborock triage.""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from dataclasses import asdict, dataclass +from typing import Any + +DEFAULT_REPO = "Python-roborock/python-roborock" +ISSUE_REF_RE = re.compile(r"(?:^|[\s(])#(\d+)\b") + +GRAPHQL_QUERY = """ +query( + $owner: String! + $name: String! + $prLimit: Int! + $includePrDetails: Boolean! + $includeIssues: Boolean! + $issueLimit: Int! +) { + viewer { + login + } + repository(owner: $owner, name: $name) { + pullRequests(first: $prLimit, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) { + nodes { + number + title + url + body + isDraft + closingIssuesReferences(first: 10) { + nodes { + number + } + } + mergeable @include(if: $includePrDetails) + reviewDecision @include(if: $includePrDetails) + createdAt @include(if: $includePrDetails) + updatedAt @include(if: $includePrDetails) + additions @include(if: $includePrDetails) + deletions @include(if: $includePrDetails) + headRefOid @include(if: $includePrDetails) + author @include(if: $includePrDetails) { + login + } + files(first: 30) @include(if: $includePrDetails) { + nodes { + path + } + } + reviewThreads(first: 50) @include(if: $includePrDetails) { + nodes { + isResolved + } + } + commits(last: 1) @include(if: $includePrDetails) { + nodes { + commit { + committedDate + statusCheckRollup { + state + } + } + } + } + reviews(last: 40) @include(if: $includePrDetails) { + nodes { + state + submittedAt + author { + login + } + commit { + oid + } + } + } + comments(last: 30) @include(if: $includePrDetails) { + nodes { + createdAt + author { + login + } + } + } + } + } + issues( + first: $issueLimit + states: OPEN + orderBy: {field: CREATED_AT, direction: DESC} + ) @include(if: $includeIssues) { + nodes { + number + title + url + createdAt + updatedAt + author { + login + } + labels(first: 10) { + nodes { + name + } + } + comments { + totalCount + } + } + } + } +} +""" + + +@dataclass(frozen=True) +class ReviewSummary: + """Summary of the latest review from a reviewer.""" + + author: str + state: str + submitted_at: str + commit_oid: str | None + + +@dataclass +class PullRequestItem: + """Normalized pull request metadata for triage classification.""" + + number: int + title: str + url: str + author: str + is_draft: bool + mergeable: str + review_decision: str | None + created_at: str + updated_at: str + last_commit_at: str | None + size: str + additions: int + deletions: int + head_oid: str + ci_state: str + unresolved_threads: int + files: list[str] + linked_issues: list[int] + overlapping_prs: list[int] + my_last_review: ReviewSummary | None + other_last_review: ReviewSummary | None + last_author_reply_at: str | None + reason: str = "" + + +@dataclass(frozen=True) +class IssueItem: + """Normalized open issue metadata for triage.""" + + number: int + title: str + url: str + author: str + created_at: str + labels: list[str] + comment_count: int + linked_prs: list[int] + + +def _login(node: dict[str, Any] | None) -> str: + if not node: + return "ghost" + author = node.get("author") + if isinstance(author, dict) and isinstance(author.get("login"), str): + return author["login"] + return "ghost" + + +def _extract_issue_refs(pr_node: dict[str, Any], pr_numbers: set[int]) -> list[int]: + refs: set[int] = set() + closing = pr_node.get("closingIssuesReferences", {}).get("nodes") or [] + for item in closing: + if isinstance(item, dict) and isinstance(item.get("number"), int): + refs.add(item["number"]) + for text in (pr_node.get("title") or "", pr_node.get("body") or ""): + for match in ISSUE_REF_RE.finditer(text): + num = int(match.group(1)) + if num not in pr_numbers: + refs.add(num) + return sorted(refs) + + +def _parse_pr(node: dict[str, Any], reviewer: str, pr_numbers: set[int]) -> PullRequestItem: + author = _login(node) + commits = node.get("commits", {}).get("nodes") or [] + last_commit = commits[-1].get("commit", {}) if commits else {} + rollup = last_commit.get("statusCheckRollup") + ci_state = rollup.get("state", "UNKNOWN") if isinstance(rollup, dict) else "PENDING_APPROVAL" + + reviews_raw = [ + r for r in (node.get("reviews", {}).get("nodes") or []) if isinstance(r, dict) and r.get("state") != "PENDING" + ] + my_reviews = [r for r in reviews_raw if _login(r) == reviewer] + other_reviews = [ + r for r in reviews_raw if _login(r) not in {reviewer, author, "copilot-pull-request-reviewer", "github-actions"} + ] + + my_last: ReviewSummary | None = None + if my_reviews: + last_r = my_reviews[-1] + commit_obj = last_r.get("commit") + my_last = ReviewSummary( + author=reviewer, + state=last_r.get("state") or "", + submitted_at=last_r.get("submittedAt") or "", + commit_oid=commit_obj.get("oid") if isinstance(commit_obj, dict) else None, + ) + + other_last: ReviewSummary | None = None + if other_reviews: + last_o = other_reviews[-1] + commit_obj = last_o.get("commit") + other_last = ReviewSummary( + author=_login(last_o), + state=last_o.get("state") or "", + submitted_at=last_o.get("submittedAt") or "", + commit_oid=commit_obj.get("oid") if isinstance(commit_obj, dict) else None, + ) + + comments_raw = [c for c in (node.get("comments", {}).get("nodes") or []) if isinstance(c, dict)] + author_timestamps = [ + ts + for ts in ( + [c.get("createdAt") for c in comments_raw if _login(c) == author] + + [r.get("submittedAt") for r in reviews_raw if _login(r) == author] + ) + if isinstance(ts, str) + ] + last_author_reply = max(author_timestamps) if author_timestamps else None + + threads = [t for t in (node.get("reviewThreads", {}).get("nodes") or []) if isinstance(t, dict)] + unresolved = sum(1 for t in threads if not t.get("isResolved", False)) + files = [ + f["path"] + for f in (node.get("files", {}).get("nodes") or []) + if isinstance(f, dict) and isinstance(f.get("path"), str) + ] + additions = int(node.get("additions") or 0) + deletions = int(node.get("deletions") or 0) + + return PullRequestItem( + number=int(node["number"]), + title=str(node.get("title") or ""), + url=str(node.get("url") or ""), + author=author, + is_draft=bool(node.get("isDraft")), + mergeable=str(node.get("mergeable") or "UNKNOWN"), + review_decision=node.get("reviewDecision"), + created_at=str(node.get("createdAt") or ""), + updated_at=str(node.get("updatedAt") or ""), + last_commit_at=last_commit.get("committedDate"), + size=f"+{additions}/-{deletions}", + additions=additions, + deletions=deletions, + head_oid=str(node.get("headRefOid") or ""), + ci_state=ci_state, + unresolved_threads=unresolved, + files=files, + linked_issues=_extract_issue_refs(node, pr_numbers), + overlapping_prs=[], + my_last_review=my_last, + other_last_review=other_last, + last_author_reply_at=last_author_reply, + ) + + +def _populate_overlaps(prs: list[PullRequestItem]) -> None: + active = [p for p in prs if not p.is_draft] + file_sets = {p.number: set(p.files) for p in active} + for pr in active: + my_files = file_sets[pr.number] + if not my_files: + continue + pr.overlapping_prs = sorted( + other.number for other in active if other.number != pr.number and (my_files & file_sets[other.number]) + ) + + +def classify_prs(prs: list[PullRequestItem], reviewer: str) -> dict[str, list[PullRequestItem]]: + """Classify open PRs into the four maintainer triage buckets.""" + buckets: dict[str, list[PullRequestItem]] = { + "new_reviews": [], + "re_reviews": [], + "ready_or_own": [], + "waiting_or_draft": [], + } + for pr in sorted(prs, key=lambda p: p.number, reverse=True): + if pr.is_draft: + pr.reason = "draft" + buckets["waiting_or_draft"].append(pr) + continue + + if pr.author == reviewer: + notes = [f"own PR ({pr.mergeable}, CI: {pr.ci_state})"] + if pr.review_decision: + notes.append(pr.review_decision) + if pr.unresolved_threads: + notes.append(f"{pr.unresolved_threads} unresolved thread(s)") + pr.reason = ", ".join(notes) + buckets["ready_or_own"].append(pr) + continue + + my_rev = pr.my_last_review + if ( + pr.review_decision == "APPROVED" + and pr.mergeable == "MERGEABLE" + and (my_rev is None or my_rev.commit_oid == pr.head_oid) + ): + pr.reason = f"approved & mergeable (CI: {pr.ci_state})" + buckets["ready_or_own"].append(pr) + continue + + if my_rev is None: + notes = [f"opened {pr.created_at[:10]}"] + if pr.other_last_review: + notes.append(f"@{pr.other_last_review.author}: {pr.other_last_review.state}") + pr.reason = "; ".join(notes) + buckets["new_reviews"].append(pr) + continue + + has_new_commits = my_rev.commit_oid != pr.head_oid + has_author_reply = pr.last_author_reply_at is not None and pr.last_author_reply_at > my_rev.submitted_at + if has_new_commits or has_author_reply: + triggers: list[str] = [] + if has_new_commits: + triggers.append("new commits") + if has_author_reply and pr.last_author_reply_at: + triggers.append(f"author reply {pr.last_author_reply_at[:10]}") + pr.reason = f"{' + '.join(triggers)} since {my_rev.state} ({my_rev.submitted_at[:10]})" + buckets["re_reviews"].append(pr) + else: + pr.reason = f"waiting on author after {my_rev.state} ({my_rev.submitted_at[:10]})" + buckets["waiting_or_draft"].append(pr) + + return buckets + + +def recommend_batch(buckets: dict[str, list[PullRequestItem]], max_count: int = 5) -> list[PullRequestItem]: + """Select up to max_count non-overlapping actionable PRs ordered by quick wins.""" + candidates = [ + p + for p in (buckets["re_reviews"] + buckets["new_reviews"]) + if p.mergeable != "CONFLICTING" and p.ci_state not in {"FAILURE", "ERROR"} + ] + candidates.sort( + key=lambda p: ( + 0 if p in buckets["re_reviews"] else 1, + 0 if p.ci_state == "SUCCESS" else 1, + p.additions + p.deletions, + -p.number, + ) + ) + chosen: list[PullRequestItem] = [] + claimed_files: set[str] = set() + for pr in candidates: + pr_files = set(pr.files) + if pr_files & claimed_files: + continue + chosen.append(pr) + claimed_files |= pr_files + if len(chosen) >= max_count: + break + return chosen + + +def _format_pr_line(pr: PullRequestItem) -> str: + extras = [f"CI: `{pr.ci_state}`"] + if pr.mergeable == "CONFLICTING": + extras.append("`CONFLICTING`") + if pr.unresolved_threads: + extras.append(f"{pr.unresolved_threads} unresolved") + if pr.linked_issues: + refs = ", ".join(f"#{n}" for n in pr.linked_issues[:3]) + extras.append(f"refs {refs}") + if pr.overlapping_prs: + overlaps = ", ".join(f"#{n}" for n in pr.overlapping_prs[:3]) + suffix = f" +{len(pr.overlapping_prs) - 3}" if len(pr.overlapping_prs) > 3 else "" + extras.append(f"overlaps {overlaps}{suffix}") + meta = " | ".join(extras) + return f"- [#{pr.number}]({pr.url}) — `{pr.title}` (`@{pr.author}`, `{pr.size}`, {meta}) — {pr.reason}" + + +def _render_prs_markdown( + reviewer: str, + prs: list[PullRequestItem], + buckets: dict[str, list[PullRequestItem]], +) -> list[str]: + lines = [f"## PR Triage Queue (`@{reviewer}` — {len(prs)} open PRs)", ""] + + sections = [ + ("1. New PRs Awaiting Initial Review", buckets["new_reviews"]), + ("2. Re-reviews Needed (Updated Since Your Last Review)", buckets["re_reviews"]), + ("3. Ready to Merge / Own PRs", buckets["ready_or_own"]), + ] + for heading, items in sections: + lines.append(f"### {heading} ({len(items)})") + if items: + lines.extend(_format_pr_line(pr) for pr in items) + else: + lines.append("- None") + lines.append("") + + waiting = [p for p in buckets["waiting_or_draft"] if not p.is_draft] + drafts = [p for p in buckets["waiting_or_draft"] if p.is_draft] + lines.append(f"### 4. Waiting on Author ({len(waiting)}) & Drafts ({len(drafts)})") + if waiting: + waiting_summary = ", ".join( + f"[#{p.number}]({p.url}) (`@{p.author}`{', CONFLICTING' if p.mergeable == 'CONFLICTING' else ''})" + for p in waiting + ) + lines.append(f"- **Waiting on author**: {waiting_summary}") + if drafts: + draft_summary = ", ".join(f"[#{p.number}]({p.url}) (`@{p.author}`)" for p in drafts) + lines.append(f"- **Drafts**: {draft_summary}") + if not waiting and not drafts: + lines.append("- None") + lines.append("") + + batch = recommend_batch(buckets) + if batch: + lines.append(f"## Suggested Next Review Batch ({len(batch)} non-overlapping PRs)") + for idx, pr in enumerate(batch, 1): + lines.append( + f"{idx}. [#{pr.number}]({pr.url}) — `{pr.title}` " + f"(`@{pr.author}`, `{pr.size}`, CI: `{pr.ci_state}`) — {pr.reason}" + ) + lines.append("") + + return lines + + +def _render_issues_markdown(repo: str, issues: list[IssueItem]) -> list[str]: + with_pr = [i for i in issues if i.linked_prs] + unlinked = [i for i in issues if not i.linked_prs] + lines = [f"## Open Issues ({len(issues)} fetched)", ""] + lines.append(f"### Linked to Open PRs ({len(with_pr)})") + for issue in with_pr: + pr_links = ", ".join(f"[#{n}](https://github.com/{repo}/pull/{n})" for n in issue.linked_prs) + lines.append(f"- [#{issue.number}]({issue.url}) — `{issue.title}` (`@{issue.author}`) → PR {pr_links}") + if not with_pr: + lines.append("- None") + lines.append("") + lines.append(f"### Unlinked Open Issues ({len(unlinked)})") + for issue in unlinked: + lbls = f" [{', '.join(issue.labels)}]" if issue.labels else "" + lines.append( + f"- [#{issue.number}]({issue.url}) — `{issue.title}` (`@{issue.author}`, " + f"opened {issue.created_at[:10]}, {issue.comment_count} comments){lbls}" + ) + if not unlinked: + lines.append("- None") + lines.append("") + return lines + + +def fetch_github_data( + repo: str, + pr_limit: int, + include_pr_details: bool, + include_issues: bool, + issue_limit: int, +) -> dict[str, Any]: + """Run a single GitHub GraphQL query via the gh CLI.""" + owner, name = repo.split("/", 1) + cmd = [ + "gh", + "api", + "graphql", + "-F", + f"owner={owner}", + "-F", + f"name={name}", + "-F", + f"prLimit={pr_limit}", + "-F", + f"includePrDetails={'true' if include_pr_details else 'false'}", + "-F", + f"includeIssues={'true' if include_issues else 'false'}", + "-F", + f"issueLimit={issue_limit}", + "-f", + f"query={GRAPHQL_QUERY}", + ] + proc = subprocess.run(cmd, check=True, capture_output=True, text=True) + payload: dict[str, Any] = json.loads(proc.stdout) + if payload.get("errors"): + raise RuntimeError(f"GraphQL errors: {payload['errors']}") + return payload["data"] + + +def main(argv: list[str] | None = None) -> int: + """CLI entrypoint for PR and issue triage.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "command", + nargs="?", + choices=("prs", "issues", "all"), + default="prs", + help="Triage target: 'prs' (default), 'issues', or 'all'", + ) + parser.add_argument("--repo", default=DEFAULT_REPO, help="GitHub owner/repo (default: %(default)s)") + parser.add_argument("--reviewer", default=None, help="GitHub username to triage for (default: authenticated user)") + parser.add_argument("--pr-limit", type=int, default=100, help="Max open PRs to fetch (default: %(default)s)") + parser.add_argument("--issue-limit", type=int, default=50, help="Max open issues to fetch (default: %(default)s)") + parser.add_argument("--json", action="store_true", help="Emit JSON instead of Markdown") + args = parser.parse_args(argv) + + include_prs = args.command in {"prs", "all"} + include_issues = args.command in {"issues", "all"} + + data = fetch_github_data( + args.repo, + args.pr_limit, + include_pr_details=include_prs, + include_issues=include_issues, + issue_limit=args.issue_limit, + ) + reviewer: str = args.reviewer or data["viewer"]["login"] + repo_data = data["repository"] + + pr_nodes = [n for n in (repo_data.get("pullRequests", {}).get("nodes") or []) if isinstance(n, dict)] + pr_numbers = {int(n["number"]) for n in pr_nodes if isinstance(n.get("number"), int)} + + prs: list[PullRequestItem] = [] + buckets: dict[str, list[PullRequestItem]] = {} + if include_prs: + prs = [_parse_pr(node, reviewer, pr_numbers) for node in pr_nodes] + _populate_overlaps(prs) + buckets = classify_prs(prs, reviewer) + + issues: list[IssueItem] = [] + if include_issues: + prs_by_issue: dict[int, list[int]] = {} + for pr_node in pr_nodes: + if bool(pr_node.get("isDraft")): + continue + pr_num = int(pr_node["number"]) + for issue_num in _extract_issue_refs(pr_node, pr_numbers): + prs_by_issue.setdefault(issue_num, []).append(pr_num) + issue_nodes = [n for n in (repo_data.get("issues", {}).get("nodes") or []) if isinstance(n, dict)] + issues = [ + IssueItem( + number=int(node["number"]), + title=str(node.get("title") or ""), + url=str(node.get("url") or ""), + author=_login(node), + created_at=str(node.get("createdAt") or ""), + labels=[ + lbl["name"] + for lbl in (node.get("labels", {}).get("nodes") or []) + if isinstance(lbl, dict) and isinstance(lbl.get("name"), str) + ], + comment_count=int((node.get("comments") or {}).get("totalCount") or 0), + linked_prs=sorted(prs_by_issue.get(int(node["number"]), [])), + ) + for node in issue_nodes + ] + + if args.json: + out: dict[str, Any] = {"reviewer": reviewer} + if include_prs: + out["buckets"] = {k: [asdict(p) for p in v] for k, v in buckets.items()} + out["recommended_batch"] = [p.number for p in recommend_batch(buckets)] + if include_issues: + out["issues"] = [asdict(i) for i in issues] + print(json.dumps(out, indent=2)) + else: + md_lines: list[str] = [] + if include_prs: + md_lines.extend(_render_prs_markdown(reviewer, prs, buckets)) + if include_issues: + md_lines.extend(_render_issues_markdown(args.repo, issues)) + print("\n".join(md_lines).rstrip()) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/AGENTS.md b/AGENTS.md index 4e7c6daad..9128a2a1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,10 +17,11 @@ This document serves as the authoritative, single source of truth for engineerin # Environment setup uv venv && uv sync -# Run tests +# Run tests (benchmarks are disabled by default; pass --benchmark-enable to run them) uv run pytest uv run pytest tests/devices/traits/v1/test_status.py uv run pytest tests/protocols/test_v1_protocol.py +uv run pytest tests/map/test_benchmarks.py --benchmark-enable # Lint and typecheck uv run pre-commit run --all-files @@ -29,6 +30,8 @@ uv run ruff check roborock tests uv run mypy roborock tests ``` +- **Isolated Virtualenv in Shared / Worktree Containers**: If `VIRTUAL_ENV` or `UV_PROJECT_ENVIRONMENT` in your shell points to an external environment (such as a Home Assistant venv), override it (`UV_PROJECT_ENVIRONMENT=.venv VIRTUAL_ENV= uv run ...` or point `UV_PROJECT_ENVIRONMENT` at the main checkout's `.venv`) so `uv sync` and `pre-commit` never mutate external environments or load unrelated `pytest` plugins. Prefer `git grep` over assuming `rg` is installed, and pass `-R Python-roborock/python-roborock` to `gh` commands if no default repo is configured. + --- ## Core Architectural Hierarchy & Review Priorities @@ -67,7 +70,7 @@ Evaluate every change against the repository's three core layers in strict prior ### 3. Trait Design & Client Integration - **Compound Capability & Feature Gating**: Capability and trait availability MUST be gated by protocol version (`device.pv == "1.0"` or `DeviceVersion.V1`), appropriate category (`RoborockCategory.VACUUM`, `WET_DRY_VAC`, or `WASHING_MACHINE`), and device feature flags (`device.features`). -- **Linear State Flow**: Methods that parse responses or transform telemetry must return values to make state assignments explicit at the call site. Avoid multi-layered helper cascades. +- **Linear State & Write-Then-Refresh Flow**: Methods that parse responses or transform telemetry must return values to make state assignments explicit at the call site. Avoid multi-layered helper cascades. In trait setters, match sibling trait RPC conventions: lazily initialize cached state only when `None`, send the `SET` command, and `await self.refresh()` (or update optimistically where standard) **after** writing rather than issuing redundant pre- and post-write `GET` round-trips. Build wire payload dicts declaratively (e.g., filtering `None` values via dict comprehension) rather than long imperative `if x is not None:` chains. - **Consumer Agnosticism**: Design traits around cohesive, general-purpose consumer concepts (`CleanHistoryTrait`, `DockTrait`, `ConsumableTrait`), not low-level firmware registers or raw Tuya DPS numbers. - **Diagnostic Safety & Privacy**: Exclude sensitive user information (Wi-Fi SSIDs, passwords, cloud tokens, encryption keys) from device diagnostics and logs. @@ -80,11 +83,13 @@ Evaluate every change against the repository's three core layers in strict prior ### 5. Test Patterns & Fixtures - **Test Mirroring & Colocation**: Place and maintain unit tests in the matching mirror path under `tests/` (e.g. `tests/devices/traits/v1/test_status.py` for `roborock/devices/traits/v1/status.py`; `tests/map/test_b01_q10_map_parser.py` for `roborock/map/b01_q10_map_parser.py`). - **Avoid One-Off Test Files**: Do not create fragmented, single-bug test files (such as `tests/test_battery_low_voltage_fix.py`). Integrate test cases into the module's corresponding test suite. -- **Fixture Reuse & Parametrization**: Reuse shared fixtures (`fake_channel`, `message_builder`, `device_fixture`) in `tests/` and use table-driven `@pytest.mark.parametrize`. +- **Reproduce-First Bugfixes**: When fixing a bug or addressing post-merge review findings, add a failing test reproducing the issue against the baseline behavior first before applying the implementation fix. +- **Simulators & Fixture Reuse**: Reuse shared module fixtures (`mock_rpc_channel` and `device_fixture` in `tests/devices/traits/v1/fixtures.py`; `fake_channel` and `message_builder` in B01/RPC suites), stateful firmware simulators in `roborock.testing` (`V1VacuumSimulator`, `Q10VacuumSimulator`, `DyadSimulator`, `ZeoSimulator`, `FakeChannel`, `FakeRoborockCloud`), and table-driven `@pytest.mark.parametrize` rather than ad-hoc inline command-dict fakes. When adding new RPC commands, consider extending the corresponding `roborock.testing` simulator. - **Behavior-Driven Assertions**: Assert on public trait methods, return values, and emitted channel commands—never on private object attributes (`_state`). ### 6. PR Hygiene & Sizing - **Scoping & Sizing**: Keep pull requests focused on a single logical change or subsystem where possible (e.g. parser module with tests in one PR, traits consuming it in a follow-up PR). Large PRs (>500–1,000 LOC) take longer to review and block releases. +- **Minimal Diffs & Concise Comments**: Preserve existing method and class ordering when editing files to minimize diff noise. Keep docstrings and inline comments concise—distill non-obvious protocol quirks into 1–2 high-signal lines rather than essay-length comment blocks, without stripping useful domain context. - **CI Requirements**: PRs must pass automated CI (`.github/workflows/ci.yml`): - **Commitlint**: Commit messages and PR titles MUST follow Conventional Commits (`feat:`, `fix:`, `refactor:`, `chore:`, `docs:`). - **Pre-commit**: Ruff, Mypy (`check_untyped_defs = true`), and Codespell must pass (`uv run pre-commit run --all-files`). diff --git a/pyproject.toml b/pyproject.toml index 4a963338e..1f641d2ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,7 +148,7 @@ module = ["roborock.map.proto.*"] ignore_errors = true [tool.pytest.ini_options] -addopts = "-m 'not mqtt_broker'" +addopts = "-m 'not mqtt_broker' --benchmark-disable" markers = ["mqtt_broker: tests requiring a real MQTT broker"] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" diff --git a/tests/map/test_benchmarks.py b/tests/map/test_benchmarks.py index 1cf6c0570..2fa9e6b0c 100644 --- a/tests/map/test_benchmarks.py +++ b/tests/map/test_benchmarks.py @@ -8,9 +8,9 @@ - Pixel output validation (dimensions, format, bounding box) Can be run via pytest: - uv run pytest tests/map/test_benchmarks.py - uv run pytest tests/map/test_benchmarks.py --benchmark-only - uv run pytest tests/map/test_benchmarks.py --benchmark-autosave + uv run pytest tests/map/test_benchmarks.py --benchmark-enable + uv run pytest tests/map/test_benchmarks.py --benchmark-enable --benchmark-only + uv run pytest tests/map/test_benchmarks.py --benchmark-enable --benchmark-autosave Or directly as a standalone profiling CLI: uv run python -m tests.map.test_benchmarks