π The fast, Pythonic way to build MCP servers and clients.
Restore Marvin labeling and reopen disputed duplicates (#6495)
nate nowackffc65c7a8063
diff --git a/.github/workflows/auto-close-duplicates.yml b/.github/workflows/auto-close-duplicates.ymlindex 914bd22b7..c5cb6363a 100644--- a/.github/workflows/auto-close-duplicates.yml+++ b/.github/workflows/auto-close-duplicates.yml@@ -4,9 +4,21 @@ on:schedule:- cron: "0 9 * * *" # Run daily at 9 AM UTCworkflow_dispatch:+ issue_comment:+ types: [created]++concurrency:+ group: auto-close-duplicates-${{ github.event_name == 'issue_comment' && github.event.issue.number || 'scheduled' }}+ cancel-in-progress: falsejobs:auto-close-duplicates:+ if: >-+ github.event_name != 'issue_comment' ||+ (!github.event.issue.pull_request &&+ github.event.issue.state == 'closed' &&+ github.event.comment.user.type == 'User' &&+ contains(github.event.issue.labels.*.name, 'duplicate'))runs-on: ubuntu-latesttimeout-minutes: 10permissions:@@ -24,11 +36,12 @@ jobs:with:app-id: ${{ secrets.MARVIN_APP_ID }}private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}+ permission-issues: write- name: Install uvuses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2- - name: Auto-close duplicate issues+ - name: Process duplicate lifecyclerun: uv run scripts/auto_close_duplicates.pyenv:GITHUB_TOKEN: ${{ steps.marvin-token.outputs.token }}diff --git a/.github/workflows/marvin-label-triage.yml b/.github/workflows/marvin-label-triage.ymlindex 7f2f5179c..46729163a 100644--- a/.github/workflows/marvin-label-triage.yml+++ b/.github/workflows/marvin-label-triage.yml@@ -32,15 +32,9 @@ jobs:timeout-minutes: 10permissions:contents: read- issues: write- pull-requests: write-- # Pinned Claude Code. The repository instructions are AGENTS.md, which- # Claude Code reads natively from 2.1.281 on. Releases 2.1.216 through- # 2.1.226 broke every Bash call under the action's sandbox (`bwrap: Can't- # create file at /home/.mcp.json`), which let triage apply zero labels- # while reporting success; the sandbox check below fails the run instead.- # https://github.com/anthropics/claude-code/issues/79997+ issues: read+ pull-requests: read+env:PINNED_CLAUDE_CODE_VERSION: "2.1.282"@@ -51,20 +45,15 @@ jobs:repository: ${{ github.repository }}ref: ${{ github.event.repository.default_branch }}- - name: Generate Marvin App token+ - name: Generate Marvin read tokenid: marvin-tokenuses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3with:app-id: ${{ secrets.MARVIN_APP_ID }}private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}- # No `owner:` β with it set and `repositories:` empty the token is- # scoped to every repo in the PrefectHQ installation. Triage only- # ever touches this one. The permissions below match the job's- # `permissions:` block; unscoped the token would also carry- # contents: write and actions: write from the App installation.permission-contents: read- permission-issues: write- permission-pull-requests: write+ permission-issues: read+ permission-pull-requests: read- name: Read repository labelsid: repository-labels@@ -82,18 +71,9 @@ jobs:run: |cat >> $GITHUB_OUTPUT << 'EOF'PROMPT<<PROMPT_END- You're an issue triage assistant for FastMCP, a Python framework for building Model Context Protocol servers and clients. Your task is to analyze issues/PRs and apply appropriate labels.-- IMPORTANT: Your primary action should be to apply labels using the locked-down helper `.github/scripts/triage-label.sh`. DO NOT post comments. When you apply too-long, the workflow posts the comment for you (see below).-- CRITICAL β LABEL MECHANICS:- - Apply labels ONLY through the helper, which adds or removes repository labels on THIS issue/PR. It already knows the target repo and number (from the workflow environment) β you never pass them:- add: `bash .github/scripts/triage-label.sh add "label1" "label2"`- remove: `bash .github/scripts/triage-label.sh remove "label1"`- - The helper uses the additive REST labels endpoint, so it works for both issues and PRs and never clobbers labels applied by other workflows β notably the Require Issue Link workflow's `missing-issue-link` control label, which must survive or an auto-closed PR won't reopen when its author is assigned.- - The helper is your ONLY GitHub write access. Do NOT use raw `gh api`, `gh issue edit`, `gh pr edit`, or any other mutation β they are not available to you.- - Only apply labels from the complete repository label list below. Never invent labels.- - Use `remove` only to correct a label you believe is wrong, and never remove the control labels `missing-issue-link`, `bypass-issue-check`, or `trusted-contributor`.+ Classify this FastMCP issue or PR. Return the label names to add in the structured labels array.+ Use only labels described below that already exist in the repository.+ Return an empty array if you cannot retrieve the item or cannot classify it.Issue/PR Information:- REPO: ${{ github.repository }}@@ -110,7 +90,7 @@ jobs:- mcp__github__get_issue_comments: Read any discussion- If the issue/PR mentions other issues (e.g., "fixes #123", "related to #456"), use mcp__github__get_issue to read those linked issues for additional context- 3. Analyze and apply labels based on these guidelines:+ 3. Choose labels based on these guidelines:CORE CATEGORIES (apply EXACTLY ONE - these are mutually exclusive, including when applying too-long):- bug: Reports of broken functionality OR PRs that fix bugs@@ -143,7 +123,7 @@ jobs:- invalid: Spam, completely off-topic, or nonsensical (often LLM-generated)- too-long: Apply when an issue or PR doesn't conform to CONTRIBUTING.md. Issues should be a short problem description, an MRE, and expected vs. actual behavior β not a design document. PRs should have a focused description of the change β not a report. We don't need proposed solutions or design alternatives (the issue should describe the problem and let maintainers architect the fix), summaries of what tests cover, explanations of code we can read ourselves, or speculative root-cause analysis. Common LLM failure modes to watch for: verbose "diagnostic" writeups, large proposed patches in issue bodies, multi-section reports restating what's visible in the diff, numbered lists of possible approaches or solutions, "suggested" schemas/shapes/APIs, generic analysis that doesn't reference specific code, and "Notes" sections. But these are heuristics, not rules β a complex PR may legitimately need more context, and a brief submission can still be low-quality. Judge by whether the content helps a reviewer or just adds noise. When applying too-long, still apply the core category and area labels β too-long is a format signal, not a replacement for categorization. Issues still need to be findable by category.- WHEN APPLYING too-long: A later workflow step posts the contributing-guidelines comment. Do not post it yourself.+ Returning too-long also asks the workflow to post its contributing-guidelines comment.AREA LABELS (apply ONLY when thematically central to the issue):- cli: Issues primarily about FastMCP CLI commands (run, dev, install)@@ -166,9 +146,6 @@ jobs:- dependencies: Only for dependabot PRs or issues specifically about package updates- DON'T MERGE: Only if PR author explicitly states it's not ready- 4. Apply selected labels:- Add them with `bash .github/scripts/triage-label.sh add "label1" "label2"`.- DO NOT post any commentsPROMPT_ENDEOF@@ -200,22 +177,58 @@ jobs:allowed_non_write_users: "*"allowed_bots: "marvin-context-protocol"claude_args: |- --allowedTools "Bash(bash .github/scripts/triage-label.sh:*)",mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__get_pull_request,mcp__github__get_pull_request_files+ --allowedTools mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__get_pull_request,mcp__github__get_pull_request_files+ --json-schema '{"type":"object","properties":{"labels":{"type":"array","items":{"type":"string"},"maxItems":5}},"required":["labels"],"additionalProperties":false}'settings: |- {- "model": "claude-sonnet-5",- "env": {- "GH_TOKEN": "${{ steps.marvin-token.outputs.token }}",- "TRIAGE_REPO": "${{ github.repository }}",- "TRIAGE_NUMBER": "${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}"- }- }-- # Marvin has no comment tool. When it applies too-long, this step posts- # the contributing-guidelines comment on this issue or PR, once.+ { "model": "claude-sonnet-5" }++ - name: Generate Marvin write token+ id: marvin-write-token+ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3+ with:+ app-id: ${{ secrets.MARVIN_APP_ID }}+ private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}+ permission-issues: write+ permission-pull-requests: write++ - name: Apply triage labels+ env:+ GH_TOKEN: ${{ steps.marvin-write-token.outputs.token }}+ TRIAGE_REPO: ${{ github.repository }}+ TRIAGE_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}+ REPOSITORY_LABELS: ${{ steps.repository-labels.outputs.labels }}+ RESULT: ${{ steps.marvin.outputs.structured_output }}+ run: |+ labels=$(jq -er --argjson known "$REPOSITORY_LABELS" '+ ($known | map(.name)) as $existing+ | ["bug", "enhancement", "feature", "documentation"] as $core+ | ($core + [+ "breaking change", "high-priority", "low-priority", "needs more info",+ "invalid", "too-long", "cli", "client", "server", "auth", "openapi",+ "http", "contrib", "tests", "security", "dependencies", "DON\u0027T MERGE"+ ]) as $allowed+ | .labels+ | if type != "array" then error("Expected a labels array") else unique end+ | if length > 5 or any(.[]; . as $label |+ ($allowed | index($label)) == null or ($existing | index($label)) == null)+ then error("Invalid triage label selection") else . end+ | if length > 0 and ([.[] | select(. as $label | $core | index($label))] | length) != 1+ then error("Expected exactly one category") else . end+ | join("\n")+ ' <<< "$RESULT")+ if [[ -z "$labels" ]]; then+ echo "Marvin returned no labels."+ exit 0+ fi+ selected=()+ while IFS= read -r label; do+ selected+=("$label")+ done <<< "$labels"+ bash .github/scripts/triage-label.sh add "${selected[@]}"+- name: Post too-long commentenv:- GH_TOKEN: ${{ steps.marvin-token.outputs.token }}+ GH_TOKEN: ${{ steps.marvin-write-token.outputs.token }}REPO: ${{ github.repository }}NUMBER: ${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}run: |@@ -241,95 +254,6 @@ jobs:gh api "repos/$REPO/issues/$NUMBER/comments" -f body="$message" > /dev/nullecho "Posted the too-long comment on #$NUMBER."- # Triage is fire-and-forget: nobody watches a green run, so a broken- # allowlist has to fail the job or it goes unnoticed indefinitely β a- # mangled pattern silently produced zero labels across a dozen PRs- # because the run still reported success.- #- # Only denials of commands we MEANT to grant indicate that breakage. An- # agent reaching for something never on the allowlist (falling back to- # `gh issue view` when the API is down, say) is behaving normally, and- # failing on that would cry wolf during every GitHub incident.- - name: Fail if Marvin could not run its tools- if: always() && steps.marvin.conclusion != 'skipped'- env:- EXECUTION_FILE: ${{ steps.marvin.outputs.execution_file }}- run: |- file="${EXECUTION_FILE:-}"- if [[ -z "$file" || ! -s "$file" ]]; then- file="${RUNNER_TEMP}/claude-execution-output.json"- fi- # A missing or empty log means we cannot tell a clean run from a- # blocked one, which is the exact failure this step exists to catch.- if [[ ! -s "$file" ]]; then- echo "::error::No Marvin execution log found; cannot verify tool permissions."- exit 1- fi-- # The persisted log carries a `permission_denials` array on each- # `type: result` entry; the `permission_denials_count` scalar only- # appears in the action's condensed stdout summary, never on disk.- # Anchor to result entries rather than recursing with `..`, which- # descends into each denial's `tool_input` and double-counts any- # denied command that happens to mention the field name.- if ! summary=$(jq -sr '- [ .[] | if type == "array" then .[] else . end ]- | map(select(type == "object" and .type == "result"))- | map(.permission_denials // []) | flatten- | map(.tool_input.command // "")- | { total: length,- granted: map(select(- startswith("bash .github/scripts/triage-label.sh")- ))- }- | "\(.total)\t\(.granted | length)\t\(.granted | join(" | "))"- ' "$file"); then- echo "::error::Could not parse Marvin execution log ($file)."- exit 1- fi- IFS=$'\t' read -r total granted commands <<<"$summary"- echo "Denied tool calls: $total (of which allowlisted: $granted)"-- if [[ "$granted" -gt 0 ]]; then- echo "::error::Marvin was denied $granted call(s) to tools this workflow grants, so it could not apply labels: ${commands}. The --allowedTools value is not reaching the permission matcher intact β claude_args is lexed with shell-quote, so any Bash(...) pattern containing a space must be quoted or it is split into fragments."- exit 1- fi- if [[ "$total" -gt 0 ]]; then- echo "::notice::Marvin was denied $total call(s), none of them to tools this workflow grants. That is expected when it probes for a tool we deliberately withhold; the allowlist is intact."- fi-- # A granted tool can also fail *after* the permission check, which the- # denial count above cannot see. Claude Code 2.1.216 did exactly that:- # the sandbox refused to build and every Bash call β including the- # labeling helper β exited 1 with `bwrap: ...`, while the run stayed- # green. Correlate results back to their Bash tool_use rather than- # grepping the whole log, so an issue body quoting a sandbox error- # cannot fail an otherwise healthy run.- if ! sandbox=$(jq -sr '- [ .[] | if type == "array" then .[] else . end ]- | map(select(type == "object" and (.type == "assistant" or .type == "user")))- | map(.message.content // []) | flatten- | map(select(type == "object"))- | . as $blocks- | ( $blocks- | map(select(.type == "tool_use" and .name == "Bash"))- | map(.id) ) as $bash- | $blocks- | map(select(.type == "tool_result" and (.tool_use_id as $i | $bash | index($i))))- | map(.content | tostring)- | map(select(test("bwrap:|Failed to (start|create) sandbox")))- | "\(length)\t\(.[0] // "" | gsub("[\t\n]"; " ") | .[0:200])"- ' "$file"); then- echo "::error::Could not scan Marvin execution log for sandbox failures ($file)."- exit 1- fi- IFS=$'\t' read -r sandbox_failures sandbox_sample <<<"$sandbox"-- if [[ "$sandbox_failures" -gt 0 ]]; then- echo "::error::Marvin's Bash tool failed $sandbox_failures time(s) inside the action's subprocess sandbox, so it could not apply labels: ${sandbox_sample}. This is an environment failure, not a prompt or allowlist problem β check whether the pinned Claude Code version (${PINNED_CLAUDE_CODE_VERSION}) still avoids the upstream sandbox regression."- exit 1- fi-- name: Upload Marvin execution logif: always() && steps.marvin.conclusion != 'skipped'uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7diff --git a/scripts/auto_close_duplicates.py b/scripts/auto_close_duplicates.pyindex e6a88886a..7ea6feb9c 100644--- a/scripts/auto_close_duplicates.py+++ b/scripts/auto_close_duplicates.py@@ -12,12 +12,20 @@ This script runs on a schedule to automatically close issues that have beenmarked as duplicates and haven't received any preventing activity."""+import jsonimport osfrom dataclasses import dataclassfrom datetime import UTC, datetime, timedelta+from pathlib import Pathimport httpx+MARVIN_BOT_ID = 225465937+CLOSURE_NOTICE = (+ "Closing this issue as a duplicate based on the automated analysis above."+)+ESTABLISHED_ASSOCIATIONS = {"CONTRIBUTOR", "COLLABORATOR", "MEMBER", "OWNER"}+@dataclassclass Issue:@@ -112,67 +120,61 @@ class GitHubClient:return issues- def get_issue_comments(self, issue_number: int) -> list[Comment]:- """Fetch all comments for an issue."""- url = f"{self.base_url}/issues/{issue_number}/comments"- comments = []-+ def _read_all(self, path: str) -> list[dict]:+ records = []with httpx.Client() as client:- page = 1- while True:+ for page in range(1, 11):response = client.get(- url, headers=self.headers, params={"page": page, "per_page": 100}+ f"{self.base_url}/{path}",+ headers=self.headers,+ params={"page": page, "per_page": 100},)+ response.raise_for_status()+ batch = response.json()+ if not isinstance(batch, list):+ raise ValueError("Expected a GitHub collection")+ records.extend(batch)+ if "next" not in response.links:+ return records+ raise ValueError("GitHub collection exceeded the ten-page limit")- if response.status_code != 200:- break-- data = response.json()- if not data:- break-- for comment_data in data:- comments.append(- Comment(- id=comment_data["id"],- body=comment_data["body"],- created_at=comment_data["created_at"],- user_id=comment_data["user"]["id"],- user_login=comment_data["user"]["login"],- user_type=comment_data["user"]["type"],- )- )-- page += 1- if page > 10: # Safety limit- break-- return comments+ def get_issue_comments(self, issue_number: int) -> list[Comment]:+ return [+ Comment(+ id=comment["id"],+ body=comment["body"],+ created_at=comment["created_at"],+ user_id=comment["user"]["id"],+ user_login=comment["user"]["login"],+ user_type=comment["user"]["type"],+ )+ for comment in self._read_all(f"issues/{issue_number}/comments")+ ]++ def get_comment_reactions(self, comment_id: int) -> list[Reaction]:+ return [+ Reaction(+ user_id=reaction["user"]["id"],+ user_login=reaction["user"]["login"],+ content=reaction["content"],+ )+ for reaction in self._read_all(f"issues/comments/{comment_id}/reactions")+ ]- def get_comment_reactions(- self, issue_number: int, comment_id: int- ) -> list[Reaction]:- """Fetch reactions for a specific comment."""- url = f"{self.base_url}/issues/{issue_number}/comments/{comment_id}/reactions"- reactions = []+ def get_issue_timeline(self, issue_number: int) -> list[dict]:+ return self._read_all(f"issues/{issue_number}/timeline")+ def reopen_duplicate(self, issue_number: int, closed_at: str) -> bool:+ url = f"{self.base_url}/issues/{issue_number}"with httpx.Client() as client:response = client.get(url, headers=self.headers)-- if response.status_code != 200:- return reactions-- data = response.json()- for reaction_data in data:- reactions.append(- Reaction(- user_id=reaction_data["user"]["id"],- user_login=reaction_data["user"]["login"],- content=reaction_data["content"],- )- )-- return reactions+ response.raise_for_status()+ issue = response.json()+ if not is_closed_duplicate(issue) or issue["closed_at"] != closed_at:+ return False+ response = client.patch(url, headers=self.headers, json={"state": "open"})+ response.raise_for_status()+ return response.json()["state"] == "open"def remove_label(self, issue_number: int, label: str) -> bool:"""Remove a label from an issue."""@@ -283,6 +285,60 @@ def has_human_activity(return False+def is_closed_duplicate(issue: dict) -> bool:+ return (+ issue["state"] == "closed"+ and "pull_request" not in issue+ and any(label["name"] == "duplicate" for label in issue["labels"])+ )+++def reconsider_duplicate(client: GitHubClient, event: dict) -> None:+ issue = event["issue"]+ comment = event["comment"]+ author = comment["user"]+ if not is_closed_duplicate(issue) or author["type"] != "User":+ return+ if (+ author["id"] != issue["user"]["id"]+ and comment["author_association"] not in ESTABLISHED_ASSOCIATIONS+ ):+ return++ closed_at = issue["closed_at"]+ if not closed_at or comment["created_at"] < closed_at:+ return+ number = issue["number"]+ closed_time = datetime.fromisoformat(closed_at)+ found_close = False+ for entry in reversed(client.get_issue_timeline(number)):+ kind, created_at = entry["event"], entry.get("created_at")+ if kind in {"closed", "reopened"}:+ if (+ found_close+ or kind != "closed"+ or created_at != closed_at+ or (entry.get("actor") or {}).get("id") != MARVIN_BOT_ID+ ):+ return+ found_close = True+ elif (+ found_close+ and kind == "commented"+ and (entry.get("user") or {}).get("id") == MARVIN_BOT_ID+ and (entry.get("body") or "").startswith(CLOSURE_NOTICE)+ and created_at+ and timedelta(0)+ <= closed_time - datetime.fromisoformat(created_at)+ <= timedelta(minutes=5)+ ):+ if client.reopen_duplicate(number, closed_at):+ print(+ f"Reopened #{number} for maintainer review after comment {comment['id']}"+ )+ return++def main():"""Main entry point for auto-closing duplicate issues."""print("[DEBUG] Starting auto-close duplicates script")@@ -299,6 +355,10 @@ def main():# Initialize clientclient = GitHubClient(token, owner, repo)+ if os.environ.get("GITHUB_EVENT_NAME") == "issue_comment":+ event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())+ reconsider_duplicate(client, event)+ return# Only fetch issues with the potential-duplicate labelall_issues = client.get_potential_duplicate_issues()@@ -307,10 +367,15 @@ def main():closed_count = 0cleared_count = 0+ failed_reads = 0for issue in all_issues:- # Get comments for this issue- comments = client.get_issue_comments(issue.number)+ try:+ comments = client.get_issue_comments(issue.number)+ except (httpx.HTTPError, ValueError, KeyError, TypeError) as error:+ print(f"Unable to read comments for #{issue.number}: {error}")+ failed_reads += 1+ continue# Look for duplicate marking commentduplicate_comment = find_duplicate_comment(comments)@@ -337,8 +402,12 @@ def main():print(f"[DEBUG] Issue #{issue.number} still in 3-day cooldown period")continue- # Get reactions on the duplicate comment- reactions = client.get_comment_reactions(issue.number, duplicate_comment.id)+ try:+ reactions = client.get_comment_reactions(duplicate_comment.id)+ except (httpx.HTTPError, ValueError, KeyError, TypeError) as error:+ print(f"Unable to read reactions for #{issue.number}: {error}")+ failed_reads += 1+ continue# Check for human activity that prevents closureif has_human_activity(issue, duplicate_comment, comments, reactions):@@ -349,7 +418,7 @@ def main():# No human activity after cooldown - close as duplicateclose_message = (- "Closing this issue as a duplicate based on the automated analysis above.\n\n"+ f"{CLOSURE_NOTICE}\n\n""The duplicate issues identified contain existing discussions and potential solutions. ""Please add your π to those issues if they match your use case.\n\n""If this was closed in error, please leave a comment explaining why this is not "@@ -364,8 +433,10 @@ def main():print(f"[DEBUG] Processing complete. Closed {closed_count} duplicates, "- f"cleared {cleared_count} from review"+ f"cleared {cleared_count} from review, {failed_reads} evidence reads failed")+ if failed_reads:+ raise SystemExit(1)if __name__ == "__main__":diff --git a/tests/scripts/test_auto_close_duplicates.py b/tests/scripts/test_auto_close_duplicates.pynew file mode 100644index 000000000..175da98f5--- /dev/null+++ b/tests/scripts/test_auto_close_duplicates.py@@ -0,0 +1,171 @@+import httpx+import pytest++from scripts import auto_close_duplicates as duplicate+++ ("endpoint", "scenario", "writes"),+ [+ ("comments", "http_error", []),+ ("reactions", "http_error", []),+ ("comments", "page_limit", []),+ ("reactions", "page_limit", []),+ ("reactions", "objected", ["DELETE"]),+ ("reactions", "unchallenged", ["POST", "DELETE", "POST", "PATCH"]),+ ],+)+def test_duplicate_close_uses_complete_evidence(+ endpoint: str, scenario: str, writes: list[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ real_client = httpx.Client+ calls: list[str] = []+ issue = {+ "number": 1,+ "title": "A duplicate report",+ "state": "open",+ "created_at": "2026-01-01T00:00:00Z",+ "user": {"id": 1, "login": "reporter"},+ }+ warning = {+ "id": 2,+ "body": "Found 1 possible duplicate issue",+ "created_at": "2026-01-01T00:00:00Z",+ "user": {"id": 2, "login": "marvin[bot]", "type": "Bot"},+ }++ def respond(request: httpx.Request) -> httpx.Response:+ calls.append(request.method)+ path = request.url.path+ if request.method != "GET":+ status = 201 if path.endswith("/comments") else 200+ return httpx.Response(status)+ if path.endswith("/issues"):+ return httpx.Response(+ 200, json=[issue] if request.url.params["page"] == "1" else []+ )+ result = [warning] if path.endswith("/comments") else []+ if path.endswith("/reactions"):+ assert path.endswith("/issues/comments/2/reactions")+ if path.endswith(f"/{endpoint}"):+ if scenario == "http_error":+ return httpx.Response(503)+ if scenario == "page_limit" or (+ scenario == "objected" and request.url.params["page"] == "1"+ ):+ return httpx.Response(+ 200, json=result, headers={"Link": f'<{request.url}>; rel="next"'}+ )+ if scenario == "objected":+ result = [{"user": {"id": 1, "login": "reporter"}, "content": "-1"}]+ return httpx.Response(200, json=result)++ transport = httpx.MockTransport(respond)+ monkeypatch.setenv("GITHUB_TOKEN", "test")+ monkeypatch.setattr(httpx, "Client", lambda: real_client(transport=transport))++ if scenario in {"http_error", "page_limit"}:+ with pytest.raises(SystemExit) as stopped:+ duplicate.main()+ assert stopped.value.code == 1+ else:+ duplicate.main()++ assert [method for method in calls if method != "GET"] == writes+++ ("association", "scenario", "expected_requests"),+ [+ ("CONTRIBUTOR", "followup", ["timeline", "issue", "reopen"]),+ ("MEMBER", "followup", ["timeline", "issue", "reopen"]),+ ("NONE", "reporter", ["timeline", "issue", "reopen"]),+ ("NONE", "followup", []),+ ("CONTRIBUTOR", "bot", []),+ ("CONTRIBUTOR", "before_close", []),+ ("CONTRIBUTOR", "pull_request", []),+ ("CONTRIBUTOR", "manual_close", ["timeline"]),+ ("CONTRIBUTOR", "previous_closure", ["timeline"]),+ ("CONTRIBUTOR", "already_reopened", ["timeline", "issue"]),+ ("CONTRIBUTOR", "closed_again", ["timeline", "issue"]),+ ("CONTRIBUTOR", "label_removed", ["timeline", "issue"]),+ ],+)+def test_duplicate_followup_reopens_only_current_marvin_closure(+ association: str, scenario: str, expected_requests: list[str]+) -> None:+ closed_at = "2026-01-01T00:00:04Z"+ issue = {+ "number": 1,+ "state": "closed",+ "labels": [{"name": "duplicate"}],+ "user": {"id": 3},+ "closed_at": closed_at,+ }+ event = {+ "issue": {+ **issue,+ **({"pull_request": {}} if scenario == "pull_request" else {}),+ },+ "comment": {+ "id": 5,+ "user": {+ "id": 3 if scenario == "reporter" else 4,+ "type": "Bot" if scenario == "bot" else "User",+ },+ "author_association": association,+ "created_at": (+ "2026-01-01T00:00:03Z" if scenario == "before_close" else closed_at+ ),+ },+ }+ timeline = [+ {+ "event": "commented",+ "user": {"id": duplicate.MARVIN_BOT_ID},+ "body": duplicate.CLOSURE_NOTICE,+ "created_at": "2026-01-01T00:00:02Z",+ },+ {+ "event": "closed",+ "actor": {+ "id": 4 if scenario == "manual_close" else duplicate.MARVIN_BOT_ID+ },+ "created_at": closed_at,+ },+ ]+ if scenario == "previous_closure":+ timeline.insert(1, {"event": "reopened", "created_at": "2026-01-01T00:00:03Z"})+ if scenario == "already_reopened":+ issue["state"] = "open"+ if scenario == "closed_again":+ issue["closed_at"] = "2026-01-01T00:01:00Z"+ if scenario == "label_removed":+ issue["labels"] = []++ calls: list[str] = []++ def respond(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/issues/1/timeline"):+ assert request.method == "GET"+ calls.append("timeline")+ return httpx.Response(200, json=timeline)+ assert request.url.path.endswith("/issues/1")+ if request.method == "GET":+ calls.append("issue")+ return httpx.Response(200, json=issue)+ assert request.method == "PATCH"+ assert request.content == b'{"state":"open"}'+ calls.append("reopen")+ return httpx.Response(200, json={"state": "open"})++ real_client = httpx.Client+ with pytest.MonkeyPatch.context() as patch:+ patch.setattr(+ httpx, "Client", lambda: real_client(transport=httpx.MockTransport(respond))+ )+ duplicate.reconsider_duplicate(+ duplicate.GitHubClient("test", "owner", "repo"), event+ )++ assert calls == expected_requests