🚀 The fast, Pythonic way to build MCP servers and clients.
Stop writing the triage review-desk Markdown artifact (#6212)
nate nowackadcad6a45f43
diff --git a/.github/agentic/README.md b/.github/agentic/README.mdindex ac725eea5..5cb3fe73e 100644--- a/.github/agentic/README.md+++ b/.github/agentic/README.md@@ -1,382 +1,65 @@# Agentic maintenance-Experimental FastMCP maintenance automation for Prefect Cloud. This directory owns-the execution plans, deterministic controller, tests and deployment definitions.-It is an isolated Python 3.12 project; Prefect is not a FastMCP library dependency.-Cloud workers fetch an immutable commit from `PrefectHQ/fastmcp` and execute here.--## Maintainer review with EGM--Use Google's [Elephant–Goldfish Model](https://github.com/google/elephant-goldfish-model)-in the maintainer's interactive session to review a saved triage proposal. Install-the **complete upstream plugin**, following its [Codex integration guide](https://github.com/google/elephant-goldfish-model/blob/main/docs/codex.md),-then start a fresh session. The plugin includes the reviewer personas and-document standards its skills load during review.--Use the installed `egm-review-loop` skill with the proposal as `TargetFile` and-`full file` as `SemanticTarget`. Configure its upstream reviewers and standards-through that skill's configuration step. Supply FastMCP's contribution policy,-applicable review skills, and the proposal's pinned source and evidence as-`GoldfishContext`. Follow upstream's review and resolution gates; retain its-report with the proposal for the maintainer's decision. The maintainer authorizes-the selected GitHub actions after reviewing the proposal.--Cloud nodes receive role-specific FastMCP instruction files through-`instructions.files`, loaded at the issue's pinned base revision by-`scripts/load_fastmcp_skills.sh`. The maintainer session loads EGM from the-installed plugin. Running EGM inside Cloud requires access to the full upstream-bundle and verified support for fresh subagents.--## Review outputs--The connected triage plan is built by `flows.agentic_triage_plan.build_triage_plan`-after registering its two worker deployments. Its Luna assessment selects an-existing-contribution verification, a real reproduction, or a recorded decision.-All branches join a deterministic finalizer; failed agents or workers retain an-operational outcome. The finalizer is executable code, not a human-input placeholder.-The managed intake still supplies bounded GitHub evidence and pins the admission.-Review and MRE batches require the connected plan; a missing configuration returns-an operational failure instead of falling back to the old Python role routing.-Workers resolve that immutable admission and verify their native parent, node,-deployment source, parameters and selected outputs before accepting a result.--Native triage reuses an entire completed result only for the same evidence,-instructions, probes, release baseline, plan version and worker source. It verifies-the original parent and finalizer runs and rechecks current GitHub evidence before-settling the intake. Failed or stale results are not reused. The current execution-engine cannot skip a root agent by omitting an optional plan input, so partial-assessment reuse is not used in the connected plan. Transient verification retries-remain within the same assessment run. Preparation and independent review retain their individual role caches. Fix batches-use the same connected assessment and reproduction as review and MRE batches; the-standalone assessment and reproduction plans are no longer dispatched by the controller.--A required independent triage reviewer adversarially challenges every non-operational-outcome before it reaches the review queue: reproductions, verified contributions,-evidence requests, closure candidates, maintainer questions and skips. It uses the exact-source and executed checks. Its disposition and concrete next action lead each review-item. Native triage refuses a runtime without it. GPT-6.1 Sol runs this review and the-fix-stack review while Luna retains assessment, reproduction and preparation.-Its review standards live in `.agents/skills/adversarial-review/SKILL.md`, which each run-loads from the pinned base revision. Editing that file on `main` changes the standards for the-next run without republishing a plan. The role prompt keeps only output and authority rules.-Serialized regression patches must materialize as tests on their stated baseline-before a reproduced result can advance. Agent claims alone do not establish that-those saved bytes are reusable. Review recommendations do not grant write permission.--Contribution-review freshness follows code revisions, contribution state, holds and-substantive discussion. CI progress and PR activity timestamps do not invalidate a-review; exact acknowledged reviewer receipts are excluded from its own discussion-comparison. Draft-fix publication keeps its stricter evidence comparison. Posted-reviews remain visible and counted when later evidence becomes stale, including-reviews delivered on generated drafts. Native triage retains its evidence durably-and returns that exact evidence to independent review without an immediate lookup.--The draft-fix pilot accepts a manually selected issue in `fix` mode. Only a-connected reproduction of a supported defect can reach preparation, full validation,-independent review and deterministic draft publication. A review queue alone does-not establish that this write path produced an accepted fix.--A manually selected batch contains at most six issues in two coherent groups.-`gh` collects existing labels, full issue discussion, all-state related PRs,-reviews and source revisions. Deterministic policy routes existing contributions,-claims, security reports and outstanding reproduction requests before model work.-It never writes labels. Existing automation retains ownership of its timers and-contribution gates.--The original intake remains an immutable artifact. Assessment receives a compact-view with full discussion text, event identities instead of repeated issue bodies,-and summarized successful checks. For unmerged contributions it also receives bounded-current diffs and changes since the original reviewed commits. Moved heads stop-collection; missing patches and comparison limits are explicit. A stale review-does not establish a current defect, and diff inspection does not count as a test.-The assessor loads contribution-review skills; test-authoring guidance is reserved-for the reproduction, preparation and independent review roles.--Before starting another assessment, the controller looks up a durable fingerprint-index, falling back to the twelve most recent completed role runs for older-unindexed results. Reuse requires identical skills and projected inputs,-the same complete intake revision and active plan version, and a successful-non-operational decision. Only the raw snapshot hash, which includes collection-time, is excluded from comparison. Revision hashes ignore repository-wide counts,-size and activity timestamps embedded in cross-reference events; those remain in-the retained raw evidence. Changed contribution history, revisions, labels or-skills invalidate reuse. Reused assessments retain provenance and add zero new model-usage to the batch; historical usage is not counted again.--Explicit Luna roles use complete repository skills pinned to the source revision:-assessment, reproduction, preparation and independent review. Each role has one-attempt and a 180-second platform limit. The batch allows one repair round and a-two-hour window. Haiku is configured as a comparison candidate, not an automatic-fallback. Missing telemetry remains unknown; these are execution bounds, not a-hard token or dollar cap.--One qualified patch becomes an independent draft PR. Two or three coherent patches-become a draft GitHub Stack through the same validation, review and publication path. Each layer is-validated on its actual parent with the full FastMCP suite and static checks.-Immutable Prefect artifacts retain the exact commits, patches, credit and review.-Publication rechecks ownership, issue history, holds and branch heads; uncertain-writes reconcile with existing GitHub objects. Validation retains per-layer commands, exit codes, elapsed time and bounded output.-Stack validation uses the same unprivileged process boundary as contribution-verification before fetching, installing or executing candidate repository code. Other results are grouped as existing-work-reviews, evidence, pruning proposals, maintainer decisions or operational failures.--Fork PRs are reviewed in place. Adoption and supersession require a maintainer's-decision, with original authorship and issue credit preserved. Closed PRs are-evidence: distinguish assignment-gate closure from explicit maintainer rejection-or supersession.--Existing-contribution assessments dispatch to `cloud-contribution-verification`.-Assessment selects at most three candidates in `verification_prs`, independently-of the complete PR history supplied for review. Historical discovery does not-schedule every unmerged PR for execution. An empty selection retains a review-decision and explicitly records that no tests ran.-An unmerged contribution can be verified while closed, including assignment-gated-PRs; verification does not reopen it. Its current diff and changes since review-are supplied to assessment just as for an open contribution. Merged contributions-remain in the history assessment without launching verification of their old heads.-The verifier fetches immutable commits, derives changed test modules from their-merge base, and runs them on both the pinned current release target and proposed-head. Optional independent-probes run on both as well. Immediate sibling test modules run on the head as-explicit file paths; verification never expands a parent directory into the full-suite. More than twenty sibling modules are omitted with a recorded limitation.-An omitted adjacent stage is `not_run`, not a duplicated passing head result. The repository-lockfile is installed without re-resolution; JUnit cases distinguish assertion-failures, setup errors, skips and missing tests. The managed supervisor launches-verification as UID/GID 65534 with no supplementary groups, capabilities, or-inherited credentials, and with privilege escalation disabled. The supervisor's-runner and input files remain root-owned; verification has its own home and-scratch directory. A network-disabled container canary checks access to a dummy-supervisor environment and private file. Linux, a root supervisor, and `setpriv`-are required; an unavailable boundary fails closed. This isolates supervisor-credentials, not all networking or world-readable files. Command process groups-have timeouts; the managed container deadline is the final lifetime bound.--Results retain the source revisions, probe source, commands, exit codes and test-transitions. The controller checks deployment version and exact inputs before-accepting an artifact, rechecks contribution evidence afterward, and retains stale-results as historical evidence. Matching requests reuse the same verification run.-This deterministic stage uses no model tokens. Provider compute cost remains-unknown. Passing contributor tests is not a merge recommendation: contract review,-current-branch composition and full-suite/static checks remain separate evidence.--When only the release baseline advances during an existing-contribution review,-the controller retains the completed assessment and runs at most two incremental-refreshes. Each refresh requires unchanged contribution history and pinned skill-contents, a complete bounded fast-forward diff, a new Luna assessment of that diff-against the prior contract, and deterministic verification at the new baseline.-The prior assessment is historical context, not automatic approval of new commits.-Interrupted stages resume their saved inputs and child runs. Final freshness checks-use the accepted refreshed snapshot; the original intake remains available.-Changed PR revisions, human discussion, holds or policy require full reassessment.-Incomplete or divergent baseline history also returns to full assessment.--## Bounded intake and review queue--`cloud-triage-intake` selects work without a hand-authored batch. It reads one-30-row page of the oldest open GitHub items and one 30-row page of recent updates,-filters out PRs, and retains at most sixty unique pending issues before dispatch.-It drains that queue in batches of at most three, then advances the backlog page.-The queue and page are saved before starting the child controller. An interrupted-intake recovers the same child by its stable identity and exact inputs. Saved-results, including a completed group without final review bins, survive a later-child failure. Fresh evidence is required before finalizing queued work. The-finalized decision snapshot is saved before receipts and presentation artifacts,-so retrying an interrupted commit completes the same snapshot; a later intake-recovery revalidates the child evidence before making a new snapshot.--Intake has no schedule. Independent event targets have separate checkpoints;-rolling backlog checkpoints remain scoped to their queue and release branch.-Prefect leases serialize overlapping queue updates and issue work across intake,-PR events and manual fix batches. Issue ownership is recorded before work starts.-A takeover stops the prior controller and its proven children, waits for terminal-acknowledgement and shared verification, then records its new ownership. The-active-controller budget is separate from issue ownership, so waiting for another-owner does not occupy an execution slot. Lease renewal failure stops the worker.-This bounds controllers, not all child compute: orphan children may temporarily-outlive a failed controller. Same-issue takeover drains those children before-starting replacement work.--Intake uses `mre` mode: existing-contributions go to verification, new work can reach reproduction, and fix-stack-publication is unavailable through this entrypoint. Public GitHub mutations and-bot-owned label behavior remain unchanged. Independent probes for arbitrary-reports still require the reproduction handler; intake does not manufacture them.--GitHub PR events refresh referenced issues; they do not request a review of the-PR itself. The webhook excludes drafts, PR descriptions without an issue-reference-hint (`#` or a repository issue URL), and edits that do not change the description.-Intake resolves references and discards closed issues and references to other PRs.-Events for the same GitHub item are limited to one launch per sixty seconds;-intake fetches current GitHub state when it starts. Slack announces the issues-accepted for triage only when their controller starts. Empty intake runs stay quiet.-Failure alerts follow the intake's terminal outcome once, with issue-specific-reasons in its state message. Child failures remain in the linked review queue-and run graph rather than producing separate alerts for every orchestration layer.--Successful receipts defer unchanged issue metadata for sixty minutes by default.-This is a cooldown, not a claim that associated PR history is unchanged. Full-history and PR revisions are refreshed when an item is processed, and again before-finalizing its result. Three unsuccessful admissions retain an operational receipt;-the same metadata and implementation are not automatically retried again unless-`retry_failed` is explicitly set. Changed metadata or implementation can retry it.-Baseline churn is retained as pending refresh work, moved behind other queued-items, and does not consume that operational-failure allowance. It never counts-as an acknowledged issue. Review and MRE intake can select a freshly collected-baseline if the branch moved during provisioning; fix publication retains its-original pinned target and freshness gates.--Rolling pages are not a snapshot census: concurrent closes and new activity can-shift entries between pages. Repeated sweeps revisit them. Coverage artifacts-report raw rows, unique issues, deferred work, selected/triaged/pending counts and-retry exhaustion. They do not claim whole-backlog coverage or measured hours saved.-Each controller also creates a Markdown review queue with existing contribution-links, holds, executed regressions, closure proposals, missing evidence, concrete-questions and observed usage. Evidence stays bound to the recorded revisions.--For the general backlog, use `{"branch":"main","max_items":3}` as the config.-An optional `issues` list bounds a trial to named issues and has a separate queue:+FastMCP's triage automation for Prefect Cloud. It's an isolated Python 3.12+project (Prefect is not a FastMCP dependency). Cloud workers fetch an immutable+`PrefectHQ/fastmcp` commit and run the flows here.++## What runs++Two event automations (`fastmcp-triage-on-github-issue` and `-pr`) start+`cloud-triage-intake` when an issue changes or a ready PR that references an issue+changes. Intake collects bounded GitHub evidence and hands a batch to+`cloud-stack-batch`. The connected triage plan (`flows.agentic_triage_plan`)+assesses each item, verifies existing contributions through+`cloud-contribution-verification` or reproduces the report, and sends every+public-facing outcome through the Sol `triage_review` node, which loads+`.agents/skills/adversarial-review/SKILL.md` from the pinned revision.+`cloud-triage-finalize` records the outcome, and accepted reviews are posted as+COMMENT reviews by the triage review app. Nothing in this path assigns, closes, labels or+merges.++Each controller run retains its results as `<batch-id>-review-bins`:```sh-bash scripts/agentic_stack.sh intake config.json runtime.json \- CONTROLLER_DEPLOYMENT_ID INTAKE_DEPLOYMENT_ID unique-operation-id+bash scripts/agentic_stack.sh results CONTROLLER_RUN_ID```-Reuse the operation ID if the launch response is uncertain. Inspect the intake's-coverage and review queue artifacts and its linked controller's results. This-command does not enable recurring runs.--GitHub Actions owns labels, duplicate marking and closure cooldowns. Prefect owns-bounded contract assessment, executable reproduction/contribution verification,-and the explicitly selected draft-fix pilot. Existing GitHub investigation comments-are supplied as evidence; Prefect verifies claims needed for a patch and does not-publish a second investigation comment or close an issue.+Role instructions come from `workflows/stack-skills.json` and are loaded at the+item's base revision by `scripts/load_fastmcp_skills.sh`. Agent roles get no+GitHub write credential.-## Local verification+## Local checks-From this directory:+From this directory (needs `git`, `gh` and `jq`, no Cloud credentials):```shuv sync --locked-uv run ruff check .-uv run ruff format --check .-uv run ty check+uv run ruff check . && uv run ruff format --check . && uv run ty checkuv run pytest -q```-The tests use temporary Git repositories, a local HTTP fault server and a real-temporary Prefect server. They need `git`, `gh` and `jq` on PATH. They do not need-Cloud credentials and do not publish GitHub objects. The separate CI workflow-runs these checks without adding automation dependencies to the library suite.+`agentic-checks.yml` runs the same checks in CI.-## Cloud setup and manual operation+## Deploy-Use an authenticated Prefect CLI profile or `PREFECT_API_KEY`. Set-`PREFECT_API_URL` to the intended Cloud workspace URL. The launcher rejects-self-hosted URLs. Configure that workspace's provider connection ID and explicit-models in `workflows/stack-models.json`, then regenerate the plans:+Merging does not deploy. Live automations run the `source_sha` pinned in their+runtime parameters. To deploy a new main commit, from a clean checkout of it:```sh-uv run python -m flows.agentic_stack_plans+uv run python -m flows.agentic_stack_plans # only if plans or models changedbash scripts/agentic_stack.sh validate+bash scripts/agentic_stack.sh register # registers deployments from prefect.yaml```-Publish the four new role plans through the Agentic Workflows tooling. Registration-requires a clean checkout at a commit already available in `PrefectHQ/fastmcp`:--```sh-bash scripts/agentic_stack.sh register-```--This registers `cloud-triage-intake`, `cloud-stack-batch`, `cloud-stack-validation`,-and `cloud-contribution-verification` in the managed pool, with no schedules. The-publisher loads the existing Cloud Secret block-`fastmcp-triage-gh-token`. Agent roles receive no GitHub write credential.--Managed execution accepts only its supported image tags, not arbitrary patch-version tags. The deployment uses its supported Python 3.12 image and installs-the pinned Prefect version and FastAPI compatibility constraint before pull steps.--Prepare a batch matching `flows.agentic_stack_policy.Batch` and runtime inputs-matching `flows.agentic_stack_runtime.Runtime`. Runtime inputs name the four-published role flow/version IDs, validator deployment ID, contribution verification-deployment ID (`verification_id`) and controller source SHA. Once the named batch-is configured for connected triage, also supply `triage_plan` (flow and version),-`triage_verify_id`, and `triage_finalize_id`; all three must be supplied together.-The connected plan handles assessment and verification/reproduction for `mre`,-`review` and `fix` items. The bounded controller continues a successful `fix`-reproduction through preparation, validation, independent review and publication. Once the named batch-and its external effects are approved:--```sh-bash scripts/agentic_stack.sh run /absolute/path/batch.json /absolute/path/runtime.json CONTROLLER_DEPLOYMENT_ID-bash scripts/agentic_stack.sh results CONTROLLER_RUN_ID-```--Registration is not a successful trial. This implementation has not yet produced-a live stack. Before unattended use, verify the managed runtime, actual PR/stack-readback, cancellation and observed token usage on a bounded batch. Cancellation-stops further publication; an already-started child can run to its own limit.-Public comments, closures, assignments, ready transitions, merges and recurring-schedules are outside this initial automation's authority.--### Delivering reviews and draft fixes--Runtime `prepare_fixes: true` admits automatic issues in fix mode. A reproduced,-independently recommended unclaimed issue proceeds through the existing preparation,-credential-isolated validation, independent patch review and draft publication path.-The triage review's `prepare_fix` disposition carries its implementation controls-into preparation; unresolved reproduction or product decisions must use-`repair_evidence` or `maintainer`. Draft publication still requires final patch-approval without findings, fresh ownership and contribution checks, and reporter credit.--Public reviews are separate from retained investigation records. Existing-contribution-reviewers return a PR-bound `public_reviews` entry with a short finding, requested-change and check evidence (at most 120 words). Missing or invalid public feedback-stops delivery; internal `reason`, `findings` and `next_action` are never a fallback.-Generated-draft reviews summarize successful validation without publishing the-reviewer's internal report or command transcripts. Full evidence remains in the-original Prefect artifacts; revision markers bind the public review to that evidence.--Runtime `publish_reviews: true` posts independent existing-contribution and generated-patch reviews as-GitHub `COMMENT` reviews at the exact verified head. Configure `reviewer_app` with-`app_id`, `slug` and `private_key_block`. The current reviewer is GitHub App-`fastmcp-triage-reviewer` (5514681), owned by zzstoatzz and installed only on FastMCP.-Its signing key lives in the Prefect Secret `fastmcp-triage-reviewer-private-key`;-it is loaded only by trusted delivery code. Agent nodes and verification subprocesses-receive no App credential. Each delivery mints a short-lived repository-scoped token-with PR write and contents/issues/checks/statuses read permissions, then revokes it.-Draft authorship continues through the separate existing publishing credential.--PR claims serialize delivery across issues. A retained revision marker reconciles-retries and lost responses without reposting. External drafts, explicit holds, changed heads,-new discussion and self-authored PRs block posting. The review records executed-checks, findings and next actions; it neither approves nor merges. Exact acknowledged-App reviews are excluded from subsequent freshness comparisons, while new human-or other bot evidence still invalidates an old result. Posted review URLs are retained-alongside the original Cloud review evidence.--After draft publication, the same delivery client posts the retained independent-patch review and validator commands on each exact generated head. Only drafts whose-author, body, branch, base and head match the validated publication qualify for this-path. They remain drafts. Publication is recorded before a separate delivery task,-which retries transient failures and reconciles lost POST responses. New PR comments,-inline comments or reviews stop delivery; only the exact acknowledged App review is-ignored on retry. Exhausted delivery failures retain the published PR receipt and an-operational failure rather than discarding the useful patch or claiming review delivery.---### Maintainer review queue+Then publish any changed role plans with the Agentic Workflows tooling and update+`source_sha` (and any new plan versions) in both triage automations right away.+Flows refuse to run when their deployment version differs from the pinned+`source_sha`, so between `register` and that update, new intakes and any in-flight+run that starts a child fail. Check for running intakes first. If the alert template+changed, re-run `agentic_stack.sh alerts`.-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.+## Roll back-Evidence collection follows at most three one-hop, same-repository canonical or-superseding PR hints from repository-associated human discussion. It verifies each-number is a PR, retains full discussion and source-comment provenance, and rechecks-source and canonical revisions after enrichment. Hints are discovery evidence,-never selection authority. Foreign references, ordinary contributor comments and-bot comments do not expand discovery; existing candidate and byte bounds remain.+Set `source_sha` in both automations back to the previous commit and re-register+from that commit. If a plan changed, also point the runtime back at the previous+plan versions.diff --git a/.github/agentic/flows/agentic_artifacts.py b/.github/agentic/flows/agentic_artifacts.pynew file mode 100644index 000000000..fb3c2b286--- /dev/null+++ b/.github/agentic/flows/agentic_artifacts.py@@ -0,0 +1,79 @@+from __future__ import annotations++import html+import re+from uuid import UUID++from prefect.client.orchestration import get_client+from prefect.client.schemas.actions import ArtifactCreate+from prefect.client.schemas.filters import ArtifactFilter, FlowRunFilter+++def plain(value: object) -> str:+ if value is None:+ return "unknown"+ text = re.sub(r"\s+", " ", str(value)).strip()+ text = re.sub(r"([\\`*{}\[\]()#+.!_~-])", r"\\\1", text)+ return html.escape(text, quote=False).replace("|", "|")+++def published_reviews(result: dict) -> list[dict]:+ receipts = {}++ def collect(item: dict) -> None:+ posted = [+ *item.get("published_reviews", []),+ *item.get("review_delivery", {}).get("posted", []),+ ]+ for receipt in posted:+ identity = (receipt["pr_number"], receipt["review_id"])+ if identity in receipts and {+ key: value+ for key, value in receipts[identity].items()+ if key != "status"+ } != {key: value for key, value in receipt.items() if key != "status"}:+ raise ValueError("Conflicting retained public review receipts")+ receipts[identity] = receipt+ for retained in item.get("retained_outcomes", []):+ collect(retained["result"])++ for items in result.get("bins", {}).values():+ for item in items:+ collect(item)+ return list(receipts.values())+++def retain_markdown(owner: UUID, key: str, markdown: str) -> str:+ return retain_artifact(+ owner, key, markdown, "markdown", "FastMCP maintainer review"+ )+++def retain_artifact(+ owner: UUID, key: str, data: dict | str, artifact_type: str, description: str+) -> str:+ with get_client(sync_client=True) as client:+ previous = client.read_artifacts(+ artifact_filter=ArtifactFilter(key={"any_": [key]}),+ flow_run_filter=FlowRunFilter(id={"any_": [owner]}),+ limit=2,+ )+ if previous:+ if (+ len(previous) != 1+ or previous[0].data != data+ or previous[0].type != artifact_type+ ):+ raise ValueError("Conflicting retained artifact")+ return str(previous[0].id)+ return str(+ client.create_artifact(+ ArtifactCreate(+ key=key,+ type=artifact_type,+ flow_run_id=owner,+ data=data,+ description=description,+ )+ ).id+ )diff --git a/.github/agentic/flows/agentic_review_queue.py b/.github/agentic/flows/agentic_review_queue.pydeleted file mode 100644index 66873eddb..000000000--- a/.github/agentic/flows/agentic_review_queue.py+++ /dev/null@@ -1,271 +0,0 @@-from __future__ import annotations--import html-import re-from uuid import UUID--from prefect.client.orchestration import get_client-from prefect.client.schemas.actions import ArtifactCreate-from prefect.client.schemas.filters import ArtifactFilter, FlowRunFilter---def plain(value: object) -> str:- if value is None:- return "unknown"- text = re.sub(r"\s+", " ", str(value)).strip()- text = re.sub(r"([\\`*{}\[\]()#+.!_~-])", r"\\\1", text)- return html.escape(text, quote=False).replace("|", "|")---def code_block(value: str, language: str = "text") -> str:- fence = "`" * max(- 3, 1 + max((len(run) for run in re.findall(r"`+", value)), default=0)- )- return f"{fence}{language}\n{value}\n{fence}"---def published_reviews(result: dict) -> list[dict]:- receipts = {}-- def collect(item: dict) -> None:- posted = [- *item.get("published_reviews", []),- *item.get("review_delivery", {}).get("posted", []),- ]- for receipt in posted:- identity = (receipt["pr_number"], receipt["review_id"])- if identity in receipts and {- key: value- for key, value in receipts[identity].items()- if key != "status"- } != {key: value for key, value in receipt.items() if key != "status"}:- raise ValueError("Conflicting retained public review receipts")- receipts[identity] = receipt- for retained in item.get("retained_outcomes", []):- collect(retained["result"])-- for items in result.get("bins", {}).values():- for item in items:- collect(item)- return list(receipts.values())---def review_markdown(result: dict) -> str:- sections = {- "existing_review": "Existing contributions",- "evidence": "Reproductions and missing evidence",- "pruning": "Closure candidates — approval required",- "decisions": "Maintainer decisions",- "operational": "Operational attention",- "unchanged": "No action this pass",- "stacks": "Draft fixes",- }- lines = [- f"# FastMCP triage: {plain(result['batch_id'])}",- "",- "Review evidence at the recorded revisions. Recheck current GitHub state before acting. "- "Closure candidates are proposals; a passing test is not merge approval.",- ]- posted = published_reviews(result)- if posted:- lines.extend(["", "## Published reviews", ""])- for receipt in posted:- lines.extend(- [- f"[Posted review on PR #{receipt['pr_number']}]({receipt['review_url']}) "- f"at `{receipt['head_sha']}`.",- "",- ]- )- lines.extend(- [- "Publication is a recorded side effect. Later freshness stops below "- "still require rechecking the current contribution before acting.",- "",- ]- )- for key, title in sections.items():- items = result["bins"].get(key, [])- if not items:- continue- lines.extend(["", f"## {title}", ""])- for item in items:- number = item.get("issue_number")- label = (- f"[Issue #{number}](https://github.com/PrefectHQ/fastmcp/issues/{number})"- if isinstance(number, int)- else plain(item.get("group", "Group"))- )- lines.extend([f"### {label}", ""])- next_step = item.get("next_step")- adversarial = item.get("adversarial_review")- if adversarial:- lines.extend(- [- f"**Adversarial disposition:** {plain(adversarial['decision'])}",- "",- plain(adversarial["reason"]),- "",- ]- )- lines.extend(- f"- {plain(finding)}" for finding in adversarial["findings"]- )- lines.append("")- if next_step:- lines.extend([f"Next: {plain(next_step)}", ""])- for pr_number in item.get("pull_requests", []):- lines.extend(- [- f"[Draft PR #{pr_number}](https://github.com/PrefectHQ/fastmcp/pull/{pr_number})",- "",- ]- )- if item.get("validation_run_id"):- lines.extend(- [- "Validated by run " + plain(item["validation_run_id"]) + ". "- "Independent review: " + plain(item.get("review_run_id")) + ".",- "",- ]- )- assessment = item.get("assessment", item)- reason = assessment.get("reason") or item.get("detail") or item.get("error")- if reason:- if item.get("verification"):- lines.extend(["Assessment before verification:", ""])- lines.extend([plain(reason), ""])- if "observed" in item and "base_sha" in item:- lines.extend(- [- f"**Reproduction outcome:** {plain(item.get('decision'))}.",- f"Baseline: {plain(item['base_sha'])}.",- "",- ]- )- if item.get("contract"):- lines.extend(["Contract: " + plain(item["contract"]), ""])- if item.get("command"):- lines.extend(- ["Command:", "", code_block(item["command"], "sh"), ""]- )- lines.extend(["Observed:", "", code_block(item["observed"]), ""])- if item.get("regression_patch"):- lines.extend(- [- "Regression probe (not a fix):",- "",- code_block(item["regression_patch"], "diff"),- "",- ]- )- if item.get("status") == "stale":- lines.extend(["**Evidence changed. Refresh before acting.**", ""])- held = [- str(pr["number"])- for pr in item.get("route", {}).get("pull_requests", [])- if pr.get("held")- ]- if held:- lines.extend(- [f"**Contribution holds retained:** #{', #'.join(held)}.", ""]- )- for check in item.get("verification", []):- pr = check["pr_number"]- comparison = check.get("comparison", {})- regressions = comparison.get("regressed_tests", [])- status = check["status"]- if status == "environment_failure":- verdict = "Verification could not complete; repair the environment."- elif status == "evidence_needed":- verdict = "A regression test or independent reproduction is needed."- elif regressions:- verdict = (- "A regression was reproduced; repair it before merge review."- )- elif check["tests"]["head"]["status"] != "passed" or check["tests"][- "adjacent"- ]["status"] not in {"passed", "not_run"}:- verdict = "Executed checks need investigation."- elif check["tests"]["adjacent"]["status"] == "not_run":- verdict = "Head checks passed; adjacent checks were not run. Compatibility and merge review remain."- else:- verdict = (- "Executed checks passed; compatibility and merge review remain."- )- lines.extend(- [- f"[PR #{pr}](https://github.com/PrefectHQ/fastmcp/pull/{pr}): **{verdict}**",- "",- f"Head `{check['head_sha'][:12]}` against `{str(check.get('baseline_sha'))[:12]}`. "- f"{len(comparison.get('fixed_tests', []))} fail-to-pass cases; "- f"{len(regressions)} pass-to-fail cases. Verification run `{check['run_id']}`.",- "",- ]- )- for limitation in check.get("limitations", []):- lines.extend([f"Limitation: {plain(limitation)}", ""])- adjacent = check.get("tests", {}).get("adjacent", {})- if adjacent.get("status") == "not_run" and adjacent.get("reason"):- lines.extend([f"Adjacent checks: {plain(adjacent['reason'])}", ""])- for case in regressions:- lines.append(f"- {plain(case)}")- if regressions:- lines.append("")- question = assessment.get("question")- if question:- lines.extend([f"**Decision needed:** {plain(question)}", ""])- usage = result.get("usage", {})- lines.extend(- [- "",- "## Usage",- "",- f"Observed input tokens: {plain(usage.get('input_tokens', 'unknown'))}. "- f"Output tokens: {plain(usage.get('output_tokens', 'unknown'))}. "- "Reused assessments exclude historical usage. Dollar cost is unknown.",- ]- )- return "\n".join(lines).strip() + "\n"---def retain_review_queue(owner: UUID, result: dict) -> str:- return retain_markdown(- owner, f"{result['batch_id']}-triage-queue", review_markdown(result)- )---def retain_markdown(owner: UUID, key: str, markdown: str) -> str:- return retain_artifact(- owner, key, markdown, "markdown", "FastMCP maintainer review queue"- )---def retain_artifact(- owner: UUID, key: str, data: dict | str, artifact_type: str, description: str-) -> str:- with get_client(sync_client=True) as client:- previous = client.read_artifacts(- artifact_filter=ArtifactFilter(key={"any_": [key]}),- flow_run_filter=FlowRunFilter(id={"any_": [owner]}),- limit=2,- )- if previous:- if (- len(previous) != 1- or previous[0].data != data- or previous[0].type != artifact_type- ):- raise ValueError("Conflicting review queue artifact")- return str(previous[0].id)- return str(- client.create_artifact(- ArtifactCreate(- key=key,- type=artifact_type,- flow_run_id=owner,- data=data,- description=description,- )- ).id- )diff --git a/.github/agentic/flows/agentic_stack_controller.py b/.github/agentic/flows/agentic_stack_controller.pyindex f7c4c5de9..03d8d6d98 100644--- a/.github/agentic/flows/agentic_stack_controller.py+++ b/.github/agentic/flows/agentic_stack_controller.py@@ -23,7 +23,6 @@ from flows.agentic_intake import policy_outcome, route_intakefrom flows.agentic_native_triage import run_native_triagefrom flows.agentic_reproduction_evidence import validate_reproduction_patchfrom flows.agentic_review_delivery import deliver_reviews-from flows.agentic_review_queue import retain_review_queuefrom flows.agentic_stack import StackLayer, StackSpec, digest, read_stack_artifactfrom flows.agentic_stack_policy import Batch, Group, publication_revisionfrom flows.agentic_stack_publication import GitHub, reconcile_stack@@ -280,7 +279,6 @@ def run_batch(batch: Batch, runtime: Runtime) -> dict:)previous_result = saved(owner, f"{batch.id}-review-bins")if previous_result is not None:- retain_review_queue(owner, previous_result)return previous_resultactor = identities()bins: dict[str, list] = {@@ -663,7 +661,6 @@ def run_batch(batch: Batch, runtime: Runtime) -> dict:originals[number] = intake["evidence"]result = revalidate(result, originals, branches, collect)record(owner, f"{batch.id}-review-bins", result)- retain_review_queue(owner, result)return resultdiff --git a/.github/agentic/flows/agentic_triage.py b/.github/agentic/flows/agentic_triage.pyindex 362744a35..a48628029 100644--- a/.github/agentic/flows/agentic_triage.py+++ b/.github/agentic/flows/agentic_triage.py@@ -21,16 +21,11 @@ from prefect.client.schemas.sorting import ArtifactSortfrom prefect.context import FlowRunContextfrom prefect.states import Completed+from 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 revalidatefrom flows.agentic_intake import evidence_revision, upgrade_policy_outcomes-from flows.agentic_review_queue import (- plain,- published_reviews,- retain_markdown,- retain_review_queue,-)from flows.agentic_stack_policy import Batchfrom flows.agentic_stack_runtime import (Runtime,@@ -357,8 +352,6 @@ def finish(def commit(owner: UUID, scope: str, state: dict) -> dict:- if state["review"] is not None:- retain_review_queue(owner, state["review"])for receipt in state["receipts"]:retain(owner, f"{scope}-issue-{receipt['issue_number']}", receipt)lines = ["# FastMCP intake coverage", "", "| Measure | Observed |", "| --- | --- |"]@@ -378,7 +371,7 @@ def commit(owner: UUID, scope: str, state: dict) -> dict:lines.extend(["",- f"Controller run: `{state['controller_run_id']}`. Its review queue contains revision-bound evidence and observed usage.",+ f"Controller run: `{state['controller_run_id']}`. Its `-review-bins` artifact holds the revision-bound results.",])retain_markdown(owner, scope + "-coverage", "\n".join(lines) + "\n")diff --git a/.github/agentic/flows/agentic_triage_nodes.py b/.github/agentic/flows/agentic_triage_nodes.pyindex 559641b63..c8b140f5c 100644--- a/.github/agentic/flows/agentic_triage_nodes.py+++ b/.github/agentic/flows/agentic_triage_nodes.py@@ -9,7 +9,6 @@ from prefect.client.orchestration import get_clientfrom prefect.context import FlowRunContextfrom flows.agentic_existing_review import verify_existing-from flows.agentic_review_queue import retain_review_queuefrom flows.agentic_stack_plans import Reproductionfrom flows.agentic_stack_runtime import intake_tools, record, savedfrom flows.agentic_triage_records import (@@ -139,7 +138,4 @@ def triage_finalize(ref: AdmissionRef) -> dict:}record(ref.owner, ref.key + "-outcome", final)record(parent_id, ref.key + "-outcome", final)- retain_review_queue(- parent_id, {"batch_id": ref.key, "bins": {destination: [result]}}- )return finaldiff --git a/.github/agentic/scripts/agentic_stack.sh b/.github/agentic/scripts/agentic_stack.shindex 51d9caa6e..495b89773 100644--- a/.github/agentic/scripts/agentic_stack.sh+++ b/.github/agentic/scripts/agentic_stack.sh@@ -139,7 +139,7 @@ case "${1:-}" injq -n --slurpfile deployments "$scratch/deployments.json" --rawfile body workflows/events/failure-notification.txt.j2 --arg notify "$notify" '([$deployments[0][].id | "prefect.deployment." + .]) as $scope |{name:"fastmcp-triage-failure-alert",- description:"Notify once per failed or degraded intake; child failures are retained in the intake review queue",+ description:"Notify once per failed or degraded intake; child failures are retained in the controller review bins",enabled:true,trigger:{type:"event",posture:"Reactive",threshold:1,within:0,expect:["prefect.flow-run.Failed","prefect.flow-run.Crashed","prefect.flow-run.TimedOut","prefect.flow-run.Degraded"],diff --git a/.github/agentic/tests/test_agentic_backlog.py b/.github/agentic/tests/test_agentic_backlog.pyindex 5358a1f89..9565884b7 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", "-triage-queue")):+ if artifact.key.endswith(("-committed", "-coverage")):client.delete_artifact(artifact.id)before = len(requests)responses["/fresh/1"] = (503, {"message": "Unavailable after finalization"})diff --git a/.github/agentic/tests/test_agentic_public_output_reporting.py b/.github/agentic/tests/test_agentic_public_output_reporting.pyindex f06300fd1..cfd73c087 100644--- a/.github/agentic/tests/test_agentic_public_output_reporting.py+++ b/.github/agentic/tests/test_agentic_public_output_reporting.py@@ -2,7 +2,7 @@ from copy import deepcopyimport pytest-from flows.agentic_review_queue import published_reviews, review_markdown+from flows.agentic_artifacts import plain, published_reviewsdef test_posted_review_remains_visible_after_final_freshness_stop():@@ -38,10 +38,6 @@ def test_posted_review_remains_visible_after_final_freshness_stop():},}assert len(published_reviews(result)) == 1- rendered = review_markdown(result)- assert rendered.count(receipt["review_url"]) == 1- assert "Evidence changed. Refresh before acting." in rendered- assert "Publication is a recorded side effect" in renderedchanged = deepcopy(result)changed["bins"]["existing_review"][0]["published_reviews"][0]["head_sha"] = "b" * 40with pytest.raises(ValueError, match="Conflicting retained"):@@ -64,4 +60,11 @@ def test_generated_draft_review_is_counted_with_existing_contribution_reviews():},}assert published_reviews(result) == [receipt]- assert review_markdown(result).count(receipt["review_url"]) == 1+++def test_model_text_cannot_create_links_or_override_markdown_formatting():+ assert (+ plain("[open account settings](https://attacker.example)")+ == r"\[open account settings\]\(https://attacker\.example\)"+ )+ assert plain(None) == "unknown"diff --git a/.github/agentic/tests/test_agentic_review_queue.py b/.github/agentic/tests/test_agentic_review_queue.pydeleted file mode 100644index b0bc4a503..000000000--- a/.github/agentic/tests/test_agentic_review_queue.py+++ /dev/null@@ -1,162 +0,0 @@-from copy import deepcopy--from flows.agentic_backlog import settle-from flows.agentic_intake import policy_outcome, route_intake, upgrade_policy_outcomes-from flows.agentic_review_queue import plain, review_markdown---def test_queue_distinguishes_regression_operational_failure_and_stale_evidence():- result = {- "batch_id": "trial",- "usage": {"input_tokens": 0, "output_tokens": 0},- "bins": {- "existing_review": [- {- "issue_number": 1,- "assessment": {"reason": "Existing contribution"},- "route": {"pull_requests": [{"number": 2, "held": True}]},- "verification": [- {- "pr_number": 2,- "head_sha": "a" * 40,- "baseline_sha": "b" * 40,- "run_id": "run",- "status": "verification_recorded",- "comparison": {- "fixed_tests": ["reported_bug"],- "regressed_tests": ["neighbor"],- },- }- ],- }- ]- },- }- markdown = review_markdown(result)- assert "A regression was reproduced" in markdown- assert "Contribution holds retained" in markdown- assert "1 fail-to-pass cases; 1 pass-to-fail cases" in markdown- changed = deepcopy(result)- item = changed["bins"]["existing_review"][0]- item["status"] = "stale"- item["verification"][0]["status"] = "environment_failure"- markdown = review_markdown(changed)- assert "Evidence changed" in markdown- assert "Verification could not complete" in markdown- assert "A regression was reproduced" not in markdown- assert "Observed input tokens: 0" in markdown---def test_model_text_cannot_create_links_or_override_queue_formatting():- assert (- plain("[open account settings](https://attacker.example)")- == r"\[open account settings\]\(https://attacker\.example\)"- )- assert plain(None) == "unknown"---def test_omitted_adjacent_checks_are_visible_without_becoming_failures():- result = {- "batch_id": "trial",- "bins": {- "existing_review": [- {- "issue_number": 1,- "assessment": {"reason": "Review current proposal"},- "verification": [- {- "pr_number": 2,- "head_sha": "a" * 40,- "baseline_sha": "b" * 40,- "run_id": "run",- "status": "verification_recorded",- "comparison": {},- "tests": {- "head": {"status": "passed"},- "adjacent": {- "status": "not_run",- "reason": "No sibling modules within budget",- },- },- "limitations": [- "Adjacent verification omitted: 21 sibling modules exceeds budget"- ],- }- ],- }- ]- },- }- markdown = review_markdown(result)- assert "Head checks passed; adjacent checks were not run" in markdown- assert "21 sibling modules exceeds budget" in markdown- assert "No sibling modules within budget" in markdown- assert "Executed checks need investigation" not in markdown---def test_reproduction_queue_preserves_probe_and_contains_fence_like_output():- probe = "diff --git a/test_probe.py b/test_probe.py\n+assert result == expected\n"- observed = "Expected 200, received 404\n```\n[untrusted](https://example.com)"- result = {- "batch_id": "mre",- "bins": {- "evidence": [- {- "issue_number": 603,- "assessment": {- "reason": "Investigate the reported routing failure"- },- "decision": "reproduced",- "base_sha": "a" * 40,- "contract": "The advertised route accepts messages",- "command": "uv run pytest test_probe.py",- "observed": observed,- "regression_patch": probe,- }- ]- },- }- markdown = review_markdown(result)- assert "**Reproduction outcome:** reproduced" in markdown- assert "uv run pytest test_probe.py" in markdown- assert f"````text\n{observed}\n````" in markdown- assert f"```diff\n{probe}\n```" in markdown- assert "a" * 40 in markdown---def test_policy_decisions_render_and_legacy_bins_upgrade(evidence):- evidence["issue"]["labels"] = ["security"]- route = route_intake(evidence)- number = evidence["issue"]["number"]- current = {- "batch_id": "events",- "bins": {"decisions": [policy_outcome(number, route)], "operational": []},- }- legacy = {"batch_id": "events", "bins": {"decisions": [route], "operational": []}}- assert upgrade_policy_outcomes(legacy) == current- assert upgrade_policy_outcomes(current) == current- markdown = review_markdown(upgrade_policy_outcomes(legacy))- assert f"Issue #{number}" in markdown- assert "Security\\-labeled report requires restricted review" in markdown- _, completed = settle([{"issue_number": number, "attempts": 0}], [number], current)- assert completed == [number]---def test_actionable_disposition_precedes_the_raw_reproduction():- item = {- "issue_number": 1,- "observed": "raw observation",- "base_sha": "a" * 40,- "decision": "reproduced",- "next_step": "Prepare the scoped dispatch fix with disabled-tool coverage.",- "adversarial_review": {- "decision": "prepare_fix",- "reason": "Exact regression fails for the intended reason; controls pass.",- "findings": [],- },- }- markdown = review_markdown({"batch_id": "reviewed", "bins": {"evidence": [item]}})- assert "**Adversarial disposition:** prepare\\_fix" in markdown- assert markdown.index("Prepare the scoped dispatch") < markdown.index(- "raw observation"- )diff --git a/.github/agentic/workflows/events/failure-notification.txt.j2 b/.github/agentic/workflows/events/failure-notification.txt.j2index 1fedb3dca..1a0d036d2 100644--- a/.github/agentic/workflows/events/failure-notification.txt.j2+++ b/.github/agentic/workflows/events/failure-notification.txt.j2@@ -1,3 +1,3 @@{% set state = flow_run.state.name %}{{ {'Failed': '❌', 'Crashed': '💥', 'TimedOut': '⏱️', 'Degraded': '⚠️'}.get(state, '⚠️') }} triage {{ {'TimedOut': 'timed out'}.get(state, state|lower) }}-{{ flow_run.state.message or 'See the retained review queue for the failure details.' }}-<{{ flow_run|ui_url }}|run and review queue>+{{ flow_run.state.message or 'See the retained artifacts for the failure details.' }}+<{{ flow_run|ui_url }}|run and artifacts>