🚀 The fast, Pythonic way to build MCP servers and clients.
Post triage outcomes instead of run starts, and skip maintainer events (#6382)
nate nowack7eaae1bed73a
diff --git a/.github/agentic/README.md b/.github/agentic/README.mdindex 623e727a5..454ff02c1 100644--- a/.github/agentic/README.md+++ b/.github/agentic/README.md@@ -18,6 +18,14 @@ public-facing outcome through the Sol `triage_review` node, which loadsCOMMENT reviews by the triage review app. Nothing in this path assigns, closes, labels ormerges.+Intake skips events sent by anyone with write access to the repository, so+maintainers' own edits and their agents' activity don't start triage. If the+permission lookup fails, triage runs anyway. When a finished intake leaves issues+for a maintainer (an existing PR to review, a decision, a proposed close or missing+repro info), it emits `fastmcp.triage.outcome` and the `fastmcp-triage-outcome`+automation posts one line per issue to Slack. Intakes with nothing to decide stay+quiet; failures go through the failure alert.+Each controller run retains its results as `<batch-id>-review-bins`:```shdiff --git a/.github/agentic/flows/agentic_backlog.py b/.github/agentic/flows/agentic_backlog.pyindex d198f7dc2..7e2e6dcd2 100644--- a/.github/agentic/flows/agentic_backlog.py+++ b/.github/agentic/flows/agentic_backlog.py@@ -18,6 +18,8 @@ class Intake(BaseModel):pull_requests: list[PositiveInt] = Field(default_factory=list, max_length=10)queue: str | None = Field(default=None, pattern=r"^[a-z0-9-]{1,32}$")retry_failed: bool = False+ # GitHub login whose event started this intake; maintainers' own events are skipped.+ sender: str | None = Field(default=None, pattern=r"^[A-Za-z0-9][A-Za-z0-9-]{0,38}$")def scoped(self) -> bool:return bool(self.issues or self.pull_requests)diff --git a/.github/agentic/flows/agentic_github.py b/.github/agentic/flows/agentic_github.pyindex ae962c97d..03fe0e64f 100644--- a/.github/agentic/flows/agentic_github.py+++ b/.github/agentic/flows/agentic_github.py@@ -3,8 +3,21 @@ from __future__ import annotationsimport jsonimport urllib.errorimport urllib.request+from collections.abc import CallableREPOSITORY = "PrefectHQ/fastmcp"+WRITE_ROLES = frozenset({"admin", "maintain", "write"})+++def can_write(read: Callable[[str], object], login: str) -> bool:+ """Whether `login` has write, maintain or admin access to the repository."""+ grant = read(f"repos/{REPOSITORY}/collaborators/{login}/permission")+ if not isinstance(grant, dict):+ raise ValueError("Invalid collaborator permission")+ # `permission` folds maintain into write; `role_name` names the actual role.+ return (+ grant.get("role_name") in WRITE_ROLES or grant.get("permission") in WRITE_ROLES+ )class GitHub:diff --git a/.github/agentic/flows/agentic_outcome.py b/.github/agentic/flows/agentic_outcome.pynew file mode 100644index 000000000..bb4194253--- /dev/null+++ b/.github/agentic/flows/agentic_outcome.py@@ -0,0 +1,91 @@+"""The Slack summary of a finished intake: one line per issue that needs a maintainer."""++from __future__ import annotations++import re++ISSUE_URL = "https://github.com/PrefectHQ/fastmcp/issues/"+# Bins whose items wait on a maintainer, in the order they are listed. Unchanged+# items need nothing, and operational ones go through the failure alert.+ATTENTION_BINS = ("existing_review", "decisions", "pruning", "evidence")+MAX_LINES = 6+++def subjects(originals: dict[int, dict], pending: list[dict]) -> list[dict]:+ """Title and author of each admitted issue, from its collected evidence."""+ titles = {item["issue_number"]: item.get("title") for item in pending}+ found = {+ number: {+ "issue_number": number,+ "title": evidence["issue"].get("title") or titles.get(number),+ "author": (evidence["issue"].get("user") or {}).get("login"),+ }+ for number, evidence in originals.items()+ }+ for number, title in titles.items():+ found.setdefault(+ number, {"issue_number": number, "title": title, "author": None}+ )+ return [found[number] for number in sorted(found)]+++def clip(text: object, limit: int) -> str:+ text = " ".join(str(text or "").split())+ return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"+++def mrkdwn(text: str) -> str:+ return text.replace("&", "&").replace("<", "<").replace(">", ">")+++def first_sentence(text: object) -> str:+ return re.split(r"(?<=[.!?])\s", " ".join(str(text or "").split()), maxsplit=1)[0]+++def pull_requests(item: dict) -> list[int]:+ numbers = [+ check["pr_number"]+ for check in item.get("verification") or []+ if isinstance(check.get("pr_number"), int)+ ]+ numbers = numbers or list(item.get("verification_prs") or [])+ if not numbers:+ linked = (item.get("route") or {}).get("pull_requests") or []+ numbers = [pr["number"] for pr in linked if pr.get("state") == "open"]+ return list(dict.fromkeys(numbers))+++def action(name: str, item: dict) -> str:+ if name == "existing_review":+ numbers = pull_requests(item)[:3]+ if not numbers:+ return "review the linked contribution"+ label = "PR" if len(numbers) == 1 else "PRs"+ return f"review {label} " + ", ".join(f"#{number}" for number in numbers)+ if name == "pruning":+ return "close? " + clip(first_sentence(item.get("reason")), 60)+ if name == "evidence":+ return "needs repro info"+ return clip(item.get("question") or first_sentence(item.get("reason")), 60)+++def outcome_lines(review: dict, issues: list[dict]) -> list[str]:+ known = {issue["issue_number"]: issue for issue in issues}+ lines = []+ for name in ATTENTION_BINS:+ for item in review["bins"].get(name, []):+ number = item.get("issue_number")+ if not isinstance(number, int):+ continue+ subject = known.get(number, {})+ text = ""+ if subject.get("title"):+ text += " " + clip(subject["title"], 50)+ if subject.get("author"):+ text += f" · @{subject['author']}"+ text += " → " + action(name, item)+ lines.append(f"<{ISSUE_URL}{number}|#{number}>" + mrkdwn(text))+ if len(lines) > MAX_LINES:+ hidden = len(lines) - (MAX_LINES - 1)+ lines = lines[: MAX_LINES - 1] + [f"…and {hidden} more in the review bins"]+ return linesdiff --git a/.github/agentic/flows/agentic_triage.py b/.github/agentic/flows/agentic_triage.pyindex 4c261f24a..3854221b1 100644--- a/.github/agentic/flows/agentic_triage.py+++ b/.github/agentic/flows/agentic_triage.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+import subprocessimport tempfileimport timefrom collections.abc import Callable@@ -19,13 +20,16 @@ from prefect.client.schemas.filters import (from prefect.client.schemas.objects import Statefrom prefect.client.schemas.sorting import ArtifactSortfrom prefect.context import FlowRunContext+from prefect.events import emit_eventfrom prefect.states import Completedfrom flows.agentic_artifacts import plain, published_reviews, retain_markdownfrom flows.agentic_backlog import Intake, due, inventory, settlefrom flows.agentic_claims import claim_workfrom flows.agentic_freshness import revalidate+from flows.agentic_github import can_writefrom flows.agentic_intake import evidence_revision, upgrade_policy_outcomes+from flows.agentic_outcome import outcome_lines, subjectsfrom flows.agentic_stack_policy import Batchfrom flows.agentic_stack_runtime import (Runtime,@@ -92,6 +96,17 @@ def github(endpoint: str) -> object:return gh_api(endpoint, environment, 60)+def maintainer(sender: str, read: Callable[[str], object] = github) -> bool:+ """Whether the event sender can write to the repository.++ A failed lookup counts as not a maintainer, so an API error never drops an event.+ """+ try:+ return can_write(read, sender)+ except (RuntimeError, ValueError, OSError, subprocess.SubprocessError):+ return False++def admit(config: Intake,runtime: Runtime,@@ -229,6 +244,7 @@ def finish(completed = []pending = plan["pending"]receipts = []+ issues = []if plan["batch"]:timestamp = plan["batch"]["started_at"]if run_id:@@ -303,6 +319,10 @@ def finish({number: plan["batch"]["groups"][0]["branch"] for number in selected},read_evidence,)+ issues = subjects(+ originals,+ [item for item in plan["pending"] if item["issue_number"] in selected],+ )pending, completed = settle(pending, selected, result)exhausted = [row["issue_number"] for row in pending if row["attempts"] >= 3]for item in plan["pending"]:@@ -331,6 +351,7 @@ def finish("completed": completed,"receipts": receipts,"review": result,+ "issues": issues,}metrics = {"published_reviews": len(published_reviews(result)) if result else 0,@@ -402,32 +423,55 @@ def triage_intake():raise ValueError("Intake requires a bounded managed deployment")deadline = datetime.now(UTC) + timedelta(hours=2)- with (- claim_work([config.scope()], current.id, deadline),- tempfile.TemporaryDirectory(prefix="fastmcp-intake-") as temporary,- ):+ with tempfile.TemporaryDirectory(prefix="fastmcp-intake-") as temporary:intake_tools(Path(temporary))- plan = admit(config, runtime, controller_id, current.id)- if plan["phase"] == "committed":- return plan- try:- run_id = dispatch(plan) if plan["batch"] else None- except ValueError as error:- result = finish(plan, current.id, config.scope(), None, str(error))- return Completed(name="Degraded", data=result, message=str(error))- while run_id:- with get_client(sync_client=True) as client:- child = client.read_flow_run(run_id)- if child.state is not None and child.state.is_final():- break- time.sleep(5)- result = finish(plan, current.id, config.scope(), run_id)- reasons = attention(result["review"]) if result["review"] else []- if reasons:+ if config.sender and maintainer(config.sender):return Completed(- name="Degraded", data=result, message="; ".join(reasons)[:2000]+ data={"skipped": "maintainer_sender", "sender": config.sender},+ message=f"Skipped: {config.sender} is a maintainer",)- return result+ with claim_work([config.scope()], current.id, deadline):+ return triage(config, runtime, controller_id, current.id)+++def triage(+ config: Intake, runtime: Runtime, controller_id: UUID, owner: UUID+) -> dict | State:+ plan = admit(config, runtime, controller_id, owner)+ if plan["phase"] == "committed":+ return plan+ try:+ run_id = dispatch(plan) if plan["batch"] else None+ except ValueError as error:+ result = finish(plan, owner, config.scope(), None, str(error))+ return Completed(name="Degraded", data=result, message=str(error))+ while run_id:+ with get_client(sync_client=True) as client:+ child = client.read_flow_run(run_id)+ if child.state is not None and child.state.is_final():+ break+ time.sleep(5)+ result = finish(plan, owner, config.scope(), run_id)+ announce(owner, result)+ reasons = attention(result["review"]) if result["review"] else []+ if reasons:+ return Completed(+ name="Degraded", data=result, message="; ".join(reasons)[:2000]+ )+ return result+++def announce(owner: UUID, state: dict) -> None:+ """Emit the Slack outcome when any admitted issue now waits on a maintainer."""+ if not state["review"]:+ return+ lines = outcome_lines(state["review"], state.get("issues", []))+ if lines:+ emit_event(+ event="fastmcp.triage.outcome",+ resource={"prefect.resource.id": f"fastmcp.triage.intake.{owner}"},+ payload={"text": "\n".join(lines)},+ )# Evidence that moved during the run is requeued by `settle`, and the GitHubdiff --git a/.github/agentic/scripts/agentic_stack.sh b/.github/agentic/scripts/agentic_stack.shindex fa353b64a..3f01d312d 100644--- a/.github/agentic/scripts/agentic_stack.sh+++ b/.github/agentic/scripts/agentic_stack.sh@@ -179,23 +179,31 @@ case "${1:-}" inmatch_related:{},after:[],for_each:["prefect.resource.id"]},actions:[{type:"run-deployment",source:"selected",deployment_id:$deployment,job_variables:null,schedule_after:60,parameters:{controller_id:$controller,runtime:$runtime[0],- config:({queue:"events",max_items:3} + {(if $issue then "issues" else "pull_requests" end):+ config:({queue:"events",max_items:3,+ sender:{"__prefect_kind":"jinja",template:"{{ event.resource[\"github.sender.login\"] }}"}}+ + {(if $issue then "issues" else "pull_requests" end):{"__prefect_kind":"json",value:{"__prefect_kind":"jinja",template:"[{{ event.resource[\"github.number\"]|int }}]"}}})}}],actions_on_trigger:[],actions_on_resolve:[]}' > "$scratch/automation-$kind.json"echo "automation $kind $(upsert automations "$scratch/automation-$kind.json")"doneif [[ -n $notify ]]; then- jq -n --arg controller "$controller" --arg notify "$notify" '- {name:"fastmcp-triage-run-started",description:"Announce issues admitted to the triage controller; empty intake runs stay quiet",enabled:true,- trigger:{type:"event",posture:"Reactive",threshold:1,within:0,expect:["prefect.flow-run.Running"],- match:{"prefect.resource.id":"prefect.flow-run.*","prefect.resource.name":"fastmcp-stack-intake-*"},- match_related:{"prefect.resource.role":"deployment","prefect.resource.id":("prefect.deployment." + $controller)},+ jq -n --arg notify "$notify" '+ {name:"fastmcp-triage-outcome",description:"Post issues a finished intake left for a maintainer; intakes with nothing to decide stay quiet",enabled:true,+ trigger:{type:"event",posture:"Reactive",threshold:1,within:0,expect:["fastmcp.triage.outcome"],+ match:{"prefect.resource.id":"fastmcp.triage.intake.*"},match_related:{},after:[],for_each:["prefect.resource.id"]},actions:[{type:"send-notification",block_document_id:$notify,- subject:"",- body:"Accepted for triage: {% set ns = namespace(sep=\"\") %}{% for group in flow_run.parameters.batch.groups %}{% for item in group[\"items\"] %}{{ ns.sep }}<https://github.com/PrefectHQ/fastmcp/issues/{{ item.issue_number }}|#{{ item.issue_number }}>{% set ns.sep = \", \" %}{% endfor %}{% endfor %}\n<{{ flow_run|ui_url }}|Follow triage>"}],+ subject:"",body:"{{ event.payload.text }}"}],actions_on_trigger:[],actions_on_resolve:[]}' > "$scratch/automation-notify.json"echo "automation notify $(upsert automations "$scratch/automation-notify.json")"+ # The outcome notice replaced this run-start notice.+ jq -n '{limit:200}' > "$scratch/retired.filter"+ api POST /automations/filter --data "@$scratch/retired.filter" \+ | jq -r '.[] | select(.name == "fastmcp-triage-run-started") | .id' \+ | while read -r retired; do+ api DELETE "/automations/$retired" >/dev/null+ echo "removed fastmcp-triage-run-started $retired"+ donefi;;alerts)diff --git a/.github/agentic/tests/test_agentic_backlog.py b/.github/agentic/tests/test_agentic_backlog.pyindex 6b142da29..883c7e3c1 100644--- a/.github/agentic/tests/test_agentic_backlog.py+++ b/.github/agentic/tests/test_agentic_backlog.py@@ -474,6 +474,9 @@ def test_finish_commits_policy_decisions_saved_by_an_older_controller()assert state["completed"] == [1]assert state["review"]["bins"]["decisions"] == [policy_outcome(1, legacy)]+ assert state["issues"] == [+ {"issue_number": 1, "title": "Report 1", "author": "reporter"}+ ]assert checkpoint(config.scope()) == (owner, state)diff --git a/.github/agentic/tests/test_agentic_events.py b/.github/agentic/tests/test_agentic_events.pyindex 34eafb281..c2cd9aada 100644--- a/.github/agentic/tests/test_agentic_events.py+++ b/.github/agentic/tests/test_agentic_events.py@@ -13,6 +13,9 @@ from prefect.server.utilities.user_templates import (register_user_template_filters,render_user_template_sync,)+from prefect.utilities.schema_tools.hydration import HydrationContext, hydrate++from flows.agentic_backlog import IntakeROOT = Path(__file__).resolve().parents[1]@@ -222,53 +225,49 @@ def test_failure_alert_shows_the_cause_and_one_run_link(automations):assert failed.startswith("❌ triage failed before finishing\nboom\n")-def test_notification_announces_admitted_issues_only(automations):- configs, controller, intake = automations- config = configs["fastmcp-triage-run-started"][email protected]("kind", ["issue", "pr"])+def test_launch_passes_the_event_sender_to_intake(automations, kind):+ configs, _, _ = automations+ event = github_event(configs, kind=kind)+ parameters = hydrate(+ configs["fastmcp-triage-on-github-" + kind]["actions"][0]["parameters"],+ HydrationContext(+ raise_on_error=True, render_jinja=True, jinja_context={"event": event}+ ),+ )+ config = Intake.model_validate(parameters["config"])+ target = "issues" if kind == "issue" else "pull_requests"+ assert config.sender == "zzstoatzz"+ assert getattr(config, target) == [6089]+ # The sender does not split the shared event queue.+ assert config.scope() == Intake(queue="events", **{target: [6089]}).scope()+++def test_outcome_notification_posts_the_emitted_text_verbatim(automations):+ configs, _, _ = automations+ assert "fastmcp-triage-run-started" not in configs+ config = configs["fastmcp-triage-outcome"]trigger = AutomationCore.model_validate(config).trigger- run_id = str(uuid4())+ text = (+ "<https://github.com/PrefectHQ/fastmcp/issues/6344|#6344> A <b> title"+ " · @reporter → close? Promotional\n"+ "<https://github.com/PrefectHQ/fastmcp/issues/6349|#6349> → needs repro info"+ )- def event(deployment):+ def event(name, resource):return Event.model_validate({"id": uuid4(),"occurred": datetime.now(UTC),- "event": "prefect.flow-run.Running",- "resource": {- "prefect.resource.id": "prefect.flow-run." + run_id,- "prefect.resource.name": "fastmcp-stack-intake-" + run_id,- },- "related": [- {- "prefect.resource.id": "prefect.deployment." + deployment,- "prefect.resource.role": "deployment",- }- ],+ "event": name,+ "resource": {"prefect.resource.id": resource},+ "payload": {"text": text},})- assert not trigger.covers(event(intake))- assert trigger.covers(event(controller))- register_user_template_filters(- {"ui_url": lambda run: "https://app.prefect.cloud/runs/" + run["id"]}- )- message = render_user_template_sync(- config["actions"][0]["body"],- {- "flow_run": {- "id": run_id,- "parameters": {- "batch": {- "groups": [- {"items": [{"issue_number": 123}, {"issue_number": 456}]},- ]- }- },- },- },- )- assert message == (- "Accepted for triage: <https://github.com/PrefectHQ/fastmcp/issues/123|#123>, "- "<https://github.com/PrefectHQ/fastmcp/issues/456|#456>\n"- f"<https://app.prefect.cloud/runs/{run_id}|Follow triage>"- )+ outcome = event("fastmcp.triage.outcome", f"fastmcp.triage.intake.{uuid4()}")+ assert trigger.covers(outcome) and trigger.expects(outcome.event)+ other = event("prefect.flow-run.Running", f"prefect.flow-run.{uuid4()}")+ assert not (trigger.covers(other) and trigger.expects(other.event))+ body = config["actions"][0]["body"]+ assert render_user_template_sync(body, {"event": outcome}) == textdiff --git a/.github/agentic/tests/test_agentic_outcome.py b/.github/agentic/tests/test_agentic_outcome.pynew file mode 100644index 000000000..f67b97df4--- /dev/null+++ b/.github/agentic/tests/test_agentic_outcome.py@@ -0,0 +1,206 @@+import subprocess+from uuid import uuid4++import pytest+from pydantic import ValidationError++import flows.agentic_triage as triage+from flows.agentic_backlog import Intake+from flows.agentic_outcome import outcome_lines, subjects+from flows.agentic_triage import announce, maintainer++URL = "https://github.com/PrefectHQ/fastmcp/issues/"++# Trimmed from retained controller review bins.+REVIEW = {+ "bins": {+ "existing_review": [+ {+ "issue_number": 6303,+ "route": {+ "route": "review_existing",+ "pull_requests": [+ {+ "number": 6309,+ "held": False,+ "merged": False,+ "state": "closed",+ }+ ],+ },+ "verification": [+ {"pr_number": 6309, "status": "verification_recorded"}+ ],+ "status": "verification_recorded",+ "merge_ready": False,+ }+ ],+ "decisions": [+ {+ "issue_number": 6316,+ "decision": "maintainer",+ "reason": "The report describes a credible production limitation.",+ "question": "Should FastMCP add and maintain a supported TasksExtension customization seam for alternate Docket Workers, given the reported ElastiCache Serverless Valkey limitation?",+ "verification_prs": [],+ },+ {+ "issue_number": 6295,+ "reason": "Security-labeled report requires restricted review",+ "route": {"route": "restricted_review"},+ },+ ],+ "pruning": [+ {+ "issue_number": 6344,+ "decision": "prune",+ "reason": "The request is promotional rather than a FastMCP defect. Maintaining vendor-specific instructions would create drift.",+ "question": "Confirm whether to close this promotional catalog request.",+ "verification_prs": [],+ }+ ],+ "evidence": [{"issue_number": 6400, "reason": "Needs a concrete reproduction"}],+ "unchanged": [{"issue_number": 6401, "reason": "Closed"}],+ "operational": [{"issue_number": 6402, "reason": "Verification setup failed"}],+ }+}+ISSUES = [+ {+ "issue_number": 6303,+ "title": "A proxy served over stdio forwards only some of the backend's `ctx.log()` messages",+ "author": "alpaylan",+ },+ {+ "issue_number": 6316,+ "title": "fastmcp-tasks: let TasksExtension run a custom docket Worker",+ "author": "rob-archivium",+ },+ {"issue_number": 6295, "title": "Redirect <URI> & helpers", "author": "alpaylan"},+ {"issue_number": 6344, "title": "Add CrakSEO MCP connect skills", "author": None},+]+++def test_outcome_lists_only_items_waiting_on_a_maintainer():+ assert outcome_lines(REVIEW, ISSUES) == [+ f"<{URL}6303|#6303> A proxy served over stdio forwards only some of t… · @alpaylan → review PR #6309",+ f"<{URL}6316|#6316> fastmcp-tasks: let TasksExtension run a custom do… · @rob-archivium → Should FastMCP add and maintain a supported TasksExtension…",+ f"<{URL}6295|#6295> Redirect <URI> & helpers · @alpaylan → Security-labeled report requires restricted review",+ f"<{URL}6344|#6344> Add CrakSEO MCP connect skills → close? The request is promotional rather than a FastMCP defect.",+ f"<{URL}6400|#6400> → needs repro info",+ ]+++def test_outcome_prefers_verified_then_open_pull_requests():+ def line(item):+ return outcome_lines({"bins": {"existing_review": [item]}}, [])[0]++ route = {+ "pull_requests": [+ {"number": 1, "state": "closed"},+ {"number": 2, "state": "open"},+ ]+ }+ verified = [{"pr_number": n} for n in (5, 3, 5, 4, 6)]+ assert line({"issue_number": 9, "route": route}).endswith("→ review PR #2")+ assert line({"issue_number": 9, "route": route, "verification": verified}).endswith(+ "→ review PRs #5, #3, #4"+ )+ assert line({"issue_number": 9, "route": {}}).endswith(+ "→ review the linked contribution"+ )+++def test_outcome_caps_the_message():+ many = {"bins": {"evidence": [{"issue_number": n} for n in range(1, 10)]}}+ lines = outcome_lines(many, [])+ assert len(lines) == 6+ assert lines[-1] == "…and 4 more in the review bins"+ assert (+ outcome_lines({"bins": {"evidence": many["bins"]["evidence"][:6]}}, [])[-1]+ == f"<{URL}6|#6> → needs repro info"+ )+++def test_subjects_come_from_evidence_with_inventory_fallback(evidence):+ originals = {+ 1: {**evidence, "issue": {**evidence["issue"], "title": "From evidence"}},+ 2: evidence,+ }+ pending = [+ {"issue_number": n, "title": f"Report {n}", "attempts": 0} for n in (1, 2, 3)+ ]+ assert subjects(originals, pending) == [+ {"issue_number": 1, "title": "From evidence", "author": "reporter"},+ {"issue_number": 2, "title": "Report 2", "author": "reporter"},+ {"issue_number": 3, "title": "Report 3", "author": None},+ ]+++ "review,emitted",+ [+ (REVIEW, True),+ ({"bins": {"unchanged": REVIEW["bins"]["unchanged"]}}, False),+ ({"bins": {"operational": REVIEW["bins"]["operational"]}}, False),+ (None, False),+ ],+)+def test_announce_emits_only_when_a_maintainer_is_needed(monkeypatch, review, emitted):+ calls = []+ monkeypatch.setattr(triage, "emit_event", lambda **event: calls.append(event))+ owner = uuid4()+ announce(owner, {"review": review, "issues": ISSUES})+ if not emitted:+ assert calls == []+ return+ assert calls == [+ {+ "event": "fastmcp.triage.outcome",+ "resource": {"prefect.resource.id": f"fastmcp.triage.intake.{owner}"},+ "payload": {"text": "\n".join(outcome_lines(REVIEW, ISSUES))},+ }+ ]+++ "grant,expected",+ [+ ({"permission": "admin", "role_name": "admin"}, True),+ ({"permission": "write", "role_name": "maintain"}, True),+ ({"permission": "write", "role_name": "write"}, True),+ ({"permission": "read", "role_name": "triage"}, False),+ ({"permission": "read", "role_name": "read"}, False),+ ],+)+def test_maintainer_senders_have_write_access(grant, expected):+ paths = []++ def read(path):+ paths.append(path)+ return grant++ assert maintainer("zzstoatzz", read) is expected+ assert paths == ["repos/PrefectHQ/fastmcp/collaborators/zzstoatzz/permission"]+++ "error",+ [+ RuntimeError("gh api exited 1: HTTP 403"),+ subprocess.TimeoutExpired("gh", 60),+ ValueError("Expecting value"),+ ],+)+def test_permission_lookup_failure_still_triages(error):+ def read(path):+ raise error++ assert maintainer("contributor", read) is False+ assert maintainer("contributor", lambda path: None) is False+++def test_intake_sender_is_a_github_login():+ assert Intake().sender is None+ assert Intake(sender="zzstoatzz").sender == "zzstoatzz"+ for invalid in ("", "-leading", "has space", "bot[bot]"):+ with pytest.raises(ValidationError):+ Intake(sender=invalid)