π The fast, Pythonic way to build MCP servers and clients.
Remove the unused triage mutation batch (#6208)
nate nowackc3223c35a0ac
diff --git a/.github/agentic/README.md b/.github/agentic/README.mdindex 9f68d7cb7..ac725eea5 100644--- a/.github/agentic/README.md+++ b/.github/agentic/README.md@@ -123,8 +123,7 @@ reviews, evidence, pruning proposals, maintainer decisions or operational failurFork PRs are reviewed in place. Adoption and supersession require a maintainer'sdecision, with original authorship and issue credit preserved. Closed PRs areevidence: distinguish assignment-gate closure from explicit maintainer rejection-or supersession. See [maintenance history](docs/fastmcp-maintenance-history.md) and-[architecture decisions](docs/agentic-stack-architecture.md).+or supersession.Existing-contribution assessments dispatch to `cloud-contribution-verification`.Assessment selects at most three candidates in `verification_prs`, independently@@ -367,51 +366,13 @@ ignored on retry. Exhausted delivery failures retain the published PR receipt anoperational failure rather than discarding the useful patch or claiming review delivery.-### Reviewing mutation batches--Each review queue also retains a `fastmcp-mutation-batch/1` JSON artifact under-`<batch-id>-mutation-batch`. Read one with `agentic_stack.sh mutations <controller-run-id>`.-The queue presents the exact proposed target, action, revisions, public comment or-assignee, source runs, scope, norm evidence and remaining gates. Conflicting proposals-for one target are blocked. No command in this path executes the proposals.--The existing independent triage reviewer may propose assignment, localized PR finishing,-PR review, duplicate PR consolidation, duplicate/completed issue closures or a closure backed by settled policy. Assignment-requires explicit public-history and reporter-claim review; passing tests alone cannot-qualify a contributor. Closure candidates now receive that same independent review.-A merged reference alone cannot establish that the whole report is fixed: current-fix,-revert and scope checks remain explicit. Missing canonical or merged-fix identities,-negative norm checks, existing owners, security restrictions and holds block proposals.-Duplicate automation and human interventions retain their existing authority.--PR review/finishing proposals retain static checks, current CI, contributor credit and-batch composition as separate gates before merge. Older retained verification outputs-project to concrete per-PR review or regression-repair steps; their prose is never parsed-into assignments or closures. Every proposal requires approval and a fresh claimed-execution against its recorded evidence and referenced resolution snapshots.--The retained-intake digest identifies the immutable original snapshot; its normalized-`evidence_revision` supports freshness comparisons without collection-time churn.-Acknowledged App review receipts are carried so only those exact own reviews can be-excluded. Resolution fingerprints omit unrelated repository counters. The expanded-Markdown view uses `<batch-id>-mutation-review-queue`, preserving older queue artifacts.--PR consolidation uses explicit `close_pr` proposals with a named `canonical_pr` and-both target and canonical revisions. The independent reviewer must compare coverage,-read prior closed-PR discussions and preserve earlier maintainer canonical choices;-matching titles or a newer pair of open PRs are not selection evidence. Both heads need-retained verification. An open canonical PR is allowed; no PR is closed automatically.--Assignment proposals always retain a live `platform_assignment_eligibility` gate.-The executing maintainer must check repository assignee eligibility (HTTP 204), then-read back issue assignees: `gh issue edit` can exit successfully while ignoring an-ineligible nonparticipant. Public-history qualification and reporter ownership do not-establish platform eligibility. No automatic gate bypass or claim comment is introduced.--Closed unmerged canonical PRs retain a reopen/coordination gate; administrative closure-is not a rejection. Bulk proposals block canonical closure chains/cycles and assigning-a contribution that the same batch proposes closing. Resolve the surviving canonical-before approval rather than applying individually plausible actions together.+### Maintainer review queue++Each controller retains its review bins as `<batch-id>-review-bins` (read one with+`agentic_stack.sh results <controller-run-id>`) and a Markdown view as+`<batch-id>-triage-queue`. The independent triage reviewer's disposition, including any+assignment or closure it recommends, stays in each item's `adversarial_review`. Nothing+in this path assigns, closes or merges; the maintainer acts on GitHub directly.Evidence collection follows at most three one-hop, same-repository canonical orsuperseding PR hints from repository-associated human discussion. It verifies eachdiff --git a/.github/agentic/docs/agentic-stack-architecture.md b/.github/agentic/docs/agentic-stack-architecture.mddeleted file mode 100644index 9e3b79a09..000000000--- a/.github/agentic/docs/agentic-stack-architecture.md+++ /dev/null@@ -1,111 +0,0 @@-# Stack controller architecture--Design decisions from Nate's requested source review on October 21, 2026.-These refine the approved stack workflow; they do not describe completed Cloud-integration. The first implementation remains a bounded batch of ordinary-Prefect tasks plus Agentic Workflows for judgment.--## Bind decisions to the state that justified them--Microscope gives mutable debugger state one owner and publishes immutable-snapshots. Its execution identity names an accepted operation; its stop identity-names the observed state. `validate_public_stop` rejects a supplied obsolete-stop ID, and a real debugger test verifies that jumping creates a new stop and-rejects a later command carrying the old ID.--Apply that boundary here: agents return typed proposals; the deterministic-controller owns routing, budget admission, and publication. A review identifies-the issue/contribution evidence revision, policy and skill revisions, validated-artifact, and exact parent/head chain. Recollect the facts required for that-action before publication. A new claim, relevant comment, hold label, competing-contribution, or changed parent/head invalidates the affected decision. An-approval being recent is insufficient. A validation run ID identifies an attempt;-it is not interchangeable with the identity of the validated bytes.--Keep immutable skills, source and patch artifacts separately from changing-GitHub observations. Define the evidence fields required by each decision before-optimizing revision hashes. The current whole-snapshot hash is conservative;-do not remove fields merely to improve cache hit rate.--Microscope also separates cheap state summaries from expensive inspection. The-notes' bounded-scan lesson makes this directly relevant to cost: fetching six-items is not cheap if discovering them requires inspecting the entire backlog.-Use bounded metadata intake, then load discussion, review and CI details only for-the selected handler. Preserve all-state contribution discovery and explicit-coverage markers. Unfetched, truncated, failed, and absent are different states;-missing evidence must never become a cheap negative answer.--The current new collector eagerly loads PR reviews/checks and stack inventory.-Split its routing envelope from handler detail before scaling intake. Existing-labels remain evidence owned by the repository's bots; this controller must not-invent or manually apply workflow labels.--## Commit evidence before advancing progress--Stream holds its cursor behind unfinished sequences and fails the pipeline when-cursor persistence fails. Its admission script verifies a receipt for an exact-image digest. Together these provide the useful rule: progress describes a-verified durable boundary, rather than work that was started or appeared to finish.--For our pipeline, collected, proposed, validated, reviewed and published are-separate facts with retained evidence. Validation must durably retain the exact-Git chain and its checks before a later stage may consume it. Publication is-complete only after GitHub readback verifies branch heads, PR bases and ordered-native stack membership. A green orchestration run alone does not establish a-reviewable stack.--Before external writes, retain a stable publication identity and the intended-refs, commits and membership. A timeout leaves an unknown outcome. Reconcile it-through reads and recover the same operation instead of creating a second stack.-Keep partial publication visible and resumable. Publication and abandonment must-not both succeed for one operation; a late worker cannot revive an abandoned one.-Use enforced execution deadlines and ownership checks at the write boundary.-An expired heartbeat alone does not prove remote work stopped or free its budget.--The local implementation retains exact commits in a bundle, stores immutable-Prefect artifacts, binds independent review to the validated chain, and reconciles-partial publication. Tests use real Git, an HTTP fault server, and a temporary-Prefect server: lost responses after either PR or stack creation recover the same-objects; changed holds and cancelled ownership block further writes. A resumed-batch restores completed group outcomes instead of repeating them. These component-checks do not establish the full managed controller's runtime behavior. Verify-that boundary in the authorized Cloud/GitHub trial, including cancellation while-a child run is active.--## Scope--The notes explicitly distinguish portable primitives from someone else's-constraints. We need revision checks, durable receipts and recoverable effects.-We do not need Stream's storage engine, a debugger-style runtime, a new general-agent framework, or a full deterministic simulator to process the first batch.-Keep Prefect's changing plan/model/result APIs in small adapters around ordinary-Python policy. Add abstractions only when a demonstrated second use requires them.--## Source record--Read source and behavioral tests, not only project descriptions. Stream and-notes were inspected in their existing local checkouts; Microscope was refreshed-through the librarian checkout. Existing unrelated local changes were untouched.--- Stream at `d1a3118074c7bf72db1a66f1f01f46b79b3b109a`:- [repository](https://tangled.org/zat.dev/stream),- `docs/architecture.md`, `docs/invariants.md`,- `src/internal/ingest/pipeline.zig` (`cursorAfterBatch`, cursor callback ordering),- `src/internal/ingest/backfill/lifecycle.zig`, and `scripts/admit`.- The current cursor implementation uses the minimum inflight sequence minus one,- otherwise the global accepted high-water mark; some prose describes a batch- maximum instead. The code is the evidence for this mechanism.-- Notes at `2c2ed474eab6b26b94423c0fb984ba55d0cc98ed`:- [repository](https://tangled.org/zzstoatzz.io/notes),- `systems/prior-art-encodes-someone-elses-constraints.md`,- `systems/watermark-semantics.md`, `systems/ownership-must-expire.md`,- `systems/publish-then-free.md`, `operations/bounded-scans.md`,- `systems/stateful-property-testing.md`, and- `systems/deterministic-simulation-testing.md`.-- Microscope at `1ef7c29dacf6c26d3cd8f553c947307f46ce9de9`:- [architecture](https://github.com/microscope-dev/microscope/blob/1ef7c29dacf6c26d3cd8f553c947307f46ce9de9/dev/architecture.md),- [state validation](https://github.com/microscope-dev/microscope/blob/1ef7c29dacf6c26d3cd8f553c947307f46ce9de9/src/backend/linux.rs#L2937),- [stale-operation test](https://github.com/microscope-dev/microscope/blob/1ef7c29dacf6c26d3cd8f553c947307f46ce9de9/tests/debugger/writes.rs#L344),- and `dev/simulator.md`. `jcalabro/microscope` redirects to this repository.- Some internal operations permit an omitted stop ID; the lesson is explicit- validation of supplied state identity, not a claim that every API requires it.diff --git a/.github/agentic/docs/fastmcp-maintenance-history.md b/.github/agentic/docs/fastmcp-maintenance-history.mddeleted file mode 100644index 9d23c7e9f..000000000--- a/.github/agentic/docs/fastmcp-maintenance-history.md+++ /dev/null@@ -1,26 +0,0 @@-# Maintenance history carried into the stack workflow--Nate approved the visual design on October 21, 2026, and requested Jeremiah's historical process before implementation. Reviewed local history against GitHub main `d92276995f2f7b34dedbc7a8dfa8a4fa2ea4d013`, current labels through `gh label list`, original PR bodies, and current workflow scripts.--## Preserve--- **Contract before fix.** Jeremiah added the explicit contract gate in [#4214](https://github.com/PrefectHQ/fastmcp/pull/4214): reproducible behavior is not necessarily a defect. Preserve that gate, while applying current skills' requirement to inspect docs, protocol, history and maintainer decisions before escalating. Do not resurrect the older habit of asking the maintainer whenever code alone is ambiguous.-- **Closed contributions remain evidence.** [#4780](https://github.com/PrefectHQ/fastmcp/pull/4780) requires reading associated closed external PRs, including comments and timeline. Gate closure does not mean a rejected implementation. Preserve useful code and attribution; avoid competing replacement PRs by default.-- **Explicit supersession remains authoritative.** Nate [closed #5656 in favor of #5779](https://github.com/PrefectHQ/fastmcp/pull/5656#issuecomment-6296713451), preserving the earlier contribution and credit. Its earlier dependency on #5671 does not authorize reviving that pair to manufacture a stack. Distinguish an administrative gate closure from a maintainer's recorded selection among overlapping proposals.-- **Human intervention persists.** [#2981](https://github.com/PrefectHQ/fastmcp/pull/2981) repaired repeated duplicate closures. Current duplicate automation uses `potential-duplicate`, a three-day cooldown, any subsequent human comment, negative/confused reactions, and prior auto-closure evidence. These can stop closure; the temporary label is consumed. Do not recalculate a rejected duplicate verdict on every scan. Record adjudication and evidence revision.-- **Missing reproduction is a separate lifecycle.** `needs MRE` drives a seven-day author-inactivity closer; maintainer-authored issues are exempt. `needs more info` does not invoke the same timer. Current bot retains comments and edit evidence; label presence alone is not permission to close. The new trial produces recommendations and leaves existing closers responsible for their own actions.-- **Gate ownership matters.** [#4518](https://github.com/PrefectHQ/fastmcp/pull/4518) documents a label replacement race that erased `missing-issue-link` and broke reopening. Preserve labels from other owners. `missing-issue-link`, `bypass-issue-check`, `trusted-contributor`, and `prs welcome` are protected by the current triage helper. Do not infer distrust from a gate label or remove it as cleanup.-- **Community participation has explicit routes.** [#4557](https://github.com/PrefectHQ/fastmcp/pull/4557) introduced issue-level `prs welcome` to waive assignment, not the issue-link requirement. It deliberately replaced misleading `good first issue` expectations. Assignment can reopen a gated PR; manual reopen/removal of the gate label grants sticky bypass. Current [#5048](https://github.com/PrefectHQ/fastmcp/pull/5048) keeps linked PRs open while awaiting assignment, superseding the older close-all behavior.-- **Label precision and ownership.** [#4654](https://github.com/PrefectHQ/fastmcp/pull/4654) explicitly removed guessed labels and label suggestions from PR prose. Marvin owns category/area classification; the stack controller consumes actual labels and records internal bins in artifacts. Release categories depend on exact names, including `breaking change`, `bug`, `enhancement`, and `security`. Live `breaking` is not equivalent to `breaking change`; do not silently normalize or mutate it.-- **Intentional automation triggers.** [#3124](https://github.com/PrefectHQ/fastmcp/pull/3124) constrained automatic issue triage and guarded the human-applied `triage-martian` trigger. Do not apply this label from an agent or launch a second competing fixer. Snapshot ongoing activity and ownership before dispatch/publication.-- **Bounded small-model work is established precedent.** Jeremiah tried Haiku for narrow labeling/dedupe in [#1613](https://github.com/PrefectHQ/fastmcp/pull/1613). This supports trying cheap models, not assuming their current quality or price. Measure accepted output and human corrections. Later model upgrades do not establish why the experiment changed without further evidence.-- **Silence is often the correct public output.** Labeling/dedupe prompts suppress unsolicited commentary, except narrowly defined messages. Keep detailed traces private and public descriptions concise. Review real bot findings on their merits, cap speculative repair loops, and preserve issue-author credit ([#5410](https://github.com/PrefectHQ/fastmcp/pull/5410)).-- **A green orchestration run is insufficient.** [#4555](https://github.com/PrefectHQ/fastmcp/pull/4555), [#4560](https://github.com/PrefectHQ/fastmcp/pull/4560), and [#4645](https://github.com/PrefectHQ/fastmcp/pull/4645) fixed silent tool-permission/sandbox failures. Check actual evidence, test artifacts, PRs and stack membership; keep operational failures distinct from negative issue verdicts.--## Encode with gh and existing labels--Collect paginated REST issue/comment/timeline/PR/review/check/stack data using `gh api`, preserving failures rather than treating missing pages as empty. Read all-state linked PRs; bounded search is additional evidence, not proof of absence. Snapshot live labels and exact source SHAs. Use area/category labels to narrow coherent batches, with unlabelled items still eligible for classification. Treat priority labels as hints, not proof of severity or rejection.--Deterministically route existing PRs to review; human hold/draft/DO NOT MERGE signals to held review; gate labels to contribution-state handling; `needs MRE` and `potential-duplicate` to their evidence/decision lanes. Labels do not override newer comments, supported-version evidence, or the intended contract. Refresh them immediately before publication. Security goes to restricted review; an auth label alone is not a security verdict.--No new workflow-state labels, manual label changes, bypasses, assignment changes, automatic comments/closures, merges, or schedules are needed for the first trial. The controller's persistent ledger tracks claims, costs and internal decisions without overloading community-facing labels.diff --git a/.github/agentic/flows/agentic_mutation_batch.py b/.github/agentic/flows/agentic_mutation_batch.pydeleted file mode 100644index 2bd557ece..000000000--- a/.github/agentic/flows/agentic_mutation_batch.py+++ /dev/null@@ -1,664 +0,0 @@-from __future__ import annotations--import re-from collections import Counter, defaultdict-from collections.abc import Callable-from copy import deepcopy--from flows.agentic_intake import directly_addresses, duplicate_intervention, held-from flows.agentic_mutation_models import MutationRecommendation-from flows.agentic_stack import digest-from flows.agentic_stack_policy import publication_revision--REPOSITORY = "PrefectHQ/fastmcp"-REQUIRED = {- "assign_issue": {- "scope_contract",- "prior_discussion",- "public_history",- "reporter_first_claim",- "bot_feedback",- },- "finish_pr": {"scope_contract", "prior_discussion", "bot_feedback"},- "review_pr": {"scope_contract", "prior_discussion", "bot_feedback"},- "close_duplicate": {"scope_contract", "prior_discussion", "canonical_equivalence"},- "close_completed": {- "scope_contract",- "prior_discussion",- "current_fix_and_reverts",- },- "close_settled": {"scope_contract", "prior_discussion", "settled_policy"},- "close_pr": {- "scope_contract",- "prior_discussion",- "reporter_first_claim",- "bot_feedback",- "maintainer_direction",- "coverage_parity",- },-}---def resolution_snapshot(value: dict) -> dict:- snapshot = {- name: value[name]- for name in (- "number",- "title",- "body",- "state",- "updated_at",- "merged",- "merged_at",- "merge_commit_sha",- )- if name in value- }- for name in ("head", "base"):- if isinstance(value.get(name), dict):- side = value[name]- snapshot[name] = {- "sha": side.get("sha"),- "ref": side.get("ref"),- "repository": (side.get("repo") or {}).get("full_name"),- }- snapshot["labels"] = sorted(- label.get("name") if isinstance(label, dict) else label- for label in value.get("labels", [])- )- snapshot["assignees"] = sorted(- person.get("login") if isinstance(person, dict) else person- for person in value.get("assignees", [])- )- return snapshot---def qualify_recommendations(- outcome: dict,- review: dict,- run_id: str,- evidence: dict | None,- read: Callable[[str], dict | None] | None = None,-) -> list[dict]:- evidence = evidence or {}- issue = evidence.get("issue", {})- prs = {pr["number"]: pr for pr in evidence.get("prs", [])}- intervention = any(- event.get("event") == "reopened" for event in evidence.get("timeline", [])- ) or duplicate_intervention(- {- "comments": evidence.get("comments", []),- "timeline": evidence.get("timeline", []),- "reactions": evidence.get("reactions", []),- }- )- route = outcome.get("route")- if not isinstance(route, dict):- route = {}- resolved = []- reference_cache: dict[str, dict] = {}- for raw in review.get("recommendations", []):- proposal = MutationRecommendation.model_validate(raw).model_dump(mode="json")- action, number = proposal["action"], proposal["target_number"]- is_pr = action in {"finish_pr", "review_pr", "close_pr"}- pr = prs.get(number if is_pr else proposal.get("related_pr"))- checks = {- item["check"] for item in proposal["norm_evidence"] if item["satisfied"]- }- gates = {- check: "passed" if check in checks else "required"- for check in sorted(REQUIRED[action])- }- gates.update(- independent_review="passed"- if run_id and review.get("decision") != "environment_failure"- else "required",- complete_intake="passed"- if evidence.get("complete") is True and evidence.get("schema_version") == 2- else "required",- target_identity="passed"- if (pr if is_pr else number == issue.get("number"))- else "required",- evidence_binding="passed"- if proposal["evidence_sha256"] == digest(evidence)- else "required",- scope_notes="passed" if proposal["scope_notes"].strip() else "required",- fresh_evidence="required"- if outcome.get("status")- in {"stale", "baseline_changed", "environment_failure", "refresh_failed"}- else "passed",- )- gates["action_disposition"] = (- "passed"- if review.get("decision")- == (- "propose_closure"- if action in {"close_duplicate", "close_completed", "close_settled"}- else "review_existing"- )- else "required"- )- if issue.get("state") != "open" or "security" in issue.get("labels", []):- gates["open_unrestricted_issue"] = "required"- if review.get("findings") and action in {- "close_duplicate",- "close_completed",- "close_settled",- }:- gates["unresolved_findings"] = "required"- gates["baseline_identity"] = (- "passed"- if re.fullmatch(r"[a-f0-9]{40}", evidence.get("base_sha") or "")- else "required"- )- references = []- if is_pr or action == "assign_issue":- gates["target_revision"] = (- "passed"- if pr- and proposal["head_sha"]- and proposal["base_sha"]- and proposal["head_sha"] == pr["head_sha"]- and proposal["base_sha"] == pr["base_sha"]- else "required"- )- gates["contribution_hold"] = (- "required" if pr is None or held(pr) else "passed"- )- if action == "assign_issue":- gates["platform_assignment_eligibility"] = "required"- author = (pr or {}).get("user", {}).get("login")- verified = next(- (- check- for check in outcome.get("verification", [])- if check.get("pr_number") == proposal["related_pr"]- and check.get("head_sha") == proposal["head_sha"]- and check.get("status") == "verification_recorded"- ),- {},- )- gates["executed_verification"] = (- "passed"- if verified.get("tests", {}).get("head", {}).get("status")- == "passed"- and not verified.get("comparison", {}).get("regressed_tests")- else "required"- )- gates["assignee_identity"] = (- "passed"- if author and proposal["assignee"] == author- else "required"- )- gates["existing_ownership"] = (- "passed"- if not issue.get("assignees") or issue["assignees"] == [author]- else "required"- )- gates["linked_unmerged_contribution"] = (- "passed"- if pr- and not pr.get("merged")- and directly_addresses(pr.get("body") or "", number)- else "required"- )- if issue.get("assignees") == [author]:- gates["assignment_needed"] = "required"- if (- pr- and pr.get("state") != "open"- and (- not any(- "<!-- require-issue-link -->" in c.get("body", "")- and c.get("user", {}).get("type") == "Bot"- for c in pr.get("comments", [])- )- or next(- (- (event.get("actor") or {}).get("type")- for event in reversed(pr.get("timeline", []))- if event.get("event") == "closed"- ),- None,- )- != "Bot"- )- ):- gates["assignment_gate_history"] = "required"- else:- gates["open_contribution"] = (- "passed"- if pr and pr.get("state") == "open" and not pr.get("merged")- else "required"- )- if action.startswith("close_"):- gates["public_closure_reason"] = (- "passed" if proposal["public_comment"].strip() else "required"- )- if not is_pr:- gates["existing_ownership"] = (- "required" if issue.get("assignees") else "passed"- )- if not is_pr and any(- pr.get("state") == "open" and not pr.get("merged")- for pr in prs.values()- ):- gates["active_contribution_coordination"] = "required"- if action in {"close_duplicate", "close_completed", "close_pr"}:- related = proposal[- "canonical_issue"- if action == "close_duplicate"- else "canonical_pr"- if action == "close_pr"- else "merged_pr"- ]- path = "issues" if action == "close_duplicate" else "pulls"- related_value: dict = {}- if (- related- and related != number- and read- and gates["evidence_binding"] == "passed"- ):- endpoint = f"repos/{REPOSITORY}/{path}/{related}"- if endpoint not in reference_cache:- try:- reference_cache[endpoint] = read(endpoint) or {}- except (ValueError, OSError):- reference_cache[endpoint] = {}- related_value = reference_cache[endpoint]- url = f"https://github.com/{REPOSITORY}/{'pull' if path == 'pulls' else path}/{related}"- valid = (- isinstance(related_value, dict)- and related_value.get("number") == related- and related_value.get("html_url") == url- )- if action == "close_duplicate":- valid = valid and "pull_request" not in related_value- gates["canonical_identity"] = "passed" if valid else "required"- if (- "potential-duplicate" in issue.get("labels", [])- or intervention- or route.get("human_intervention")- ):- gates["existing_duplicate_automation_or_intervention"] = "required"- elif action == "close_pr":- gates["canonical_identity"] = "passed" if valid else "required"- gates["canonical_reopen_coordination"] = (- "passed"- if related_value.get("state") == "open"- or related_value.get("merged") is True- else "required"- )- canonical_head = (related_value.get("head") or {}).get("sha")- canonical_base = (related_value.get("base") or {}).get("sha")- gates["canonical_revision"] = (- "passed"- if valid- and proposal["canonical_head_sha"]- and proposal["canonical_head_sha"] == canonical_head- and (- not proposal["canonical_base_sha"]- or proposal["canonical_base_sha"] == canonical_base- )- else "required"- )- verified = {- check["pr_number"]: check- for check in outcome.get("verification", [])- if check.get("status") == "verification_recorded"- }- target_check, canonical_check = (- verified.get(number, {}),- verified.get(related, {}),- )- gates["executed_comparison"] = (- "passed"- if target_check.get("head_sha") == proposal["head_sha"]- and canonical_check.get("head_sha")- == proposal["canonical_head_sha"]- else "required"- )- if (- canonical_check.get("comparison", {}).get("regressed_tests")- or canonical_check.get("tests", {}).get("head", {}).get("status")- != "passed"- ):- gates["canonical_behavior"] = "required"- if (- related_value.get("merged")- and "current_fix_and_reverts" not in checks- ):- gates["current_fix_and_reverts"] = "required"- else:- valid = (- valid- and related_value.get("merged") is True- and directly_addresses(related_value.get("body") or "", number)- )- gates["merged_complete_fix"] = "passed" if valid else "required"- if valid:- if "security" in [- label.get("name") if isinstance(label, dict) else label- for label in related_value.get("labels", [])- ]:- gates["restricted_resolution_evidence"] = "required"- gates["closure_reference_in_comment"] = (- "passed"- if url in proposal["public_comment"]- or re.search(- rf"(?<![\w/])#{related}(?!\d)", proposal["public_comment"]- )- else "required"- )- references.append(- {- "url": url,- "sha256": digest(resolution_snapshot(related_value)),- "updated_at": related_value.get("updated_at"),- }- )- if action == "close_settled":- policy = proposal["policy_url"] or ""- gates["settled_policy_reference"] = (- "passed"- if policy.startswith(- (f"https://github.com/{REPOSITORY}/", "https://gofastmcp.com/")- )- else "required"- )- if policy and policy not in proposal["public_comment"]:- gates["closure_reference_in_comment"] = "required"- for name in (- "static_checks",- "current_ci",- "batch_composition",- "contributor_credit",- ):- gates[name] = (- "required_before_merge"- if action in {"finish_pr", "review_pr"}- else "not_applicable"- )- required = sorted(- name for name, status in gates.items() if status == "required"- )- resolved.append(- {- "id": digest([proposal, run_id, digest(evidence), references])[:24],- "action": action,- "target": {- "kind": "pull_request" if is_pr else "issue",- "number": number,- "url": f"https://github.com/{REPOSITORY}/{'pull' if is_pr else 'issues'}/{number}",- },- "issue_number": issue.get("number", outcome.get("issue_number")),- "payload": {- key: proposal[key]- for key in (- "assignee",- "related_pr",- "canonical_issue",- "merged_pr",- "canonical_pr",- "canonical_head_sha",- "canonical_base_sha",- "policy_url",- "public_comment",- )- if proposal[key]- },- "reason": proposal["reason"],- "next_step": proposal["next_step"],- "scope_notes": proposal["scope_notes"],- "head_sha": proposal["head_sha"],- "base_sha": proposal["base_sha"],- "baseline_sha": evidence.get("base_sha"),- "evidence_sha256": digest(evidence) if evidence else None,- "evidence_kind": "retained_intake",- "evidence_revision": publication_revision(evidence)- if evidence.get("complete") and evidence.get("schema_version") == 2- else None,- "source_runs": {- "triage_review": run_id,- "verification": [- c["run_id"]- for c in outcome.get("verification", [])- if c.get("pr_number")- in {(pr or {}).get("number"), proposal.get("canonical_pr")}- ],- },- "norm_evidence": proposal["norm_evidence"],- "references": references,- "gates": gates,- "remaining_gates": required,- "before_merge": sorted(- name- for name, status in gates.items()- if status == "required_before_merge"- ),- "status": "blocked" if required else "proposed",- "approval_required": True,- "merge_ready": False,- "execution_preconditions": [- "Refresh the exact issue, PR revisions, discussion and referenced resolution evidence",- "Acquire the existing issue/PR claim",- "Respect contributor ownership, security restrictions and explicit holds",- "Obtain maintainer approval for this exact mutation",- *(- [- f"Verify GET /repos/{REPOSITORY}/assignees/{proposal['assignee']} returns 204; read back issue assignees after assignment, since a successful CLI exit can silently ignore an ineligible user"- ]- if action == "assign_issue"- else []- ),- ],- }- )- return resolved---def retained_pr_steps(item: dict, category: str) -> list[dict]:- if item.get("status") in {- "stale",- "baseline_changed",- "environment_failure",- "refresh_failed",- }:- return []- checks: list[dict] = item.get("verification", [])- generated = category == "stacks" and item.get("status") == "published"- if generated:- receipts = {- receipt["pr_number"]: receipt- for receipt in item.get("review_delivery", {}).get("posted", [])- }- checks = [- {- "pr_number": number,- "head_sha": receipts.get(number, {}).get("head_sha"),- "baseline_sha": receipts.get(number, {}).get("baseline_sha"),- "run_id": item.get("validation_run_id"),- }- for number in item.get("pull_requests", [])- ]- result = []- for check in checks:- number, head, base = (- check["pr_number"],- check.get("head_sha"),- check.get("baseline_sha"),- )- regressions = check.get("comparison", {}).get("regressed_tests", [])- action = "finish_pr" if regressions else "review_pr"- review = item.get("adversarial_review", {})- step = (- "Repair the reproduced regressions before further merge review: "- + ", ".join(regressions)- if regressions- else item.get("next_step")- or f"Review PR #{number} at the retained revisions against its linked issue and repository skills."- )- gates = {- "target_revision": "passed" if head and base else "required",- "independent_review": "passed"- if item.get("triage_review_run_id") or item.get("review_run_id")- else "required",- "target_skill_review": "required",- "static_checks": "required_before_merge",- "current_ci": "required_before_merge",- "batch_composition": "required_before_merge",- "contributor_credit": "required_before_merge",- }- if check.get("status") in {"environment_failure", "evidence_needed"}:- gates["executed_verification"] = "required"- if any(- pr.get("number") == number and pr.get("held")- for pr in item.get("route", {}).get("pull_requests", [])- ):- gates["contribution_hold"] = "required"- remaining = sorted(- name for name, status in gates.items() if status == "required"- )- result.append(- {- "id": digest([action, number, head, base, digest(item)])[:24],- "action": action,- "target": {- "kind": "pull_request",- "number": number,- "url": f"https://github.com/{REPOSITORY}/pull/{number}",- },- "issue_number": item.get("issue_number"),- "payload": {},- "reason": review.get("reason")- or item.get("assessment", {}).get("reason")- or "Retained generated patch validation and independent review are available.",- "next_step": step,- "scope_notes": "Recorded verification is evidence for review; compatibility, contribution policy and merge readiness remain separate.",- "head_sha": head,- "base_sha": base,- "baseline_sha": base,- "evidence_sha256": digest(item),- "evidence_kind": "retained_outcome",- "evidence_revision": item.get("route", {}).get("revision"),- "source_runs": {- "verification": [check["run_id"]] if check.get("run_id") else [],- "triage_review": item.get("triage_review_run_id"),- "patch_review": item.get("review_run_id"),- "validation": item.get("validation_run_id"),- },- "norm_evidence": [],- "references": [],- "gates": gates,- "remaining_gates": remaining,- "before_merge": sorted(- name- for name, status in gates.items()- if status == "required_before_merge"- ),- "status": "blocked" if remaining else "proposed",- "approval_required": True,- "merge_ready": False,- "execution_preconditions": [- "Refresh and claim this target before acting",- "Respect ownership and explicit holds",- "Obtain approval for the exact action",- ],- }- )- return result---def mutation_batch(result: dict, owner: str | None = None) -> dict:- recommendations = []- for category, items in result.get("bins", {}).items():- if category in {"operational", "unchanged"}:- continue- for item in items:- candidates = item.get("mutation_recommendations")- if not candidates:- candidates = retained_pr_steps(item, category)- for recommendation in candidates:- value = deepcopy(recommendation)- value["acknowledged_reviews"] = deepcopy(- item.get("published_reviews", [])- + item.get("review_delivery", {}).get("posted", [])- )- if item.get("status") in {- "stale",- "baseline_changed",- "environment_failure",- "refresh_failed",- }:- value["gates"]["fresh_evidence"] = "required"- value["remaining_gates"] = sorted(- set(value["remaining_gates"]) | {"fresh_evidence"}- )- value["status"] = "blocked"- recommendations.append(value)- grouped = defaultdict(list)- for item in recommendations:- grouped[(item["target"]["kind"], item["target"]["number"])].append(item)- for items in grouped.values():- if (- len(- {- digest(- {- key: item.get(key)- for key in ("action", "payload", "head_sha", "base_sha")- }- )- for item in items- }- )- > 1- ):- for item in items:- item["gates"]["conflicting_recommendations"] = "required"- item["remaining_gates"] = sorted(- set(item["remaining_gates"]) | {"conflicting_recommendations"}- )- item["status"] = "blocked"- closing = {- (item["target"]["kind"], item["target"]["number"]): item- for item in recommendations- if item["action"] in {"close_pr", "close_duplicate"}- }- for item in recommendations:- dependency = None- if item["action"] == "close_pr":- dependency = ("pull_request", item["payload"].get("canonical_pr"))- elif item["action"] == "close_duplicate":- dependency = ("issue", item["payload"].get("canonical_issue"))- elif item["action"] == "assign_issue":- dependency = ("pull_request", item["payload"].get("related_pr"))- if dependency in closing:- for conflict in (item, closing[dependency]):- conflict["gates"]["canonical_survival_or_assignment_conflict"] = (- "required"- )- conflict["remaining_gates"] = sorted(- set(conflict["remaining_gates"])- | {"canonical_survival_or_assignment_conflict"}- )- conflict["status"] = "blocked"- unique = {digest(item): item for item in recommendations}- values = sorted(- unique.values(),- key=lambda item: (- item["target"]["kind"],- item["target"]["number"],- item["action"],- ),- )- return {- "schema_version": "fastmcp-mutation-batch/1",- "batch_id": result["batch_id"],- "source_run_id": owner,- "approval_required": True,- "execution_enabled": False,- "recommendations": values,- "counts": dict(Counter(item["status"] for item in values)),- }diff --git a/.github/agentic/flows/agentic_review_queue.py b/.github/agentic/flows/agentic_review_queue.pyindex b70ed3fe8..66873eddb 100644--- a/.github/agentic/flows/agentic_review_queue.py+++ b/.github/agentic/flows/agentic_review_queue.py@@ -1,7 +1,6 @@from __future__ import annotationsimport html-import jsonimport refrom uuid import UUID@@ -9,8 +8,6 @@ from prefect.client.orchestration import get_clientfrom prefect.client.schemas.actions import ArtifactCreatefrom prefect.client.schemas.filters import ArtifactFilter, FlowRunFilter-from flows.agentic_mutation_batch import mutation_batch-def plain(value: object) -> str:if value is None:@@ -87,61 +84,6 @@ def review_markdown(result: dict) -> str:"",])- mutations = mutation_batch(result)["recommendations"]- if mutations:- lines.extend(- [- "",- "## Proposed mutations",- "",- "Every row requires maintainer approval. No mutations are executed by this queue.",- "",- "| Action | Target | Evidence | Remaining gates | Next step |",- "| --- | --- | --- | --- | --- |",- ]- )- for mutation in mutations:- target = mutation["target"]- revision = (- mutation.get("head_sha") or mutation.get("baseline_sha") or "unbound"- )- gates = (- ", ".join(mutation["remaining_gates"]) or "Approval and live preflight"- )- lines.append(- f"| {plain(mutation['action'])} | [#{target['number']}]({target['url']}) | {plain(revision)} | {plain(gates)} | {plain(mutation['next_step'])} |"- )- for mutation in mutations:- target = mutation["target"]- lines.extend(- [- "",- f"### {plain(mutation['action'])} on {plain(target['kind'])} #{target['number']}",- "",- "Reason: " + plain(mutation["reason"]),- "Scope: " + plain(mutation["scope_notes"]),- "Before merge: "- + plain(- ", ".join(mutation.get("before_merge", []))- or "Not a merge proposal"- ),- "",- ]- )- if mutation.get("payload"):- lines.extend(- [- "Proposed payload:",- "",- code_block(json.dumps(mutation["payload"], indent=2), "json"),- "",- ]- )- for check in mutation.get("norm_evidence", []):- lines.append(- f"- {plain(check['check'])} ({'passed' if check['satisfied'] else 'unmet'}): {plain(check['summary'])} Sources: {plain(', '.join(check['evidence_urls']))}"- )- lines.append("")for key, title in sections.items():items = result["bins"].get(key, [])if not items:@@ -288,15 +230,8 @@ def review_markdown(result: dict) -> str:def retain_review_queue(owner: UUID, result: dict) -> str:- retain_artifact(- owner,- f"{result['batch_id']}-mutation-batch",- mutation_batch(result, str(owner)),- "fastmcp-mutation-batch",- "Approval-required FastMCP mutation proposals; execution disabled",- )return retain_markdown(- owner, f"{result['batch_id']}-mutation-review-queue", review_markdown(result)+ owner, f"{result['batch_id']}-triage-queue", review_markdown(result))diff --git a/.github/agentic/flows/agentic_stack_controller.py b/.github/agentic/flows/agentic_stack_controller.pyindex 5aceda3ac..f7c4c5de9 100644--- a/.github/agentic/flows/agentic_stack_controller.py+++ b/.github/agentic/flows/agentic_stack_controller.py@@ -422,27 +422,11 @@ def run_batch(batch: Batch, runtime: Runtime) -> dict:{**projected, "outcome": result},f"issue-{number}-triage-review",)- mutation_reader = None- if any(- proposed["action"]- in {"close_duplicate", "close_completed", "close_pr"}- for proposed in review.get("recommendations", [])- ):- mutation_github = GitHub(secret_sync("fastmcp-triage-gh-token"))-- def mutation_reader(endpoint: str) -> dict | None:- value = mutation_github.request(endpoint)- if value is not None and not isinstance(value, dict):- raise ValueError("Expected a closure evidence object")- return value-destination, result = apply_disposition(destination,result,review,review_run,- evidence=final_evidence,- read=mutation_reader,)if runtime.publish_reviews and destination == "existing_review":try:@@ -663,18 +647,11 @@ def run_batch(batch: Batch, runtime: Runtime) -> dict:"agent_runs": calls,"usage": usage,}- proposed_issues = {- item["issue_number"]- for values in bins.values()- for item in values- if item.get("mutation_recommendations")- and isinstance(item.get("issue_number"), int)- }branches = {item.issue_number: group.branchfor group in batch.groupsfor item in group.items- if item.mode != "fix" or item.issue_number in proposed_issues+ if item.mode != "fix"}originals = {}for number in branches:diff --git a/.github/agentic/flows/agentic_triage_review.py b/.github/agentic/flows/agentic_triage_review.pyindex 993a18742..fc4b472af 100644--- a/.github/agentic/flows/agentic_triage_review.py+++ b/.github/agentic/flows/agentic_triage_review.py@@ -1,9 +1,5 @@from __future__ import annotations-from collections.abc import Callable--from flows.agentic_mutation_batch import qualify_recommendations-def requires_review(destination: str) -> bool:return destination != "operational"@@ -14,8 +10,6 @@ def apply_disposition(outcome: dict,review: dict,run_id: str,- evidence: dict | None = None,- read: Callable[[str], dict | None] | None = None,) -> tuple[str, dict]:decision = review["decision"]if decision == "prepare_fix" and outcome.get("decision") != "reproduced":@@ -49,10 +43,6 @@ def apply_disposition("triage_review_run_id": run_id,"next_step": review["next_action"],}- if review.get("recommendations"):- result["mutation_recommendations"] = qualify_recommendations(- outcome, review, run_id, evidence, read- )destination = destinations[decision]if decision == "repair_evidence":result["decision"] = "evidence_needed"diff --git a/.github/agentic/scripts/agentic_stack.sh b/.github/agentic/scripts/agentic_stack.shindex 453691fa5..51d9caa6e 100644--- a/.github/agentic/scripts/agentic_stack.sh+++ b/.github/agentic/scripts/agentic_stack.sh@@ -67,16 +67,14 @@ case "${1:-}" in> "$scratch/request.json"api POST "/deployments/$deployment/create_flow_run" --data "@$scratch/request.json";;- results|mutations)+ results)run=${2:?controller run UUID required}[[ $run =~ ^[0-9a-f-]{36}$ ]] || exit 2scratch=$(mktemp -d)trap 'rm -rf "$scratch"' EXITapi GET "/flow_runs/$run" > "$scratch/run.json"jq '{id,state_type,state_name,parameters:{batch:.parameters.batch}}' "$scratch/run.json"- suffix=review-bins- if [[ $1 == mutations ]]; then suffix=mutation-batch; fi- key=$(jq -er --arg suffix "$suffix" '.parameters.batch.id + "-" + $suffix' "$scratch/run.json")+ key=$(jq -er '.parameters.batch.id + "-review-bins"' "$scratch/run.json")jq -n --arg run "$run" --arg key "$key" \'{artifacts:{key:{any_:[$key]}},flow_runs:{id:{any_:[$run]}},limit:2}' > "$scratch/filter.json"api POST /artifacts/filter --data "@$scratch/filter.json" | jq -e 'if length==1 then .[0].data else error("Final review bins not available; inspect the run and retained stage artifacts") end'diff --git a/.github/agentic/tests/test_agentic_backlog.py b/.github/agentic/tests/test_agentic_backlog.pyindex 40cd71959..5358a1f89 100644--- a/.github/agentic/tests/test_agentic_backlog.py+++ b/.github/agentic/tests/test_agentic_backlog.py@@ -328,7 +328,7 @@ def test_queue_recovers_same_controller_and_commits_only_saved_outcomes(for artifact in client.read_artifacts(flow_run_filter=FlowRunFilter(id={"any_": [replacement]})):- if artifact.key.endswith(("-committed", "-coverage", "-review-queue")):+ if artifact.key.endswith(("-committed", "-coverage", "-triage-queue")):client.delete_artifact(artifact.id)before = len(requests)responses["/fresh/1"] = (503, {"message": "Unavailable after finalization"})diff --git a/.github/agentic/tests/test_agentic_mutation_batch.py b/.github/agentic/tests/test_agentic_mutation_batch.pydeleted file mode 100644index 7854dc342..000000000--- a/.github/agentic/tests/test_agentic_mutation_batch.py+++ /dev/null@@ -1,828 +0,0 @@-from copy import deepcopy--import pytest-from pydantic import ValidationError--from flows.agentic_mutation_batch import (- REQUIRED,- mutation_batch,- qualify_recommendations,-)-from flows.agentic_mutation_models import MutationRecommendation-from flows.agentic_review_queue import retain_review_queue, review_markdown-from flows.agentic_stack import digest-from flows.agentic_stack_plans import TriageReview-from flows.agentic_triage_review import apply_disposition--HEAD, BASE = "e" * 40, "b" * 40---def snapshot(evidence):- return {- **evidence,- "stacks": [],- "prs": [- {- "number": 12,- "head_sha": HEAD,- "base_sha": BASE,- "state": "open",- "draft": False,- "merged": False,- "title": "Repair dispatch",- "body": f"Fixes #{evidence['issue']['number']}",- "labels": [],- "user": {"login": "reporter", "type": "User"},- "comments": [],- "timeline": [],- }- ],- }---def proposal(snapshot, action="assign_issue", **updates):- return {- "action": action,- "target_number": 12- if action in {"review_pr", "finish_pr", "close_pr"}- else snapshot["issue"]["number"],- "related_pr": 12,- "head_sha": HEAD,- "base_sha": BASE,- "evidence_sha256": digest(snapshot),- "reason": "The supported dispatch bug has a sound scoped contribution.",- "next_step": "Assign reporter to the issue and verify the contribution gate reruns.",- "scope_notes": "The patch repairs dispatch and preserves explicit overrides.",- "assignee": "reporter" if action == "assign_issue" else None,- "norm_evidence": [- {- "check": check,- "satisfied": True,- "summary": f"Verified {check}; sparse public history is not a rejection reason.",- "evidence_urls": ["https://github.com/PrefectHQ/fastmcp/pull/12"],- }- for check in sorted(REQUIRED.get(action, set()))- ],- **updates,- }---def review(snapshot, action="assign_issue", **updates):- return {- "decision": "propose_closure"- if action.startswith("close_") and action != "close_pr"- else "review_existing",- "reason": "Exact supported behavior and prior discussion reviewed.",- "findings": [],- "next_action": "Act on the concrete scoped proposal after approval.",- "recommendations": [proposal(snapshot, action, **updates)],- }---def assignment_checks(snapshot):- return {- "issue_number": snapshot["issue"]["number"],- "verification": [- {- "pr_number": 12,- "head_sha": HEAD,- "baseline_sha": BASE,- "status": "verification_recorded",- "run_id": "executed-run",- "tests": {"head": {"status": "passed"}},- "comparison": {"regressed_tests": []},- }- ],- }---def test_assignment_is_explicit_revision_bound_and_does_not_authorize_merge(snapshot):- result = qualify_recommendations(- assignment_checks(snapshot),- review(snapshot),- "independent-run",- snapshot,- )[0]- assert result["status"] == "blocked"- assert result["payload"]["assignee"] == "reporter"- assert result["head_sha"] == HEAD and result["base_sha"] == BASE- assert result["evidence_sha256"] == digest(snapshot)- assert result["source_runs"]["triage_review"] == "independent-run"- assert result["approval_required"] is True and result["merge_ready"] is False- assert result["remaining_gates"] == ["platform_assignment_eligibility"]- assert "silently ignore" in result["execution_preconditions"][-1]- assert result["gates"]["current_ci"] == "not_applicable"--- "change,gate",- [- ("head", "target_revision"),- ("digest", "evidence_binding"),- ("author", "assignee_identity"),- ("owner", "existing_ownership"),- ("draft", "contribution_hold"),- ("security", "open_unrestricted_issue"),- ("history", "public_history"),- ("scope", "scope_notes"),- ],-)-def test_incomplete_assignment_evidence_is_blocked(snapshot, change, gate):- output = review(snapshot)- if change == "head":- output["recommendations"][0]["head_sha"] = "c" * 40- if change == "digest":- output["recommendations"][0]["evidence_sha256"] = None- if change == "author":- output["recommendations"][0]["assignee"] = "someone-else"- if change == "owner":- snapshot["issue"]["assignees"] = ["someone-else"]- if change == "draft":- snapshot["prs"][0]["draft"] = True- if change == "security":- snapshot["issue"]["labels"] = ["security"]- if change == "scope":- output["recommendations"][0]["scope_notes"] = ""- if change == "history":- next(- check- for check in output["recommendations"][0]["norm_evidence"]- if check["check"] == "public_history"- )["satisfied"] = False- result = qualify_recommendations({}, output, "independent-run", snapshot)[0]- assert result["status"] == "blocked" and gate in result["remaining_gates"]---def test_gate_closed_contribution_needs_current_bot_closure_history(snapshot):- pr = snapshot["prs"][0]- pr["state"] = "closed"- pr["comments"] = [{"body": "<!-- require-issue-link -->", "user": {"type": "Bot"}}]- pr["timeline"] = [{"event": "closed", "actor": {"type": "Bot"}}]- assert qualify_recommendations(- assignment_checks(snapshot), review(snapshot), "run", snapshot- )[0]["remaining_gates"] == ["platform_assignment_eligibility"]- pr["timeline"].append({"event": "closed", "actor": {"type": "User"}})- assert (- "assignment_gate_history"- in qualify_recommendations(- assignment_checks(snapshot), review(snapshot), "run", snapshot- )[0]["remaining_gates"]- )--- "action,path", [("close_duplicate", "issues"), ("close_completed", "pulls")]-)-def test_closure_uses_real_read_only_identity_check_and_complete_scope(- snapshot, github_server, action, path-):- read, responses, requests = github_server- snapshot["prs"] = []- extra = {- "canonical_issue" if action == "close_duplicate" else "merged_pr": 99,- "public_comment": f"Resolved by https://github.com/PrefectHQ/fastmcp/{'pull' if path == 'pulls' else path}/99; the complete report is covered.",- }- responses[f"/repos/PrefectHQ/fastmcp/{path}/99"] = {- "number": 99,- "html_url": f"https://github.com/PrefectHQ/fastmcp/{'pull' if path == 'pulls' else path}/99",- "state": "closed",- "merged": True,- "body": f"Fixes #{snapshot['issue']['number']}",- "updated_at": "2026-10-28T00:00:00Z",- }- output = review(snapshot, action, **extra)- destination, outcome = apply_disposition(- "pruning",- {"issue_number": snapshot["issue"]["number"]},- output,- "independent-run",- snapshot,- read,- )- recommendation = outcome["mutation_recommendations"][0]- assert destination == "pruning" and recommendation["status"] == "proposed"- assert recommendation["payload"]["public_comment"] == extra["public_comment"]- assert len(requests) == 1 and recommendation["references"][0]["sha256"]- output["recommendations"][0]["norm_evidence"][0]["satisfied"] = False- assert (- qualify_recommendations({}, output, "run", snapshot, read)[0]["status"]- == "blocked"- )---def test_maintainer_confirmation_can_become_a_reviewed_closure_candidate(- snapshot, github_server-):- read, responses, _ = github_server- snapshot["prs"] = []- responses["/repos/PrefectHQ/fastmcp/pulls/99"] = {- "number": 99,- "html_url": "https://github.com/PrefectHQ/fastmcp/pull/99",- "state": "closed",- "merged": True,- "body": f"Fixes #{snapshot['issue']['number']}",- "updated_at": "2026-10-28T00:00:00Z",- }- output = review(- snapshot,- "close_completed",- merged_pr=99,- public_comment="Resolved by https://github.com/PrefectHQ/fastmcp/pull/99; the complete report is covered.",- )- outcome = {"issue_number": snapshot["issue"]["number"], "decision": "maintainer"}- destination, result = apply_disposition(- "decisions", outcome, output, "independent-run", snapshot, read- )- assert destination == "pruning"- assert result["mutation_recommendations"][0]["status"] == "proposed"- with pytest.raises(ValueError, match="concrete retained closure"):- apply_disposition("unchanged", outcome, output, "run", snapshot, read)---def test_partial_fix_and_missing_canonical_do_not_become_closure_permission(- snapshot, github_server-):- read, responses, requests = github_server- snapshot["prs"] = []- output = review(- snapshot,- "close_completed",- merged_pr=99,- public_comment="The issue is resolved.",- )- responses["/repos/PrefectHQ/fastmcp/pulls/99"] = {- "number": 99,- "html_url": "https://github.com/PrefectHQ/fastmcp/pull/99",- "merged": True,- "body": "References #2692; bytes remain unsupported.",- }- assert (- "merged_complete_fix"- in qualify_recommendations({}, output, "run", snapshot, read)[0][- "remaining_gates"- ]- )- missing = review(snapshot, "close_duplicate", public_comment="Duplicate.")- assert (- "canonical_identity"- in qualify_recommendations({}, missing, "run", snapshot, read)[0][- "remaining_gates"- ]- )- assert len(requests) == 1---def test_duplicate_automation_and_human_intervention_keep_ownership(- snapshot, github_server-):- read, responses, _ = github_server- snapshot["prs"] = []- snapshot["issue"]["labels"] = ["potential-duplicate"]- responses["/repos/PrefectHQ/fastmcp/issues/99"] = {- "number": 99,- "html_url": "https://github.com/PrefectHQ/fastmcp/issues/99",- }- output = review(- snapshot,- "close_duplicate",- canonical_issue=99,- public_comment="Duplicate of #99.",- )- result = qualify_recommendations(- {"route": {"human_intervention": True}}, output, "run", snapshot, read- )[0]- assert "existing_duplicate_automation_or_intervention" in result["remaining_gates"]---def test_proposal_schema_rejects_merge_and_keeps_older_review_outputs_compatible(- snapshot,-):- with pytest.raises(ValidationError):- MutationRecommendation.model_validate(proposal(snapshot, action="merge_pr"))- old = TriageReview.model_validate(- {- "decision": "review_existing",- "reason": "Reviewed",- "findings": [],- "next_action": "Review exact head",- }- )- assert old.recommendations == []- with pytest.raises(ValueError, match="concrete retained closure"):- apply_disposition(- "pruning", {}, {**old.model_dump(), "decision": "propose_closure"}, "run"- )---def test_bulk_batch_blocks_conflicts_and_stale_recommendations(snapshot):- first = qualify_recommendations(- assignment_checks(snapshot), review(snapshot), "run", snapshot- )[0]- second = deepcopy(first)- second["id"] = "alternative"- second["payload"]["assignee"] = "other"- result = {- "batch_id": "bulk",- "bins": {"existing_review": [{"mutation_recommendations": [first, second]}]},- }- batch = mutation_batch(result, "owner")- assert batch["schema_version"] == "fastmcp-mutation-batch/1"- assert batch["approval_required"] and not batch["execution_enabled"]- assert all(- "conflicting_recommendations" in item["remaining_gates"]- for item in batch["recommendations"]- )- result["bins"]["existing_review"][0] = {- "status": "stale",- "mutation_recommendations": [first],- }- assert (- "fresh_evidence"- in mutation_batch(result)["recommendations"][0]["remaining_gates"]- )- assert first["status"] == "blocked"- assert first["remaining_gates"] == ["platform_assignment_eligibility"]---def test_legacy_verification_projects_concrete_repairs_without_inventing_assignments():- item = {- "issue_number": 1,- "next_step": "Close the issue and assign someone",- "verification": [- {- "pr_number": 12,- "head_sha": HEAD,- "baseline_sha": BASE,- "run_id": "verified-run",- "comparison": {"regressed_tests": ["test_supported_override"]},- }- ],- }- batch = mutation_batch({"batch_id": "legacy", "bins": {"existing_review": [item]}})- assert len(batch["recommendations"]) == 1- recommendation = batch["recommendations"][0]- assert recommendation["action"] == "finish_pr"- assert "test_supported_override" in recommendation["next_step"]- assert recommendation["source_runs"]["verification"] == ["verified-run"]- assert set(recommendation["before_merge"]) >= {- "static_checks",- "current_ci",- "batch_composition",- }---def test_mutation_artifact_is_immutable_and_queue_contains_exact_public_payload(- snapshot,-):- from prefect import flow- from prefect.client.orchestration import get_client- from prefect.client.schemas.filters import ArtifactFilter, FlowRunFilter- from prefect.testing.utilities import prefect_test_harness-- @flow- def owner_flow():- return None-- item = {- "issue_number": snapshot["issue"]["number"],- "mutation_recommendations": qualify_recommendations(- {}, review(snapshot), "review-run", snapshot- ),- }- result = {"batch_id": "proposals", "bins": {"existing_review": [item]}}- markdown = review_markdown(result)- assert "Proposed mutations" in markdown and '"assignee": "reporter"' in markdown- assert "No mutations are executed" in markdown- with prefect_test_harness(), get_client(sync_client=True) as client:- owner = client.create_flow_run(owner_flow)- first = retain_review_queue(owner.id, result)- assert retain_review_queue(owner.id, result) == first- artifacts = client.read_artifacts(- artifact_filter=ArtifactFilter(type={"any_": ["fastmcp-mutation-batch"]}),- flow_run_filter=FlowRunFilter(id={"any_": [owner.id]}),- )- assert len(artifacts) == 1- assert artifacts[0].data["recommendations"][0]["head_sha"] == HEAD- changed = deepcopy(result)- changed["bins"]["existing_review"][0]["mutation_recommendations"][0]["payload"][- "assignee"- ] = "other"- with pytest.raises(ValueError, match="Conflicting"):- retain_review_queue(owner.id, changed)---def consolidation(snapshot, github_server):- read, responses, _ = github_server- snapshot["issue"]["assignees"] = ["canonical-contributor"]- responses["/repos/PrefectHQ/fastmcp/pulls/99"] = {- "number": 99,- "html_url": "https://github.com/PrefectHQ/fastmcp/pull/99",- "state": "open",- "merged": False,- "title": "The earlier maintainer-selected canonical",- "body": "Fixes #2692",- "head": {- "sha": "f" * 40,- "ref": "canonical",- "repo": {"full_name": "PrefectHQ/fastmcp", "open_issues_count": 40},- },- "base": {"sha": BASE},- }- output = review(- snapshot,- "close_pr",- canonical_pr=99,- canonical_head_sha="f" * 40,- canonical_base_sha=BASE,- public_comment="Superseded by #99, the earlier maintainer-selected canonical with the same supported coverage.",- next_step="Close this redundant PR after approval, preserving the earlier canonical and issue assignment.",- )- direction = next(- check- for check in output["recommendations"][0]["norm_evidence"]- if check["check"] == "maintainer_direction"- )- direction.update(- summary="The maintainer selected #99 in closed PR #77; newer alternatives do not replace that choice.",- evidence_urls=["https://github.com/PrefectHQ/fastmcp/pull/77#issuecomment-123"],- )- outcome = {- "issue_number": snapshot["issue"]["number"],- "verification": [- {- "pr_number": number,- "head_sha": head,- "baseline_sha": BASE,- "status": "verification_recorded",- "run_id": f"verified-{number}",- "tests": {"head": {"status": "passed"}},- "comparison": {"regressed_tests": []},- }- for number, head in [(12, HEAD), (99, "f" * 40)]- ],- }- return output, outcome, read, responses---def test_pr_consolidation_preserves_open_canonical_and_historical_direction(- snapshot, github_server-):- output, outcome, read, _ = consolidation(snapshot, github_server)- destination, result = apply_disposition(- "existing_review", outcome, output, "independent-run", snapshot, read- )- recommendation = result["mutation_recommendations"][0]- assert destination == "existing_review" and recommendation["status"] == "proposed"- assert recommendation["target"] == {- "kind": "pull_request",- "number": 12,- "url": "https://github.com/PrefectHQ/fastmcp/pull/12",- }- assert recommendation["payload"]["canonical_pr"] == 99- assert recommendation["payload"]["canonical_head_sha"] == "f" * 40- assert set(recommendation["source_runs"]["verification"]) == {- "verified-12",- "verified-99",- }- assert not recommendation["before_merge"]- assert recommendation["approval_required"] and not recommendation["merge_ready"]--- "change,gate",- [- ("canonical_head", "canonical_revision"),- ("target_check", "executed_comparison"),- ("canonical_check", "executed_comparison"),- ("canonical_failure", "canonical_behavior"),- ("maintainer_direction", "maintainer_direction"),- ("parity", "coverage_parity"),- ("hold", "contribution_hold"),- ],-)-def test_pr_consolidation_requires_both_revisions_and_skill_evidence(- snapshot, github_server, change, gate-):- output, outcome, read, responses = consolidation(snapshot, github_server)- if change == "canonical_head":- responses["/repos/PrefectHQ/fastmcp/pulls/99"]["head"]["sha"] = "c" * 40- if change == "target_check":- outcome["verification"] = outcome["verification"][1:]- if change == "canonical_check":- outcome["verification"] = outcome["verification"][:1]- if change == "canonical_failure":- outcome["verification"][1]["tests"]["head"]["status"] = "failed"- if change == "maintainer_direction":- next(- check- for check in output["recommendations"][0]["norm_evidence"]- if check["check"] == "maintainer_direction"- )["satisfied"] = False- if change == "parity":- next(- check- for check in output["recommendations"][0]["norm_evidence"]- if check["check"] == "coverage_parity"- )["satisfied"] = False- if change == "hold":- snapshot["prs"][0]["labels"] = ["do-not-merge"]- recommendation = qualify_recommendations(outcome, output, "run", snapshot, read)[0]- assert (- gate in recommendation["remaining_gates"]- and recommendation["status"] == "blocked"- )---def test_resolution_fingerprint_ignores_repository_counters_but_detects_meaningful_changes(- snapshot, github_server-):- output, outcome, read, responses = consolidation(snapshot, github_server)- first = qualify_recommendations(outcome, output, "run", snapshot, read)[0]- responses["/repos/PrefectHQ/fastmcp/pulls/99"]["head"]["repo"][- "open_issues_count"- ] += 1- second = qualify_recommendations(outcome, output, "run", snapshot, read)[0]- assert first["references"] == second["references"] and first["id"] == second["id"]- responses["/repos/PrefectHQ/fastmcp/pulls/99"]["body"] += (- "\nMaintainer: coverage is incomplete"- )- changed = qualify_recommendations(outcome, output, "run", snapshot, read)[0]- assert changed["references"] != first["references"] and changed["id"] != first["id"]---def test_duplicate_norm_checks_are_rejected_and_model_budget_is_bounded(snapshot):- output = review(snapshot)- output["recommendations"] *= 4- with pytest.raises(ValidationError):- TriageReview.model_validate(output)- one = proposal(snapshot)- one["norm_evidence"] *= 2- with pytest.raises(ValidationError, match="unique"):- MutationRecommendation.model_validate(one)---def test_assignment_needs_executed_head_evidence_in_addition_to_public_history(- snapshot,-):- result = qualify_recommendations({}, review(snapshot), "run", snapshot)[0]- assert "executed_verification" in result["remaining_gates"]- checked = assignment_checks(snapshot)- checked["verification"][0]["head_sha"] = "c" * 40- assert (- "executed_verification"- in qualify_recommendations(checked, review(snapshot), "run", snapshot)[0][- "remaining_gates"- ]- )---def test_one_existing_work_batch_can_assign_canonical_and_close_two_alternatives(- snapshot, github_server-):- read, responses, requests = github_server- snapshot["prs"][0]["user"]["login"] = "alternative-a"- canonical = {- **deepcopy(snapshot["prs"][0]),- "number": 99,- "head_sha": "f" * 40,- "user": {"login": "reporter", "type": "User"},- }- alternative = {- **deepcopy(snapshot["prs"][0]),- "number": 13,- "head_sha": "d" * 40,- "user": {"login": "alternative-b", "type": "User"},- }- snapshot["prs"].extend([canonical, alternative])- responses["/repos/PrefectHQ/fastmcp/pulls/99"] = {- "number": 99,- "html_url": "https://github.com/PrefectHQ/fastmcp/pull/99",- "state": "open",- "merged": False,- "body": "Fixes #2692",- "head": {"sha": "f" * 40},- "base": {"sha": BASE},- }- assign = proposal(snapshot, related_pr=99, head_sha="f" * 40)- close = proposal(- snapshot,- "close_pr",- canonical_pr=99,- canonical_head_sha="f" * 40,- public_comment="Superseded by the maintainer-selected #99 with equivalent supported coverage.",- )- other_close = {**deepcopy(close), "target_number": 13, "head_sha": "d" * 40}- output = {**review(snapshot), "recommendations": [assign, close, other_close]}- TriageReview.model_validate(output)- outcome = {- "issue_number": snapshot["issue"]["number"],- "verification": [- {- "pr_number": pr["number"],- "head_sha": pr["head_sha"],- "baseline_sha": BASE,- "status": "verification_recorded",- "run_id": f"verified-{pr['number']}",- "tests": {"head": {"status": "passed"}},- "comparison": {"regressed_tests": []},- }- for pr in snapshot["prs"]- ],- }- destination, resolved = apply_disposition(- "existing_review", outcome, output, "run", snapshot, read- )- assert destination == "existing_review"- batch = mutation_batch({"batch_id": "mixed", "bins": {destination: [resolved]}})- assert len(batch["recommendations"]) == 3- assignment = next(- item for item in batch["recommendations"] if item["action"] == "assign_issue"- )- assert assignment["remaining_gates"] == ["platform_assignment_eligibility"]- closes = [item for item in batch["recommendations"] if item["action"] == "close_pr"]- assert all(- item["status"] == "proposed" and not item["remaining_gates"] for item in closes- )- assert len(requests) == 1---def test_mutation_batch_carries_exact_acknowledged_review_receipts():- receipt = {- "pr_number": 12,- "head_sha": HEAD,- "review_id": 5,- "reviewer_login": "reviewer[bot]",- "body_sha256": "a" * 64,- }- result = {- "batch_id": "ack",- "bins": {- "existing_review": [- {- "issue_number": 1,- "published_reviews": [receipt],- "verification": [- {- "pr_number": 12,- "head_sha": HEAD,- "baseline_sha": BASE,- "run_id": "executed",- }- ],- }- ]- },- }- assert mutation_batch(result)["recommendations"][0]["acknowledged_reviews"] == [- receipt- ]--- "canonical_state,merged,blocked",- [("open", False, False), ("closed", False, True), ("closed", True, False)],-)-def test_closed_unmerged_canonical_requires_reopen_coordination(- snapshot, github_server, canonical_state, merged, blocked-):- output, outcome, read, responses = consolidation(snapshot, github_server)- canonical = responses["/repos/PrefectHQ/fastmcp/pulls/99"]- canonical.update(state=canonical_state, merged=merged)- if merged:- output["recommendations"][0]["norm_evidence"].append(- {- "check": "current_fix_and_reverts",- "satisfied": True,- "summary": "The selected fix remains present on the pinned main baseline.",- "evidence_urls": ["https://github.com/PrefectHQ/fastmcp/pull/99"],- }- )- result = qualify_recommendations(outcome, output, "run", snapshot, read)[0]- assert ("canonical_reopen_coordination" in result["remaining_gates"]) is blocked- assert (result["status"] == "blocked") is blocked--[email protected]("kind", ["issue", "pull_request"])-def test_bulk_canonical_cycles_do_not_lose_both_trackers(snapshot, github_server, kind):- read, responses, _ = github_server- action = "close_duplicate" if kind == "issue" else "close_pr"- rows = []- for number, other in [(12, 99), (99, 12)]:- current = deepcopy(snapshot)- if kind == "issue":- current["issue"]["number"] = number- current["prs"] = []- responses[f"/repos/PrefectHQ/fastmcp/issues/{other}"] = {- "number": other,- "html_url": f"https://github.com/PrefectHQ/fastmcp/issues/{other}",- "state": "open",- }- output = review(- current,- action,- canonical_issue=other,- public_comment=f"Duplicate of #{other}.",- )- result = qualify_recommendations({}, output, "run", current, read)[0]- else:- output, outcome, _, responses = consolidation(current, github_server)- current["prs"][0]["number"] = number- current["prs"][0]["head_sha"] = HEAD- output["recommendations"][0].update(- target_number=number,- canonical_pr=other,- evidence_sha256=digest(current),- public_comment=f"Superseded by #{other}.",- )- responses[f"/repos/PrefectHQ/fastmcp/pulls/{other}"] = {- "number": other,- "html_url": f"https://github.com/PrefectHQ/fastmcp/pull/{other}",- "state": "open",- "merged": False,- "head": {"sha": "f" * 40},- "base": {"sha": BASE},- }- outcome["verification"] = [- {- "pr_number": number,- "head_sha": HEAD,- "status": "verification_recorded",- "run_id": "target",- "tests": {"head": {"status": "passed"}},- },- {- "pr_number": other,- "head_sha": "f" * 40,- "status": "verification_recorded",- "run_id": "canonical",- "tests": {"head": {"status": "passed"}},- },- ]- result = qualify_recommendations(outcome, output, "run", current, read)[0]- assert result["status"] == "proposed"- rows.append({"issue_number": number, "mutation_recommendations": [result]})- batch = mutation_batch({"batch_id": "cycle", "bins": {"pruning": rows}})- assert len(batch["recommendations"]) == 2- assert all(- "canonical_survival_or_assignment_conflict" in item["remaining_gates"]- and item["status"] == "blocked"- for item in batch["recommendations"]- )---def test_assigning_a_contribution_that_the_same_batch_closes_is_blocked(- snapshot, github_server-):- output, outcome, read, _ = consolidation(snapshot, github_server)- close = qualify_recommendations(outcome, output, "run", snapshot, read)[0]- assign = qualify_recommendations(- assignment_checks(snapshot), review(snapshot), "run", snapshot- )[0]- batch = mutation_batch(- {- "batch_id": "conflict",- "bins": {- "existing_review": [{"mutation_recommendations": [close, assign]}]- },- }- )- assert all(- "canonical_survival_or_assignment_conflict" in item["remaining_gates"]- for item in batch["recommendations"]- )---def test_native_prune_without_route_preserves_human_reopening(snapshot, github_server):- from flows.agentic_intake import route_intake-- read, responses, _ = github_server- snapshot["prs"] = []- snapshot["timeline"] = [{"event": "reopened", "created_at": "2026-10-28T00:00:00Z"}]- assert route_intake(snapshot)["human_intervention"] is True- responses["/repos/PrefectHQ/fastmcp/issues/99"] = {- "number": 99,- "html_url": "https://github.com/PrefectHQ/fastmcp/issues/99",- "state": "open",- }- native = {- "issue_number": snapshot["issue"]["number"],- "decision": "prune",- "reason": "Potential duplicate",- }- output = review(- snapshot,- "close_duplicate",- canonical_issue=99,- public_comment="Duplicate of #99.",- )- destination, result = apply_disposition(- "pruning", native, output, "independent-run", snapshot, read- )- assert destination == "pruning"- recommendation = result["mutation_recommendations"][0]- assert recommendation["status"] == "blocked"- assert (- "existing_duplicate_automation_or_intervention"- in recommendation["remaining_gates"]- )diff --git a/.github/agentic/tests/test_agentic_triage_review.py b/.github/agentic/tests/test_agentic_triage_review.pyindex 6b2b60512..1d5231a09 100644--- a/.github/agentic/tests/test_agentic_triage_review.py+++ b/.github/agentic/tests/test_agentic_triage_review.py@@ -54,6 +54,23 @@ def test_prepare_disposition_carries_scope_controls_to_preparation():)+def test_closure_recommendation_stays_on_the_review_without_github_reads():+ recommendation = {"action": "close_duplicate", "target": {"number": 2}}+ review = {+ "decision": "propose_closure",+ "reason": "Duplicate of #2",+ "next_action": "Close as a duplicate of #2",+ "findings": [],+ "recommendations": [recommendation],+ }+ category, result = apply_disposition(+ "decisions", {"issue_number": 1}, review, "review-run"+ )+ assert category == "pruning"+ assert result["adversarial_review"]["recommendations"] == [recommendation]+ assert "mutation_recommendations" not in result++@pytest.mark.parametrize("destination", ["evidence", "existing_review", "pruning", "decisions", "unchanged"])