From da9c61ecaec931308ed048ac435de44ee2d72261 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Thu, 12 Nov 2026 17:15:00 -0600 Subject: [PATCH 1/6] Add the reviewer L1 Vally suite Add the standard review-pull-request suite with six frozen-evidence cases, the reviewer baseline and smoke experiments, the L1 fixture self-tests, and the review-pull-request dispatch option. Case-06 replaces the specialized catch-policy suite and its fixtures. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/skill-evals.yml | 1 + eng/skill-evals/README.md | 120 +- .../catch-policy.vally.yaml | 152 -- .../review-pull-request/eval.vally.yaml | 867 ++++++++++ .../fixtures/.gitattributes | 5 + .../fixtures/case-01/baseTip.source | 137 ++ .../fixtures/case-01/case.source | 8 + .../fixtures/case-01/change.diff | 61 + .../fixtures/case-01/context.source | 66 + .../fixtures/case-01/head.source | 150 ++ .../fixtures/case-01/mergeBase.source | 137 ++ .../fixtures/case-01/provenance.json | 103 ++ .../fixtures/case-02/baseTip.source | 1538 +++++++++++++++++ .../fixtures/case-02/case.source | 8 + .../fixtures/case-02/change.diff | 34 + .../fixtures/case-02/context.source | 19 + .../fixtures/case-02/head.source | 91 + .../fixtures/case-02/mergeBase.source | 88 + .../fixtures/case-02/provenance.json | 151 ++ .../fixtures/case-03/baseTip.source | 127 ++ .../fixtures/case-03/case.source | 8 + .../fixtures/case-03/change.diff | 20 + .../fixtures/case-03/context.source | 116 ++ .../fixtures/case-03/head.source | 182 ++ .../fixtures/case-03/mergeBase.source | 175 ++ .../fixtures/case-03/provenance.json | 131 ++ .../fixtures/case-04/baseTip.source | 517 ++++++ .../fixtures/case-04/case.source | 8 + .../fixtures/case-04/change.diff | 108 ++ .../fixtures/case-04/context.source | 164 ++ .../fixtures/case-04/head.source | 104 ++ .../fixtures/case-04/mergeBase.source | 109 ++ .../fixtures/case-04/provenance.json | 131 ++ .../fixtures/case-05/baseTip.source | 160 ++ .../fixtures/case-05/case.source | 8 + .../fixtures/case-05/change.diff | 83 + .../fixtures/case-05/context.source | 87 + .../fixtures/case-05/head.source | 122 ++ .../fixtures/case-05/mergeBase.source | 83 + .../fixtures/case-05/provenance.json | 145 ++ .../baseTip.source} | 0 .../fixtures/case-06/case.source | 1 + .../change.diff} | 2 +- .../fixtures/case-06/context.source | 40 + .../head.source} | 2 +- .../mergeBase.source} | 0 .../fixtures/case-06/provenance.json | 36 + .../ConversationEngineTests.cs.source | 21 - .../fixtures/catch-policy/best-effort.txt | 20 - .../catch-policy/existing-question.txt | 23 - .../fixtures/catch-policy/nonthrowing.txt | 24 - .../fixtures/catch-policy/propagation.txt | 21 - .../fixtures/catch-policy/unspecified.txt | 20 - eng/skill-evals/test_review_fixtures.ps1 | 235 ++- eng/skill-evals/test_run.ps1 | 58 +- 55 files changed, 6516 insertions(+), 311 deletions(-) delete mode 100644 eng/skill-evals/review-pull-request/catch-policy.vally.yaml create mode 100644 eng/skill-evals/review-pull-request/eval.vally.yaml create mode 100644 eng/skill-evals/review-pull-request/fixtures/.gitattributes create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/baseTip.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/case.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/change.diff create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/context.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/head.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/mergeBase.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-01/provenance.json create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/baseTip.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/case.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/change.diff create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/context.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/head.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/mergeBase.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-02/provenance.json create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/baseTip.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/case.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/change.diff create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/context.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/head.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/mergeBase.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-03/provenance.json create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/baseTip.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/case.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/change.diff create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/context.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/head.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/mergeBase.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/baseTip.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/case.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/change.diff create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/context.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/head.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/mergeBase.source create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-05/provenance.json rename eng/skill-evals/review-pull-request/fixtures/{catch-policy/Dependencies.cs.source => case-06/baseTip.source} (100%) create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-06/case.source rename eng/skill-evals/review-pull-request/fixtures/{catch-policy/ConversationEngine.diff => case-06/change.diff} (100%) create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-06/context.source rename eng/skill-evals/review-pull-request/fixtures/{catch-policy/head/ConversationEngine.cs.source => case-06/head.source} (100%) rename eng/skill-evals/review-pull-request/fixtures/{catch-policy/old/ConversationEngine.cs.source => case-06/mergeBase.source} (100%) create mode 100644 eng/skill-evals/review-pull-request/fixtures/case-06/provenance.json delete mode 100644 eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngineTests.cs.source delete mode 100644 eng/skill-evals/review-pull-request/fixtures/catch-policy/best-effort.txt delete mode 100644 eng/skill-evals/review-pull-request/fixtures/catch-policy/existing-question.txt delete mode 100644 eng/skill-evals/review-pull-request/fixtures/catch-policy/nonthrowing.txt delete mode 100644 eng/skill-evals/review-pull-request/fixtures/catch-policy/propagation.txt delete mode 100644 eng/skill-evals/review-pull-request/fixtures/catch-policy/unspecified.txt diff --git a/.github/workflows/skill-evals.yml b/.github/workflows/skill-evals.yml index 9742fc1fb905..3266aa9a679e 100644 --- a/.github/workflows/skill-evals.yml +++ b/.github/workflows/skill-evals.yml @@ -40,6 +40,7 @@ on: default: review-public-api options: - review-public-api + - review-pull-request - review-candidate-verifier - validate-blazor-feature run_type: diff --git a/eng/skill-evals/README.md b/eng/skill-evals/README.md index f160daa8c767..a0abd38c8b07 100644 --- a/eng/skill-evals/README.md +++ b/eng/skill-evals/README.md @@ -12,7 +12,8 @@ auto-discovered by this repository's experiment and runner. `skills-vs-baseline.experiment.yaml` runs the generic skill specs twice with the same stimuli: once without a skill and once with exactly `.github/skills/` loaded. The experiment owns `environment.skills`; -standard specs must not set it themselves. +standard specs must not set it themselves. Reviewer diagnostic-control runs use +`review-vs-baseline.experiment.yaml` and `review-smoke.experiment.yaml` instead. The verifier component suite has no skill arm and runs directly. Any other `*.vally.yaml` file is a specialized suite. Specialized suites are not @@ -21,24 +22,54 @@ beside the spec that consumes them, normally under a `fixtures` directory. Do not place eval specs, `evals` directories, or eval runners in runtime skill directories. A runtime skill may use a `fixtures` directory for non-eval assets. -`review-pull-request/catch-policy.vally.yaml` is a specialized, offline policy -exercise. It stages the current reviewer skill, cross-cutting guide, diff, old/head source, -dependency implementations, and one selected scenario into each trial workspace. -Five independent stimuli cover unspecified policy, existing feedback, propagation, -best-effort reporting, and a nonthrowing producer control. The agent must derive the -effect from source rather than receive the expected behavior in its prompt. -Static tool-result checks require the relevant guidance and source to be read; -binary judging checks the reasoning separately. These checks do not prove every -line was read or replace the semantic judge. Five trials per stimulus must all pass. -Platform-required native skill acquisition is allowed, but does not replace reading -the staged guidance or authorize coordinator execution. -The executor and judge models are both pinned to the reviewer skill's supported -`gpt-5.6-sol`. Because they share a model identity, the judge is not independent- -model corroboration. Overrides are separate model-compatibility results, not -evidence that the default reviewer improved. -This does not invoke live PR review or measure baseline-versus-skilled improvement. -Run it explicitly with -`./eng/skill-evals/run.ps1 Run -Eval eng/skill-evals/review-pull-request/catch-policy.vally.yaml --require-pass`. +The standard `review-pull-request` suite uses frozen source and diff excerpts from +ASP.NET Core PRs #70106, #69782, #70304, #69721, and #70299. These cover exact-input +old/head comparison, constructor mapping versus a lower-layer head test, renderer +disposal and issue intent, browser-test wrapper ordering in a disputed +token-exchange dependency claim, and existing feedback on render-mode-dependent +navigation. Each case carries its source roles, +Git blob identities, original line ranges, and fixture SHA-256 hashes in +`provenance.json`. Issue and feedback excerpts identify their captured public +revision metadata. Neutral stimulus names and destination paths do not encode +expected dispositions. A sixth case integrates the synthetic public catch-policy +example from #70312. It omits the explicit missing-policy hints and the redundant +existing-question case. It does not represent production framework source. +It replaces the retired standalone catch-policy suite and its duplicate fixtures. +Fixture attributes retain LF and upstream whitespace so Git checkout preserves +the frozen hashes on Windows and Unix. + +These are offline single-context candidate exercises, not full bundle preparation, +guide-worker dispatch, verifier integration, live PR review, or browser tests. +L1 is frozen-evidence adjudication regression, not a measurement of skill lift. +Its baseline is a diagnostic control, not a competitor. Skill lift requires +end-to-end evidence. +All six L1 oracles (`case-01`, `case-02`, `case-03`, `case-04`, `case-05`, and +`case-06`) are provisional pending an independent two-reviewer audit. +The agent-relabelled `DISCARDED` oracle for `case-04` remains disputed, not +independently proven. The `case-06` notification-order confound is corrected, +its `UNRESOLVED` oracle is retained, and cold GPT-5.6 and Opus-5.5 adjudications +agree. That model agreement is not a human audit. +Both arms share frozen source and both guidance documents. Only the skilled arm +receives the skill and verifier/worker instructions. Baseline does not receive +`SKILL.md` or either agent profile. `tool-calls.required` matches both read arguments and +returned bytes, including actual skill text from native acquisition or an installed +file read. A success acknowledgement or a filename citation does not satisfy those +checks. Content signatures prove the specified bytes appeared in a tool result, +not that every possible review path ran. + +Only the deterministic program grader contributes to disposition scores. It checks +the status line, C1's section placement, inline confidence, and existing-thread +deduplication. Skill acquisition, read receipts, and LLM rubrics have zero weight. +The result gate checks evidence/guidance receipts for both arms and skill/profile +receipts for skilled only. A missing baseline skill cannot lower its disposition +score. Each skilled stimulus must independently meet its threshold. Baseline +disposition scores are reported, not threshold-gated. + +The zero-weight LLM rubrics remain secondary diagnostics, not semantic quality +gates. They still incur judge calls during a model-bearing run. The subject and +judge both use `gpt-5.6-sol`; the judge is not independent-model corroboration. +These public development cases are not held-out evidence. Five repeats do not +create five independent PR lineages. The `review-candidate-verifier` component suite checks normalized `decision` and applicable `downgradeKind`, `dropBasis`, and `contradictedLink` fields. It tolerates @@ -56,6 +87,10 @@ policy-only head-test scenario (close to @maraf's 3/10 `DROP(unestablished)` / 7/10 `DOWNGRADE(intent)` synthetic fixture) was omitted from the component gate; `SKILL.md` retains the coordinator backstop mapping `DOWNGRADE(intent)` with `contract: "n/a"` to `UNRESOLVED`, which has not been measured end to end. +The fresh 30-trial-per-arm L1 regression scored 27/30 for the diagnostic baseline +and 29/30 for skilled. Skilled `case-04` scored 4/5, below its configured 5/5 +gate. Every other skilled case scored 5/5. These results are against the +provisional oracles and do not establish skill lift. Model-free validation checks layout, schema, source hashes, read-guard coverage, and experiment selection. It does not establish adjudication quality. A @@ -63,8 +98,9 @@ model-bearing `Run` and inspection of every trial's actual read receipts and semantic result remain necessary before making a behavioral claim. The experiment deliberately does not override `runs`. A standard spec owns its -trial count through `defaults.runs`. The component suite has 15 trials. -The dotnet/skills quality gate uses five trials as the minimum at which a clean sweep can support a one-sided sign test at 5%; enforcing a +trial count through `defaults.runs`. The reviewer suite has 30 trials per arm. +The component suite has 15 trials. The dotnet/skills quality gate uses five trials as the minimum at +which a clean sweep can support a one-sided sign test at 5%; enforcing a trial-count policy here remains a documented follow-up. ## Fixture purpose and file scope @@ -75,6 +111,7 @@ Verifier cases a and b supply nine C# files at each of head and merge base, plus base-tip docs, rather than full trees. Their diff covers only `AgentContext.cs`, although the snapshots also contain changes to `UIAgent.cs` and `UIAgentLog.cs`. +L1 `case-02` supplies the `FileConverter.cs` diff from a six-file PR. The results provide regression evidence for these supplied slices. They do not establish production-bundle fidelity or end-to-end review quality. @@ -129,6 +166,38 @@ them, and the spec maps each one to both revisions. Only `AgentContext.cs`, | `Engine\ConversationStatus.cs` | a, b | Status values used by the stream and callbacks. | | `Engine\ConversationTurn.cs` | a, b | Request and response block storage. | +### Reviewer cases + +Each folder under `review-pull-request\fixtures` contains the same seven filenames. +The eval stages only the selected folder for each trial. +All expected answers below remain provisional, pending an independent two-reviewer audit. + +| Folder and stimulus | Purpose | Provisional expected answer | +|---|---|---| +| `case-01` | Stale-token claim during an authentication-state change. | `DISCARDED` | +| `case-02` | Unmatched constructor file parameter compared with a lower-layer head test. | Verified finding | +| `case-03` | ErrorBoundary delivery after renderer disposal, with issue intent. | `DISCARDED` | +| `case-04` | Browser-test dependency on token exchange before assertions. | `DISCARDED` (disputed) | +| `case-05` | Navigation-ordering question already raised in existing feedback. | `EXISTING_FEEDBACK_COVERAGE` with an unresolved thread reference | +| `case-06` | Unestablished secondary-failure policy after status notification. | `UNRESOLVED` (fixture-confound corrected) | + +| File relative to each case folder | Cases | Purpose | +|---|---|---| +| `case.source` | case-01 through case-06 | Candidate claim and saved PR rationale. | +| `change.diff` | case-01 through case-06 | Selected change to adjudicate. | +| `mergeBase.source` | case-01 through case-06 | Earlier source for comparison. | +| `head.source` | case-01 through case-06 | Proposed source. | +| `baseTip.source` | case-01 through case-06 | Base-tip source context. | +| `context.source` | case-01 through case-06 | Supporting head tests, issue intent, or feedback for that case. | +| `provenance.json` | case-01 through case-06 | Source roles, revisions, line ranges, and fixture hashes. | + +The reviewer fixture root's `.gitattributes` preserves frozen bytes for all six cases. +The `.source` extension marks inert, role-tagged excerpts, which can concatenate +non-compilable snippets. The production exporter also uses `.source` for frozen files. +Both reviewer arms receive the repository's two guidance documents. +Only the skilled arm receives the skill and worker/verifier profiles. +These shared instructions sit outside the per-case fixture folders. + ## Local entry point Run these commands from any directory: @@ -140,9 +209,11 @@ Run these commands from any directory: # Prove every validator rule and runner isolation with self-tests ./eng/skill-evals/run.ps1 Test -# Select one suite for layout and lint. +# Select this suite for layout, lint, and both experiment dry-runs. +./eng/skill-evals/run.ps1 Validate -Suite review-pull-request ./eng/skill-evals/run.ps1 Validate -Suite review-candidate-verifier # Run infrastructure self-tests plus the selected suite's fixture checks. +./eng/skill-evals/run.ps1 Test -Suite review-pull-request ./eng/skill-evals/run.ps1 Test -Suite review-candidate-verifier # Strict Vally parsing/schema lint; does not call a model @@ -157,7 +228,8 @@ Run these commands from any directory: ``` Without a suite or explicit experiment, `Run` dispatches each standard suite into -its own output subdirectory. This includes the direct verifier component suite. +its own output subdirectory. This includes the reviewer diagnostic control and the direct +verifier component suite. Experiment-only options require `-Suite` or `-Experiment` and are rejected before all-suite dispatch. Each single-eval experiment or direct component `Run` checks its own new run directory with `assert_results.ps1` before it returns. A Vally exit code of 1 is accepted only @@ -165,7 +237,7 @@ after those checks pass; any failed check stops the run, including in the all-suite dispatch. A direct component run writes a plan beside Vally's timestamped `results.jsonl`; it does not invent an experiment variant directory. That plan reflects the selected YAML and CLI runs/threshold overrides. For the -verifier suite, smoke selects one repeat per case and checks trial +reviewer and verifier suites, smoke selects one repeat per case and checks trial completion, grader scores, and read-integrity receipts without enforcing the multi-trial per-stimulus disposition threshold. Experiment runs with `--variant skilled` or `--variant=skilled` check only the diff --git a/eng/skill-evals/review-pull-request/catch-policy.vally.yaml b/eng/skill-evals/review-pull-request/catch-policy.vally.yaml deleted file mode 100644 index dac0a7c91cb9..000000000000 --- a/eng/skill-evals/review-pull-request/catch-policy.vally.yaml +++ /dev/null @@ -1,152 +0,0 @@ -name: review-pull-request-catch-policy -description: Independent source-first cases for secondary-failure suppression and deduplication (70269). -type: capability -defaults: - runs: 5 - timeout: 420s - model: gpt-5.6-sol - judge_model: gpt-5.6-sol -agent_environment: - files: - - src: ../../../.github/skills/review-pull-request/SKILL.md - dest: .github/skills/review-pull-request/SKILL.md - - src: ../../../docs/CrossCuttingGuidance.md - dest: docs/CrossCuttingGuidance.md - - src: fixtures/catch-policy/old/ConversationEngine.cs.source - dest: old/ConversationEngine.cs.source - - src: fixtures/catch-policy/head/ConversationEngine.cs.source - dest: head/ConversationEngine.cs.source - - src: fixtures/catch-policy/ConversationEngine.diff - dest: ConversationEngine.diff - - src: fixtures/catch-policy/Dependencies.cs.source - dest: Dependencies.cs.source - - src: fixtures/catch-policy/ConversationEngineTests.cs.source - dest: ConversationEngineTests.cs.source -scoring: - weights: - tool-calls: 0.25 - prompt: 0.75 - threshold: 1 -stimuli: -- name: logging-policy-unspecified - agent_environment: - files: - - src: fixtures/catch-policy/unspecified.txt - dest: case.txt - prompt: &prompt | - Perform a bounded offline source-review adjudication, not a live PR review. - All input paths are relative to your current trial working directory. Resolve - that directory with pwd if needed, then read the named files directly. Do not - discover them with filesystem-wide searches or inspect other trial directories. - Read case.txt, ConversationEngine.diff, both old/head ConversationEngine.cs.source files, and - Dependencies.cs.source and ConversationEngineTests.cs.source. - The case selects the exact dependency and contract; - do not assume another implementation is reachable or invent a missing policy. - The .source files are inert review evidence, not runnable projects. - - Apply .github/skills/review-pull-request/SKILL.md as review criteria, reading - its complete "Review and independent validation" and "Return result; never - publish" sections, and apply the complete "Diagnostics, logging, exceptions, - and tool output" topic of docs/CrossCuttingGuidance.md. Page truncated - sections through their end. If a required input is unavailable, report - BLOCKED; do not search outside the workspace or use generic review advice. - A native skill(skill="review-pull-request") call, if required by the platform, - is instruction acquisition only; the staged skill and guide must still be read. - Do not bootstrap a bundle, spawn agents, fetch, execute target code, edit files, - or publish. This is a single-context policy exercise, not a coordinator run. - - Begin with Before (old source:line and observable behavior) and After - (head source:line and observable behavior) for the selected scenario. - Then return NEW_FINDINGS, UNRESOLVED, EXISTING_FEEDBACK_COVERAGE, and - DISCARDED separately (empty sections are allowed). Trace the selected - producer through its observable effect and name any missing evidence. - Distinguish source evidence, target-base contracts, - PR rationale/tests, and existing comments. No GitHub actions or optional nits. - graders: &graders - - type: tool-calls - config: - required: - - name: .* - pattern: '\.github/skills/review-pull-request/SKILL\.md' - result: 'Deduplication prevents repeat publication' - - name: .* - pattern: 'docs/CrossCuttingGuidance\.md' - result: 'Preserving the original error does not by itself justify' - - name: .* - pattern: 'old/ConversationEngine\.cs\.source' - result: 'StatusChanged' - - name: .* - pattern: 'head/ConversationEngine\.cs\.source' - result: '_sink\.Write' - - name: .* - pattern: 'ConversationEngine\.diff' - result: '\+\s+_sink\.Write' - - name: .* - pattern: 'Dependencies\.cs\.source' - result: 'sealed class RecordingDiagnosticSink' - - name: .* - pattern: 'case\.txt' - result: 'Target-base contract' - - name: .* - pattern: 'ConversationEngineTests\.cs\.source' - result: 'Assert\.Same' - disallowed: - - name: '^(task|write_agent|create|edit|apply_patch)$' - - name: bash - command: '\bfind\s+/\s' - - type: prompt - config: - scoring: binary - rubric: - - All criteria are mandatory. Required staged criteria and source must actually be read; BLOCKED, unavailable-input, generic-advice, or invented-evidence responses fail. Source citations must support the claimed behavior, not merely list filenames. - - Trace FailingClient.ProcessAsync throwing the primary failure, then ThrowingDiagnosticSink.Write throwing a distinct secondary failure into the new inner catch. Explain that the head task completes successfully with Error holding the primary failure and observers notified, while the old code never invoked the sink and therefore did not propagate a sink failure at this seam. - - Retain the concrete changed catch and missing sink-failure handling contract in UNRESOLVED. Do not report a verified defect or intent question. If the unresolved candidate is surfaced inline in NEW_FINDINGS, mark it with unresolved confidence, prefix its claim with [UNRESOLVED], and state the exact missing contract in its Why unresolved field; this preserves the uncertainty without declaring a proven defect. The PR-added test and preservation rationale are implementation intent, not independent policy authority. - - Do not assume every empty catch is a defect or that primary-error preservation justifies losing secondary failures. Do not propose nits, posting, replying, resolving, approving, or requesting changes. -- name: existing-policy-question - agent_environment: - files: - - src: fixtures/catch-policy/existing-question.txt - dest: case.txt - prompt: *prompt - graders: *graders - rubric: - - All criteria are mandatory. Required staged criteria and source must actually be read; BLOCKED, unavailable-input, generic-advice, or invented-evidence responses fail. Source citations must support the claimed behavior, not merely list filenames. - - Trace the selected FailingClient and ThrowingDiagnosticSink through the newly added catch, identifying the distinct primary and secondary failures and the caller-visible successful task completion. Do not claim the old code propagated the secondary failure; the sink call did not exist. - - UNRESOLVED explicitly retains the suppression concern, missing sink-failure contract, and existing thread reference feedback-17, and EXISTING_FEEDBACK_COVERAGE records feedback-17 as already raising this concern. Do not report a verified defect or intent question. Because feedback-17's text raises the same sink-failure suppression, NEW_FINDINGS must not contain that concern under any confidence label, including an [UNRESOLVED] or [DISCARDED] inline entry; any such entry fails even when UNRESOLVED and EXISTING_FEEDBACK_COVERAGE are otherwise correct. Merely putting the thread in EXISTING_FEEDBACK_COVERAGE or deferring to it without retaining the missing contract in UNRESOLVED fails. - - Neither the existing question nor the PR rationale/test is contract authority or proof of resolution. Deduplication prevents repeat publication but does not settle the concern. Do not propose nits, posting, replying, resolving, approving, or requesting changes. -- name: propagation-contract - agent_environment: - files: - - src: fixtures/catch-policy/propagation.txt - dest: case.txt - prompt: *prompt - graders: *graders - rubric: - - All criteria are mandatory. Required staged criteria and source must actually be read; BLOCKED, unavailable-input, generic-advice, or invented-evidence responses fail. Source citations must support the claimed behavior, not merely list filenames. - - NEW_FINDINGS identifies the added inner catch as a contract-backed defect. Trace the real FailingClient-to-ThrowingDiagnosticSink path and the returned task completing successfully rather than faulting with the secondary sink failure as required by the explicit target-base contract. - - Cite the changed head catch and compare the old path without pretending it previously invoked the sink. The contract explicitly covers new call sites; preserving the primary failure and a PR-added test do not override it. - - Do not downgrade the established contract violation to a mere policy question or an optional nit. Do not propose posting, replying, resolving, approving, or requesting changes. -- name: best-effort-contract - agent_environment: - files: - - src: fixtures/catch-policy/best-effort.txt - dest: case.txt - prompt: *prompt - graders: *graders - rubric: - - All criteria are mandatory. Required staged criteria and source must actually be read; BLOCKED, unavailable-input, generic-advice, or invented-evidence responses fail. Source citations must support the claimed behavior, not merely list filenames. - - UNRESOLVED is empty for this suppression concern. DISCARDED explains that the explicit target-base best-effort contract authorizes the changed catch, with the primary error retained and status observers notified when the selected sink throws. Do not report a verified defect, intent question, or unresolved entry. If the discarded candidate is surfaced inline in NEW_FINDINGS, mark it with discarded confidence, prefix its claim with [DISCARDED], and cite the contract in its Why discarded field. - - Distinguish the two failures, trace old/head behavior, and use the explicit contract rather than the PR rationale, primary-error preservation alone, or the new test as authority. Do not demand a second logging call to report a failed logger. - - Do not invent a defect, missing contract, or optional nit merely because the catch is empty. Do not propose posting, replying, resolving, approving, or requesting changes. -- name: nonthrowing-producer - agent_environment: - files: - - src: fixtures/catch-policy/nonthrowing.txt - dest: case.txt - prompt: *prompt - graders: *graders - rubric: - - All criteria are mandatory. Required staged criteria and source must actually be read; BLOCKED, unavailable-input, generic-advice, or invented-evidence responses fail. Source citations must support the claimed behavior, not merely list filenames. - - UNRESOLVED is empty for sink-failure suppression in the bounded scenario. DISCARDED traces RecordingDiagnosticSink.Write, which records the primary exception and returns, so the inner catch is not entered and no secondary sink failure is established. Do not report a verified defect, intent question, or unresolved entry. If this disproven candidate is surfaced inline in NEW_FINDINGS, mark it with discarded confidence, prefix its claim with [DISCARDED], and cite the source line that rules out the secondary failure in its Why discarded field. - - Recognize that ThrowingDiagnosticSink exists in the source but is not selected by this case and cannot be substituted into the producer path. The propagation contract does not create an exception producer. Do not invent unprovided failures such as out-of-memory. - - Compare the old behavior to the head's added diagnostic record while retaining the primary error and notifying observers; do not report the lack of a record on the old side as a new head defect. Do not propose nits or GitHub actions. diff --git a/eng/skill-evals/review-pull-request/eval.vally.yaml b/eng/skill-evals/review-pull-request/eval.vally.yaml new file mode 100644 index 000000000000..156800ea419c --- /dev/null +++ b/eng/skill-evals/review-pull-request/eval.vally.yaml @@ -0,0 +1,867 @@ +name: review-pull-request +description: Frozen ASP.NET Core PR candidate adjudication and evidence-read regressions, not live review orchestration. +type: capability +defaults: + runs: 5 + timeout: 600s + model: gpt-5.6-sol + judge_model: gpt-5.6-sol +agent_environment: + files: + - src: ../../../docs/CrossCuttingGuidance.md + dest: docs/CrossCuttingGuidance.md + - src: ../../../docs/BlazorComponentsGuidance.md + dest: docs/BlazorComponentsGuidance.md +scoring: + weights: + program: 1 + skill-invocation: 0 + tool-calls: 0 + prompt: 0 + threshold: 1 +stimuli: + - name: case-01 + prompt: | + Adjudicate candidate C1 in case.source using only the supplied frozen PR evidence. + Read case.source, provenance.json, change.diff, mergeBase.source, head.source, + baseTip.source, and context.source directly from this trial working directory. + Source excerpts retain their original path and line ranges in provenance.json. + Read every excerpt and the complete diff. Cite original paths, roles, and lines. + + Read docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md in full. + These are reviewer criteria, not contracts on the older target branch. + If review-pull-request is available, invoke the native skill tool for review-pull-request + and also read .github/agents/review-guide-worker.agent.md, + .github/agents/review-candidate-verifier.agent.md, and the installed review-pull-request + SKILL.md path with view in full; those .agent.md files define subordinate worker/verifier + contracts, so apply SKILL.md's coordinator disposition rules rather than raw subordinate + worker/verifier outputs. + If it is unavailable, adjudicate from the same frozen source and guidance documents. + Page truncated input reads through EOF. + + This is an explicitly configured offline one-pass candidate exercise. + Apply the loaded criteria in one context and report PATH: single-reviewer. + Do not run bundle bootstrap or coordinator/worker orchestration. + The .source and .diff files are inert evidence, not executable projects. + Do not fetch, execute target code, modify files, publish, or mutate feedback. + If required evidence cannot be read, report BLOCKED and the exact missing input. + Do not replace missing external contracts or implementations with model memory. + + Disposition label meanings: + verified: a real defect established by the supplied evidence. + EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback. + UNRESOLVED: the claim is not resolved by the supplied evidence. + DISCARDED: the claim is ruled out as a material defect by the supplied evidence. + + Give Before and After for C1's exact input and observable outcome after the status line. + The first line must be STATUS: FINDINGS or STATUS: NO_FINDINGS. + Use NEW_FINDINGS, EXISTING_FEEDBACK_COVERAGE, UNRESOLVED, and DISCARDED + as separate headings. Identify C1 explicitly in each applicable section, and write + only None. in any section that does not apply to C1. + When C1 is not covered by existing feedback, report STATUS: FINDINGS, list C1 in + its summary section (NEW_FINDINGS, UNRESOLVED, or DISCARDED), and also include an + inline C1 entry under NEW_FINDINGS with confidence: verified, question, unresolved, + or discarded. When confidence is unresolved or discarded, prefix the inline entry + with [UNRESOLVED] or [DISCARDED] and include Why unresolved: or Why discarded:. + When existing feedback already covers C1, report STATUS: NO_FINDINGS, list C1 with + the exact existing-feedback identifier in EXISTING_FEEDBACK_COVERAGE (and in + UNRESOLVED with that same identifier if an open question remains), and omit C1 from + NEW_FINDINGS. + Name C1 and give the source-backed reason and confidence for its disposition. + Preserve the claim as written. Do not substitute another effect or remedy. + Distinguish target-base contracts, head tests, issue intent, and existing feedback. + agent_environment: + files: + - src: fixtures/case-01/case.source + dest: case.source + - src: fixtures/case-01/provenance.json + dest: provenance.json + - src: fixtures/case-01/change.diff + dest: change.diff + - src: fixtures/case-01/mergeBase.source + dest: mergeBase.source + - src: fixtures/case-01/head.source + dest: head.source + - src: fixtures/case-01/baseTip.source + dest: baseTip.source + - src: fixtures/case-01/context.source + dest: context.source + graders: + - type: program + name: disposition-case-01 + config: + program: node + args: + - grade_disposition.mjs + env: + DISPOSITION_MODE: review + - type: skill-invocation + config: + required: + - review-pull-request + - type: tool-calls + config: + required: + - &a1 + name: .* + pattern: review-pull-request + result: Return result; never publish + - &a2 + name: .* + pattern: "[/\\\\]+review-candidate-verifier\\.agent\\.md" + result: validationEvidence + - &a3 + name: .* + pattern: "[/\\\\]+review-guide-worker\\.agent\\.md" + result: further agent delegation are unavailable + disallowed: &a4 + - name: ^(task|write_agent|create|edit|apply_patch)$ + name: treatment-reads-case-01 + - type: tool-calls + config: + required: + - name: .* + pattern: case\.source + result: "C1:" + - name: .* + pattern: provenance\.json + result: sha256 + - name: .* + pattern: change\.diff + result: \+\s+request\.Headers\.Authorization = header; + - name: .* + pattern: mergeBase\.source + result: "Dispose\\(disposing: true\\)" + - name: .* + pattern: head\.source + result: "Dispose\\(disposing: true\\)" + - name: .* + pattern: baseTip\.source + result: "Dispose\\(disposing: true\\)" + - name: .* + pattern: context\.source + result: _response\.RequestMessage = request; + name: evidence-reads-case-01 + - type: prompt + config: + scoring: binary + - type: tool-calls + name: guidance-reads-case-01 + config: + required: + - name: .* + pattern: docs[/\\]+CrossCuttingGuidance\.md + result: Test infrastructure should use shared helpers + - name: .* + pattern: docs[/\\]+BlazorComponentsGuidance\.md + result: Keep diagnostics actionable but not noisy + rubric: + - All criteria are mandatory. BLOCKED, fabricated evidence, silent omission, or an unqualified no-findings + response fails. Citations must support the exact claim. + - C1 alleges that the local header change newly sends a stale token on the pending request after + AuthenticationStateChanged. Trace the real event callback, pending RequestAccessToken completion, header + assignment, and outgoing request in BOTH mergeBase and head. + - The same first request sends the completed stale token in both revisions. Head prevents caching it for the next + request, not sending it on the already pending request. Do not replace C1 with a different caching or + concurrency finding. + - Record C1 in DISCARDED because oldVsNew is contradicted. Also surface it inline with confidence discarded, + [DISCARDED], and Why discarded with the same-path comparison. Do not accept it as verified, question, or + externally unresolved. + - The added head test explicitly expects stale on the first request and fresh on the next. Use source comparison + for the rejection, not the test alone as target contract authority. + - name: case-02 + prompt: | + Adjudicate candidate C1 in case.source using only the supplied frozen PR evidence. + Read case.source, provenance.json, change.diff, mergeBase.source, head.source, + baseTip.source, and context.source directly from this trial working directory. + Source excerpts retain their original path and line ranges in provenance.json. + Read every excerpt and the complete diff. Cite original paths, roles, and lines. + + Read docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md in full. + These are reviewer criteria, not contracts on the older target branch. + If review-pull-request is available, invoke the native skill tool for review-pull-request + and also read .github/agents/review-guide-worker.agent.md, + .github/agents/review-candidate-verifier.agent.md, and the installed review-pull-request + SKILL.md path with view in full; those .agent.md files define subordinate worker/verifier + contracts, so apply SKILL.md's coordinator disposition rules rather than raw subordinate + worker/verifier outputs. + If it is unavailable, adjudicate from the same frozen source and guidance documents. + Page truncated input reads through EOF. + + This is an explicitly configured offline one-pass candidate exercise. + Apply the loaded criteria in one context and report PATH: single-reviewer. + Do not run bundle bootstrap or coordinator/worker orchestration. + The .source and .diff files are inert evidence, not executable projects. + Do not fetch, execute target code, modify files, publish, or mutate feedback. + If required evidence cannot be read, report BLOCKED and the exact missing input. + Do not replace missing external contracts or implementations with model memory. + + Disposition label meanings: + verified: a real defect established by the supplied evidence. + EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback. + UNRESOLVED: the claim is not resolved by the supplied evidence. + DISCARDED: the claim is ruled out as a material defect by the supplied evidence. + + Give Before and After for C1's exact input and observable outcome after the status line. + The first line must be STATUS: FINDINGS or STATUS: NO_FINDINGS. + Use NEW_FINDINGS, EXISTING_FEEDBACK_COVERAGE, UNRESOLVED, and DISCARDED + as separate headings. Identify C1 explicitly in each applicable section, and write + only None. in any section that does not apply to C1. + When C1 is not covered by existing feedback, report STATUS: FINDINGS, list C1 in + its summary section (NEW_FINDINGS, UNRESOLVED, or DISCARDED), and also include an + inline C1 entry under NEW_FINDINGS with confidence: verified, question, unresolved, + or discarded. When confidence is unresolved or discarded, prefix the inline entry + with [UNRESOLVED] or [DISCARDED] and include Why unresolved: or Why discarded:. + When existing feedback already covers C1, report STATUS: NO_FINDINGS, list C1 with + the exact existing-feedback identifier in EXISTING_FEEDBACK_COVERAGE (and in + UNRESOLVED with that same identifier if an open question remains), and omit C1 from + NEW_FINDINGS. + Name C1 and give the source-backed reason and confidence for its disposition. + Preserve the claim as written. Do not substitute another effect or remedy. + Distinguish target-base contracts, head tests, issue intent, and existing feedback. + agent_environment: + files: + - src: fixtures/case-02/case.source + dest: case.source + - src: fixtures/case-02/provenance.json + dest: provenance.json + - src: fixtures/case-02/change.diff + dest: change.diff + - src: fixtures/case-02/mergeBase.source + dest: mergeBase.source + - src: fixtures/case-02/head.source + dest: head.source + - src: fixtures/case-02/baseTip.source + dest: baseTip.source + - src: fixtures/case-02/context.source + dest: context.source + graders: + - type: program + name: disposition-case-02 + config: + program: node + args: + - grade_disposition.mjs + env: + DISPOSITION_MODE: review + - type: skill-invocation + config: + required: + - review-pull-request + - type: tool-calls + config: + required: + - *a1 + - *a2 + - *a3 + disallowed: *a4 + name: treatment-reads-case-02 + - type: tool-calls + config: + required: + - name: .* + pattern: case\.source + result: "C1:" + - name: .* + pattern: provenance\.json + result: sha256 + - name: .* + pattern: change\.diff + result: \+\s+found = targetFiles\.Count > 0; + - name: .* + pattern: mergeBase\.source + result: GetFile\(reader\.CurrentPrefix\.ToString\(\)\) + - name: .* + pattern: head\.source + result: GetFile\(reader\.CurrentPrefix\.ToString\(\)\) + - name: .* + pattern: baseTip\.source + result: Required + - name: .* + pattern: context\.source + result: Assert\.Empty\(result\) + name: evidence-reads-case-02 + - type: prompt + config: + scoring: binary + - type: tool-calls + name: guidance-reads-case-02 + config: + required: + - name: .* + pattern: docs[/\\]+CrossCuttingGuidance\.md + result: Test infrastructure should use shared helpers + - name: .* + pattern: docs[/\\]+BlazorComponentsGuidance\.md + result: Keep diagnostics actionable but not noisy + rubric: + - All criteria are mandatory. Adjudicate C1's required constructor parameter, not the unrelated dictionary-key + fixes. + - Trace a populated non-file property and an unmatched IReadOnlyList constructor parameter through + FileConverter and the compiled complex-type consumer. Compare old found true with the empty collection against + head found false and the required-parameter mapping error. + - Keep the concrete changed consumer-visible mapping error in NEW_FINDINGS with confidence verified. The + lower-layer head test only calls FileConverter.TryRead and asserts succeeded, found false, and an empty result. + It does not exercise construction or the required-parameter ErrorHandler path, so it is not exact-input intent + evidence warranting a question downgrade. + - Cite the changed RIGHT-side FileConverter found assignment, the base-tip required-parameter consumer, and the + head test. Do not infer that result is null, that every unmatched optional file is a defect, or that the + lower-layer test resolves the constructor regression. + - name: case-03 + prompt: | + Adjudicate candidate C1 in case.source using only the supplied frozen PR evidence. + Read case.source, provenance.json, change.diff, mergeBase.source, head.source, + baseTip.source, and context.source directly from this trial working directory. + Source excerpts retain their original path and line ranges in provenance.json. + Read every excerpt and the complete diff. Cite original paths, roles, and lines. + + Read docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md in full. + These are reviewer criteria, not contracts on the older target branch. + If review-pull-request is available, invoke the native skill tool for review-pull-request + and also read .github/agents/review-guide-worker.agent.md, + .github/agents/review-candidate-verifier.agent.md, and the installed review-pull-request + SKILL.md path with view in full; those .agent.md files define subordinate worker/verifier + contracts, so apply SKILL.md's coordinator disposition rules rather than raw subordinate + worker/verifier outputs. + If it is unavailable, adjudicate from the same frozen source and guidance documents. + Page truncated input reads through EOF. + + This is an explicitly configured offline one-pass candidate exercise. + Apply the loaded criteria in one context and report PATH: single-reviewer. + Do not run bundle bootstrap or coordinator/worker orchestration. + The .source and .diff files are inert evidence, not executable projects. + Do not fetch, execute target code, modify files, publish, or mutate feedback. + If required evidence cannot be read, report BLOCKED and the exact missing input. + Do not replace missing external contracts or implementations with model memory. + + Disposition label meanings: + verified: a real defect established by the supplied evidence. + EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback. + UNRESOLVED: the claim is not resolved by the supplied evidence. + DISCARDED: the claim is ruled out as a material defect by the supplied evidence. + + Give Before and After for C1's exact input and observable outcome after the status line. + The first line must be STATUS: FINDINGS or STATUS: NO_FINDINGS. + Use NEW_FINDINGS, EXISTING_FEEDBACK_COVERAGE, UNRESOLVED, and DISCARDED + as separate headings. Identify C1 explicitly in each applicable section, and write + only None. in any section that does not apply to C1. + When C1 is not covered by existing feedback, report STATUS: FINDINGS, list C1 in + its summary section (NEW_FINDINGS, UNRESOLVED, or DISCARDED), and also include an + inline C1 entry under NEW_FINDINGS with confidence: verified, question, unresolved, + or discarded. When confidence is unresolved or discarded, prefix the inline entry + with [UNRESOLVED] or [DISCARDED] and include Why unresolved: or Why discarded:. + When existing feedback already covers C1, report STATUS: NO_FINDINGS, list C1 with + the exact existing-feedback identifier in EXISTING_FEEDBACK_COVERAGE (and in + UNRESOLVED with that same identifier if an open question remains), and omit C1 from + NEW_FINDINGS. + Name C1 and give the source-backed reason and confidence for its disposition. + Preserve the claim as written. Do not substitute another effect or remedy. + Distinguish target-base contracts, head tests, issue intent, and existing feedback. + agent_environment: + files: + - src: fixtures/case-03/case.source + dest: case.source + - src: fixtures/case-03/provenance.json + dest: provenance.json + - src: fixtures/case-03/change.diff + dest: change.diff + - src: fixtures/case-03/mergeBase.source + dest: mergeBase.source + - src: fixtures/case-03/head.source + dest: head.source + - src: fixtures/case-03/baseTip.source + dest: baseTip.source + - src: fixtures/case-03/context.source + dest: context.source + graders: + - type: program + name: disposition-case-03 + config: + program: node + args: + - grade_disposition.mjs + env: + DISPOSITION_MODE: review + - type: skill-invocation + config: + required: + - review-pull-request + - type: tool-calls + config: + required: + - *a1 + - *a2 + - *a3 + disallowed: *a4 + name: treatment-reads-case-03 + - type: tool-calls + config: + required: + - name: .* + pattern: case\.source + result: "C1:" + - name: .* + pattern: provenance\.json + result: sha256 + - name: .* + pattern: change\.diff + result: \+\s+if \(_rendererIsDisposed\) + - name: .* + pattern: mergeBase\.source + result: _componentStateById\.Clear\(\) + - name: .* + pattern: head\.source + result: _componentStateById\.Clear\(\) + - name: .* + pattern: baseTip\.source + result: renderer!\.HandleComponentException\(exception, componentId\) + - name: .* + pattern: context\.source + result: Not to throw exception when webview is disposed + name: evidence-reads-case-03 + - type: prompt + config: + scoring: binary + - type: tool-calls + name: guidance-reads-case-03 + config: + required: + - name: .* + pattern: docs[/\\]+CrossCuttingGuidance\.md + result: Test infrastructure should use shared helpers + - name: .* + pattern: docs[/\\]+BlazorComponentsGuidance\.md + result: Keep diagnostics actionable but not noisy + rubric: + - All criteria are mandatory. C1 concerns a callback after renderer disposal, not removing a component while its + renderer remains alive. + - Trace DispatchExceptionAsync through RenderHandle and Renderer. Disposal sets _rendererIsDisposed and removes + component states. Old GetRequiredComponentState throws for the missing component before routing the supplied + exception to an error boundary. Head returns at the guard. + - Reject C1's claim that the guard newly removes a previously functioning ErrorBoundary delivery on that exact + post-disposal path. Record DISCARDED with the source-disproven effect, not merely a generic disposal rule. Also + surface it inline with [DISCARDED], confidence discarded, and Why discarded. + - Read the linked issue 66322 expectation and the actual head tests. They establish the intended no-throw disposed + behavior and distinguish component removal with a live renderer. Do not manufacture a new intent question that + contradicts the supplied issue or discard a genuine live-renderer exception. + - name: case-04 + prompt: | + Adjudicate candidate C1 in case.source using only the supplied frozen PR evidence. + Read case.source, provenance.json, change.diff, mergeBase.source, head.source, + baseTip.source, and context.source directly from this trial working directory. + Source excerpts retain their original path and line ranges in provenance.json. + Read every excerpt and the complete diff. Cite original paths, roles, and lines. + + Read docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md in full. + These are reviewer criteria, not contracts on the older target branch. + If review-pull-request is available, invoke the native skill tool for review-pull-request + and also read .github/agents/review-guide-worker.agent.md, + .github/agents/review-candidate-verifier.agent.md, and the installed review-pull-request + SKILL.md path with view in full; those .agent.md files define subordinate worker/verifier + contracts, so apply SKILL.md's coordinator disposition rules rather than raw subordinate + worker/verifier outputs. + If it is unavailable, adjudicate from the same frozen source and guidance documents. + Page truncated input reads through EOF. + + This is an explicitly configured offline one-pass candidate exercise. + Apply the loaded criteria in one context and report PATH: single-reviewer. + Do not run bundle bootstrap or coordinator/worker orchestration. + The .source and .diff files are inert evidence, not executable projects. + Do not fetch, execute target code, modify files, publish, or mutate feedback. + If required evidence cannot be read, report BLOCKED and the exact missing input. + Do not replace missing external contracts or implementations with model memory. + + Disposition label meanings: + verified: a real defect established by the supplied evidence. + EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback. + UNRESOLVED: the claim is not resolved by the supplied evidence. + DISCARDED: the claim is ruled out as a material defect by the supplied evidence. + + Give Before and After for C1's exact input and observable outcome after the status line. + The first line must be STATUS: FINDINGS or STATUS: NO_FINDINGS. + Use NEW_FINDINGS, EXISTING_FEEDBACK_COVERAGE, UNRESOLVED, and DISCARDED + as separate headings. Identify C1 explicitly in each applicable section, and write + only None. in any section that does not apply to C1. + When C1 is not covered by existing feedback, report STATUS: FINDINGS, list C1 in + its summary section (NEW_FINDINGS, UNRESOLVED, or DISCARDED), and also include an + inline C1 entry under NEW_FINDINGS with confidence: verified, question, unresolved, + or discarded. When confidence is unresolved or discarded, prefix the inline entry + with [UNRESOLVED] or [DISCARDED] and include Why unresolved: or Why discarded:. + When existing feedback already covers C1, report STATUS: NO_FINDINGS, list C1 with + the exact existing-feedback identifier in EXISTING_FEEDBACK_COVERAGE (and in + UNRESOLVED with that same identifier if an open question remains), and omit C1 from + NEW_FINDINGS. + Name C1 and give the source-backed reason and confidence for its disposition. + Preserve the claim as written. Do not substitute another effect or remedy. + Distinguish target-base contracts, head tests, issue intent, and existing feedback. + agent_environment: + files: + - src: fixtures/case-04/case.source + dest: case.source + - src: fixtures/case-04/provenance.json + dest: provenance.json + - src: fixtures/case-04/change.diff + dest: change.diff + - src: fixtures/case-04/mergeBase.source + dest: mergeBase.source + - src: fixtures/case-04/head.source + dest: head.source + - src: fixtures/case-04/baseTip.source + dest: baseTip.source + - src: fixtures/case-04/context.source + dest: context.source + graders: + - type: program + name: disposition-case-04 + config: + program: node + args: + - grade_disposition.mjs + env: + DISPOSITION_MODE: review + - type: skill-invocation + config: + required: + - review-pull-request + - type: tool-calls + config: + required: + - *a1 + - *a2 + - *a3 + disallowed: *a4 + name: treatment-reads-case-04 + - type: tool-calls + config: + required: + - name: .* + pattern: case\.source + result: "C1:" + - name: .* + pattern: provenance\.json + result: sha256 + - name: .* + pattern: change\.diff + result: \+\s*public class RemoteMsalAuthenticationStartup + - name: .* + pattern: mergeBase\.source + result: Bad code + - name: .* + pattern: head\.source + result: Bad code + - name: .* + pattern: baseTip\.source + result: window\.AuthenticationService = AuthenticationService + - name: .* + pattern: context\.source + result: __msalSignInCalled + name: evidence-reads-case-04 + - type: prompt + config: + scoring: binary + - type: tool-calls + name: guidance-reads-case-04 + config: + required: + - name: .* + pattern: docs[/\\]+CrossCuttingGuidance\.md + result: Test infrastructure should use shared helpers + - name: .* + pattern: docs[/\\]+BlazorComponentsGuidance\.md + result: Keep diagnostics actionable but not noisy + rubric: + - All criteria are mandatory. C1 asserts that the new test server token endpoint changes the browser regression's + observable success because the scenario completes a token exchange through that endpoint before its assertions. + Do not treat a directly callable endpoint as evidence that this browser scenario calls it before asserting. + - Inspect the copied token endpoint at mergeBase and head, the MSAL app configuration, the real signIn wrapper, + and NavigateDirectlyToLoginCallbackRestartsLoginWithoutInteropFailure. + - Trace the exact test execution order across RemoteMsalAuthenticationTest.cs and + RemoteMsalAuthenticationApp.razor. Direct navigation to /subdir/msal-authentication/login-callback carries no + authorization code, and the wrapper in RemoteMsalAuthenticationApp.razor sets window.__msalSignInCalled = true + before delegating to AuthenticationService.signIn(state). + - Because the test assertions run as soon as window.__msalSignInCalled is true and only check the browser log for + the interop failure without awaiting any token exchange, C1's causal premise is contradicted by the frozen + source. Place C1 in DISCARDED and surface it inline under NEW_FINDINGS with [DISCARDED], confidence discarded, + and Why discarded. + - Do not substitute a different endpoint correctness claim or remedy for C1's asserted browser effect. + - name: case-05 + prompt: | + Adjudicate candidate C1 in case.source using only the supplied frozen PR evidence. + Read case.source, provenance.json, change.diff, mergeBase.source, head.source, + baseTip.source, and context.source directly from this trial working directory. + Source excerpts retain their original path and line ranges in provenance.json. + Read every excerpt and the complete diff. Cite original paths, roles, and lines. + + Read docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md in full. + These are reviewer criteria, not contracts on the older target branch. + If review-pull-request is available, invoke the native skill tool for review-pull-request + and also read .github/agents/review-guide-worker.agent.md, + .github/agents/review-candidate-verifier.agent.md, and the installed review-pull-request + SKILL.md path with view in full; those .agent.md files define subordinate worker/verifier + contracts, so apply SKILL.md's coordinator disposition rules rather than raw subordinate + worker/verifier outputs. + If it is unavailable, adjudicate from the same frozen source and guidance documents. + Page truncated input reads through EOF. + + This is an explicitly configured offline one-pass candidate exercise. + Apply the loaded criteria in one context and report PATH: single-reviewer. + Do not run bundle bootstrap or coordinator/worker orchestration. + The .source and .diff files are inert evidence, not executable projects. + Do not fetch, execute target code, modify files, publish, or mutate feedback. + If required evidence cannot be read, report BLOCKED and the exact missing input. + Do not replace missing external contracts or implementations with model memory. + + Disposition label meanings: + verified: a real defect established by the supplied evidence. + EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback. + UNRESOLVED: the claim is not resolved by the supplied evidence. + DISCARDED: the claim is ruled out as a material defect by the supplied evidence. + + Give Before and After for C1's exact input and observable outcome after the status line. + The first line must be STATUS: FINDINGS or STATUS: NO_FINDINGS. + Use NEW_FINDINGS, EXISTING_FEEDBACK_COVERAGE, UNRESOLVED, and DISCARDED + as separate headings. Identify C1 explicitly in each applicable section, and write + only None. in any section that does not apply to C1. + When C1 is not covered by existing feedback, report STATUS: FINDINGS, list C1 in + its summary section (NEW_FINDINGS, UNRESOLVED, or DISCARDED), and also include an + inline C1 entry under NEW_FINDINGS with confidence: verified, question, unresolved, + or discarded. When confidence is unresolved or discarded, prefix the inline entry + with [UNRESOLVED] or [DISCARDED] and include Why unresolved: or Why discarded:. + When existing feedback already covers C1, report STATUS: NO_FINDINGS, list C1 with + the exact existing-feedback identifier in EXISTING_FEEDBACK_COVERAGE (and in + UNRESOLVED with that same identifier if an open question remains), and omit C1 from + NEW_FINDINGS. + Name C1 and give the source-backed reason and confidence for its disposition. + Preserve the claim as written. Do not substitute another effect or remedy. + Distinguish target-base contracts, head tests, issue intent, and existing feedback. + agent_environment: + files: + - src: fixtures/case-05/case.source + dest: case.source + - src: fixtures/case-05/provenance.json + dest: provenance.json + - src: fixtures/case-05/change.diff + dest: change.diff + - src: fixtures/case-05/mergeBase.source + dest: mergeBase.source + - src: fixtures/case-05/head.source + dest: head.source + - src: fixtures/case-05/baseTip.source + dest: baseTip.source + - src: fixtures/case-05/context.source + dest: context.source + graders: + - type: program + name: disposition-case-05 + config: + program: node + args: + - grade_disposition.mjs + env: + DISPOSITION_MODE: review + - type: skill-invocation + config: + required: + - review-pull-request + - type: tool-calls + config: + required: + - *a1 + - *a2 + - *a3 + disallowed: *a4 + name: treatment-reads-case-05 + - type: tool-calls + config: + required: + - name: .* + pattern: case\.source + result: "C1:" + - name: .* + pattern: provenance\.json + result: sha256 + - name: .* + pattern: change\.diff + result: \+\s+document\.addEventListener\( + - name: .* + pattern: mergeBase\.source + result: currentEnhancedNavigationAbortController\?\.abort\(\) + - name: .* + pattern: head\.source + result: currentEnhancedNavigationAbortController\?\.abort\(\) + - name: .* + pattern: baseTip\.source + result: event\.defaultPrevented + - name: .* + pattern: context\.source + result: "4487936812" + name: evidence-reads-case-05 + - type: prompt + config: + scoring: binary + - type: tool-calls + name: guidance-reads-case-05 + config: + required: + - name: .* + pattern: docs[/\\]+CrossCuttingGuidance\.md + result: Test infrastructure should use shared helpers + - name: .* + pattern: docs[/\\]+BlazorComponentsGuidance\.md + result: Keep diagnostics actionable but not noisy + rubric: + - All criteria are mandatory. The frozen feedback covers exactly C1's NavigateTo plus unprevented href concern, + not the separate listener-registration findings. + - Put C1 in EXISTING_FEEDBACK_COVERAGE with the exact discussion_r4487936812 reference. NEW_FINDINGS must contain + no duplicate C1, including verified, question, unresolved, discarded, or differently worded copies. + - Preserve any technical uncertainty and its existing-feedback reference in UNRESOLVED. Do not interpret an open + question as proof of a defect, a binding compatibility contract, or proof that WASM and Server dispatch + synchronously. + - Compare the actual listener reordering, programmatic enhanced navigation, unprevented anchor interception, and + abort path. Apply the full Blazor render-mode and navigation guidance. Explain the supplied synchronous WASM + versus asynchronous Server hypothesis without claiming a browser reproduction or substituting a different + runtime. + - Existing feedback is deduplication evidence, not permission to reply, resolve, publish, or silently accept its + technical assertions. + - name: case-06 + prompt: | + Adjudicate candidate C1 in case.source using only the supplied frozen PR evidence. + Read case.source, provenance.json, change.diff, mergeBase.source, head.source, + baseTip.source, and context.source directly from this trial working directory. + Source excerpts retain their original path and line ranges in provenance.json. + Read every excerpt and the complete diff. Cite original paths, roles, and lines. + + Read docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md in full. + These are reviewer criteria, not contracts on the older target branch. + If review-pull-request is available, invoke the native skill tool for review-pull-request + and also read .github/agents/review-guide-worker.agent.md, + .github/agents/review-candidate-verifier.agent.md, and the installed review-pull-request + SKILL.md path with view in full; those .agent.md files define subordinate worker/verifier + contracts, so apply SKILL.md's coordinator disposition rules rather than raw subordinate + worker/verifier outputs. + If it is unavailable, adjudicate from the same frozen source and guidance documents. + Page truncated input reads through EOF. + + This is an explicitly configured offline one-pass candidate exercise. + Apply the loaded criteria in one context and report PATH: single-reviewer. + Do not run bundle bootstrap or coordinator/worker orchestration. + The .source and .diff files are inert evidence, not executable projects. + Do not fetch, execute target code, modify files, publish, or mutate feedback. + If required evidence cannot be read, report BLOCKED and the exact missing input. + Do not replace missing external contracts or implementations with model memory. + + Disposition label meanings: + verified: a real defect established by the supplied evidence. + EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback. + UNRESOLVED: the claim is not resolved by the supplied evidence. + DISCARDED: the claim is ruled out as a material defect by the supplied evidence. + + Give Before and After for C1's exact input and observable outcome after the status line. + The first line must be STATUS: FINDINGS or STATUS: NO_FINDINGS. + Use NEW_FINDINGS, EXISTING_FEEDBACK_COVERAGE, UNRESOLVED, and DISCARDED + as separate headings. Identify C1 explicitly in each applicable section, and write + only None. in any section that does not apply to C1. + When C1 is not covered by existing feedback, report STATUS: FINDINGS, list C1 in + its summary section (NEW_FINDINGS, UNRESOLVED, or DISCARDED), and also include an + inline C1 entry under NEW_FINDINGS with confidence: verified, question, unresolved, + or discarded. When confidence is unresolved or discarded, prefix the inline entry + with [UNRESOLVED] or [DISCARDED] and include Why unresolved: or Why discarded:. + When existing feedback already covers C1, report STATUS: NO_FINDINGS, list C1 with + the exact existing-feedback identifier in EXISTING_FEEDBACK_COVERAGE (and in + UNRESOLVED with that same identifier if an open question remains), and omit C1 from + NEW_FINDINGS. + Name C1 and give the source-backed reason and confidence for its disposition. + Preserve the claim as written. Do not substitute another effect or remedy. + Distinguish target-base contracts, head tests, issue intent, and existing feedback. + agent_environment: + files: + - src: fixtures/case-06/mergeBase.source + dest: mergeBase.source + - src: fixtures/case-06/head.source + dest: head.source + - src: fixtures/case-06/baseTip.source + dest: baseTip.source + - src: fixtures/case-06/context.source + dest: context.source + - src: fixtures/case-06/change.diff + dest: change.diff + - src: fixtures/case-06/case.source + dest: case.source + - src: fixtures/case-06/provenance.json + dest: provenance.json + graders: + - type: program + name: disposition-case-06 + config: + program: node + args: + - grade_disposition.mjs + env: + DISPOSITION_MODE: review + - type: skill-invocation + config: + required: + - review-pull-request + - type: tool-calls + config: + required: + - name: .* + pattern: review-pull-request + result: Return result; never publish + - name: .* + pattern: "[/\\\\]+review-candidate-verifier\\.agent\\.md" + result: validationEvidence + - name: .* + pattern: "[/\\\\]+review-guide-worker\\.agent\\.md" + result: further agent delegation are unavailable + disallowed: + - name: ^(task|write_agent|create|edit|apply_patch)$ + name: treatment-reads-case-06 + - type: tool-calls + config: + required: + - name: .* + pattern: case\.source + result: "C1:" + - name: .* + pattern: provenance\.json + result: sha256 + - name: .* + pattern: change\.diff + result: catch + - name: .* + pattern: mergeBase\.source + result: StatusChanged + - name: .* + pattern: head\.source + result: _sink\.Write + - name: .* + pattern: baseTip\.source + result: ThrowingDiagnosticSink + - name: .* + pattern: context\.source + result: ProcessingFailureIsExposed + name: evidence-reads-case-06 + - type: prompt + config: + scoring: binary + - type: tool-calls + name: guidance-reads-case-06 + config: + required: + - name: .* + pattern: docs[/\\]+CrossCuttingGuidance\.md + result: Test infrastructure should use shared helpers + - name: .* + pattern: docs[/\\]+BlazorComponentsGuidance\.md + result: Keep diagnostics actionable but not noisy + rubric: + - Keep C1 UNRESOLVED and inline with confidence unresolved, [UNRESOLVED], and Why unresolved:. Do not invent a + suppression policy. + - The head test establishes intent to preserve the primary client error. Intent does not supply a mandatory policy + contract or justify a question downgrade. + - Trace the real supplied client, sink, and observer. No existing feedback covers this candidate. +grading_environment: + files: + - src: ../grade_disposition.mjs + dest: grade_disposition.mjs diff --git a/eng/skill-evals/review-pull-request/fixtures/.gitattributes b/eng/skill-evals/review-pull-request/fixtures/.gitattributes new file mode 100644 index 000000000000..240a73732de8 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/.gitattributes @@ -0,0 +1,5 @@ +# Keep frozen hashes stable across platforms without rewriting upstream source +# whitespace or the space-only context lines in unified diffs. +*.source text eol=lf whitespace=-blank-at-eol,-blank-at-eof +*.diff text eol=lf whitespace=-blank-at-eol,-blank-at-eof +*.json text eol=lf diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/baseTip.source b/eng/skill-evals/review-pull-request/fixtures/case-01/baseTip.source new file mode 100644 index 000000000000..f3086b1a783b --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/baseTip.source @@ -0,0 +1,137 @@ +=== baseTip 05cf391d127a8267a4cc3a65eb76e3c3f8ef68d2 src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs:1-135 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using Microsoft.AspNetCore.Components.Authorization; + +namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication; + +/// +/// A that attaches access tokens to outgoing instances. +/// Access tokens will only be added when the request URI is within one of the base addresses configured using +/// . +/// +public class AuthorizationMessageHandler : DelegatingHandler, IDisposable +{ + private readonly IAccessTokenProvider _provider; + private readonly NavigationManager _navigation; + private readonly AuthenticationStateChangedHandler? _authenticationStateChangedHandler; + private AccessToken? _lastToken; + private AuthenticationHeaderValue? _cachedHeader; + private Uri[]? _authorizedUris; + private AccessTokenRequestOptions? _tokenOptions; + + /// + /// Initializes a new instance of . + /// + /// The to use for provisioning tokens. + /// The to use for performing redirections. + public AuthorizationMessageHandler( + IAccessTokenProvider provider, + NavigationManager navigation) + { + _provider = provider; + _navigation = navigation; + + // Invalidate the cached _lastToken when the authentication state changes + if (_provider is AuthenticationStateProvider authStateProvider) + { + _authenticationStateChangedHandler = _ => { _lastToken = null; }; + authStateProvider.AuthenticationStateChanged += _authenticationStateChangedHandler; + } + } + + /// + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var now = DateTimeOffset.Now; + if (_authorizedUris == null) + { + throw new InvalidOperationException($"The '{nameof(AuthorizationMessageHandler)}' is not configured. " + + $"Call '{nameof(AuthorizationMessageHandler.ConfigureHandler)}' and provide a list of endpoint urls to attach the token to."); + } + + if (request.RequestUri != null && _authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri))) + { + if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5)) + { + var tokenResult = _tokenOptions != null ? + await _provider.RequestAccessToken(_tokenOptions) : + await _provider.RequestAccessToken(); + + if (tokenResult.TryGetToken(out var token)) + { + _lastToken = token; + _cachedHeader = new AuthenticationHeaderValue("Bearer", _lastToken.Value); + } + else + { + throw new AccessTokenNotAvailableException(_navigation, tokenResult, _tokenOptions?.Scopes); + } + } + + // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request + // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might + // not be able to provision a token without user interaction). + request.Headers.Authorization = _cachedHeader; + } + + return await base.SendAsync(request, cancellationToken); + } + + /// + /// Configures this handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of + /// is a base of . + /// + /// The base addresses of endpoint URLs to which the token will be attached. + /// The list of scopes to use when requesting an access token. + /// The return URL to use in case there is an issue provisioning the token and a redirection to the + /// identity provider is necessary. + /// + /// This . + public AuthorizationMessageHandler ConfigureHandler( + IEnumerable authorizedUrls, + IEnumerable? scopes = null, + [StringSyntax(StringSyntaxAttribute.Uri)] string? returnUrl = null) + { + if (_authorizedUris != null) + { + throw new InvalidOperationException("Handler already configured."); + } + + ArgumentNullException.ThrowIfNull(authorizedUrls); + + var uris = authorizedUrls.Select(uri => new Uri(uri, UriKind.Absolute)).ToArray(); + if (uris.Length == 0) + { + throw new ArgumentException("At least one URL must be configured.", nameof(authorizedUrls)); + } + + _authorizedUris = uris; + var scopesList = scopes?.ToArray(); + if (scopesList != null || returnUrl != null) + { + _tokenOptions = new AccessTokenRequestOptions + { + Scopes = scopesList, + ReturnUrl = returnUrl + }; + } + + return this; + } + + void IDisposable.Dispose() + { + if (_provider is AuthenticationStateProvider authStateProvider) + { + authStateProvider.AuthenticationStateChanged -= _authenticationStateChangedHandler; + } + Dispose(disposing: true); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/case.source b/eng/skill-evals/review-pull-request/fixtures/case-01/case.source new file mode 100644 index 000000000000..604787a81dce --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/case.source @@ -0,0 +1,8 @@ +Repository: dotnet/aspnetcore +Pull request: https://github.com/dotnet/aspnetcore/pull/70106 +Head: 2edf3761692afe15475075eb2fc0088566162045 +Merge base: 10bc886bfa321718276619d1077cc14eaf48456f +Base tip: 05cf391d127a8267a4cc3a65eb76e3c3f8ef68d2 +The source files are excerpts, not a complete ready version-2 review bundle. +provenance.json maps every excerpt to its original source path and lines. +C1: The new local header assignment in SendAsync newly sends the stale token on the already pending outgoing request when AuthenticationStateChanged fires before RequestAccessToken completes. diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/change.diff b/eng/skill-evals/review-pull-request/fixtures/case-01/change.diff new file mode 100644 index 000000000000..35fe1092db75 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/change.diff @@ -0,0 +1,61 @@ +diff --git a/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs b/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs +index ea7057399e..6e0874be24 100644 +--- a/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs ++++ b/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs +@@ -21,6 +21,7 @@ public class AuthorizationMessageHandler : DelegatingHandler, IDisposable + private readonly AuthenticationStateChangedHandler? _authenticationStateChangedHandler; + private AccessToken? _lastToken; + private AuthenticationHeaderValue? _cachedHeader; ++ private CancellationTokenSource? _authenticationStateChangedCts; + private Uri[]? _authorizedUris; + private AccessTokenRequestOptions? _tokenOptions; + +@@ -39,7 +40,13 @@ public class AuthorizationMessageHandler : DelegatingHandler, IDisposable + // Invalidate the cached _lastToken when the authentication state changes + if (_provider is AuthenticationStateProvider authStateProvider) + { +- _authenticationStateChangedHandler = _ => { _lastToken = null; }; ++ _authenticationStateChangedHandler = _ => ++ { ++ _lastToken = null; ++ ++ _authenticationStateChangedCts?.Cancel(); ++ _authenticationStateChangedCts = null; ++ }; + authStateProvider.AuthenticationStateChanged += _authenticationStateChangedHandler; + } + } +@@ -56,16 +63,22 @@ public class AuthorizationMessageHandler : DelegatingHandler, IDisposable + + if (request.RequestUri != null && _authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri))) + { ++ var header = _cachedHeader; + if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5)) + { ++ var authenticationStateChangedToken = (_authenticationStateChangedCts ??= new()).Token; + var tokenResult = _tokenOptions != null ? + await _provider.RequestAccessToken(_tokenOptions) : + await _provider.RequestAccessToken(); + + if (tokenResult.TryGetToken(out var token)) + { +- _lastToken = token; +- _cachedHeader = new AuthenticationHeaderValue("Bearer", _lastToken.Value); ++ header = new AuthenticationHeaderValue("Bearer", token.Value); ++ if (!authenticationStateChangedToken.IsCancellationRequested) ++ { ++ _lastToken = token; ++ _cachedHeader = header; ++ } + } + else + { +@@ -76,7 +89,7 @@ public class AuthorizationMessageHandler : DelegatingHandler, IDisposable + // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request + // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might + // not be able to provision a token without user interaction). +- request.Headers.Authorization = _cachedHeader; ++ request.Headers.Authorization = header; + } + + return await base.SendAsync(request, cancellationToken); diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/context.source b/eng/skill-evals/review-pull-request/fixtures/case-01/context.source new file mode 100644 index 000000000000..16fa8f590e7b --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/context.source @@ -0,0 +1,66 @@ +=== head 2edf3761692afe15475075eb2fc0088566162045 src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs:199-226 === + public async Task DoesNotCacheToken_WhenAuthenticationStateChangesWhileTokenIsBeingRequested() + { + // Arrange + var staleTokenResult = new TaskCompletionSource(); + var tokenProvider = new TestAccessTokenProvider( + staleTokenResult.Task, + Task.FromResult(CreateTokenResult("fresh"))); + + var handler = new AuthorizationMessageHandler(tokenProvider, Mock.Of()); + handler.ConfigureHandler(new[] { "https://localhost:5001" }); + + var response = new HttpResponseMessage(HttpStatusCode.OK); + handler.InnerHandler = new TestMessageHandler(response); + var client = new HttpClient(handler); + + // Act + var firstRequest = client.GetAsync("https://localhost:5001/weather"); + tokenProvider.RaiseAuthenticationStateChanged(); + staleTokenResult.SetResult(CreateTokenResult("stale")); + _ = await firstRequest; + var firstRequestToken = response.RequestMessage.Headers.Authorization.Parameter; + + _ = await client.GetAsync("https://localhost:5001/weather"); + + // Assert + Assert.Equal("stale", firstRequestToken); + Assert.Equal("fresh", response.RequestMessage.Headers.Authorization.Parameter); + } + +=== head 2edf3761692afe15475075eb2fc0088566162045 src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs:228-230 === + private static AccessTokenResult CreateTokenResult(string value) => new( + AccessTokenResultStatus.Success, + new AccessToken { Expires = DateTime.Now.AddHours(1), GrantedScopes = new[] { "All" }, Value = value }, + +=== head 2edf3761692afe15475075eb2fc0088566162045 src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs:234-248 === + private sealed class TestAccessTokenProvider : AuthenticationStateProvider, IAccessTokenProvider + { + private readonly Queue> _results; + + public TestAccessTokenProvider(params Task[] results) => _results = new(results); + + public override Task GetAuthenticationStateAsync() + => Task.FromResult(new AuthenticationState(new ClaimsPrincipal())); + + public void RaiseAuthenticationStateChanged() => NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); + + public ValueTask RequestAccessToken() => new(_results.Dequeue()); + + public ValueTask RequestAccessToken(AccessTokenRequestOptions options) => RequestAccessToken(); + } + +=== head 2edf3761692afe15475075eb2fc0088566162045 src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs:251-262 === +internal class TestMessageHandler : HttpMessageHandler +{ + private readonly HttpResponseMessage _response; + + public TestMessageHandler(HttpResponseMessage response) => _response = response; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + _response.RequestMessage = request; + return Task.FromResult(_response); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/head.source b/eng/skill-evals/review-pull-request/fixtures/case-01/head.source new file mode 100644 index 000000000000..0777f476df48 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/head.source @@ -0,0 +1,150 @@ +=== head 2edf3761692afe15475075eb2fc0088566162045 src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs:1-148 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using Microsoft.AspNetCore.Components.Authorization; + +namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication; + +/// +/// A that attaches access tokens to outgoing instances. +/// Access tokens will only be added when the request URI is within one of the base addresses configured using +/// . +/// +public class AuthorizationMessageHandler : DelegatingHandler, IDisposable +{ + private readonly IAccessTokenProvider _provider; + private readonly NavigationManager _navigation; + private readonly AuthenticationStateChangedHandler? _authenticationStateChangedHandler; + private AccessToken? _lastToken; + private AuthenticationHeaderValue? _cachedHeader; + private CancellationTokenSource? _authenticationStateChangedCts; + private Uri[]? _authorizedUris; + private AccessTokenRequestOptions? _tokenOptions; + + /// + /// Initializes a new instance of . + /// + /// The to use for provisioning tokens. + /// The to use for performing redirections. + public AuthorizationMessageHandler( + IAccessTokenProvider provider, + NavigationManager navigation) + { + _provider = provider; + _navigation = navigation; + + // Invalidate the cached _lastToken when the authentication state changes + if (_provider is AuthenticationStateProvider authStateProvider) + { + _authenticationStateChangedHandler = _ => + { + _lastToken = null; + + _authenticationStateChangedCts?.Cancel(); + _authenticationStateChangedCts = null; + }; + authStateProvider.AuthenticationStateChanged += _authenticationStateChangedHandler; + } + } + + /// + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var now = DateTimeOffset.Now; + if (_authorizedUris == null) + { + throw new InvalidOperationException($"The '{nameof(AuthorizationMessageHandler)}' is not configured. " + + $"Call '{nameof(AuthorizationMessageHandler.ConfigureHandler)}' and provide a list of endpoint urls to attach the token to."); + } + + if (request.RequestUri != null && _authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri))) + { + var header = _cachedHeader; + if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5)) + { + var authenticationStateChangedToken = (_authenticationStateChangedCts ??= new()).Token; + var tokenResult = _tokenOptions != null ? + await _provider.RequestAccessToken(_tokenOptions) : + await _provider.RequestAccessToken(); + + if (tokenResult.TryGetToken(out var token)) + { + header = new AuthenticationHeaderValue("Bearer", token.Value); + if (!authenticationStateChangedToken.IsCancellationRequested) + { + _lastToken = token; + _cachedHeader = header; + } + } + else + { + throw new AccessTokenNotAvailableException(_navigation, tokenResult, _tokenOptions?.Scopes); + } + } + + // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request + // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might + // not be able to provision a token without user interaction). + request.Headers.Authorization = header; + } + + return await base.SendAsync(request, cancellationToken); + } + + /// + /// Configures this handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of + /// is a base of . + /// + /// The base addresses of endpoint URLs to which the token will be attached. + /// The list of scopes to use when requesting an access token. + /// The return URL to use in case there is an issue provisioning the token and a redirection to the + /// identity provider is necessary. + /// + /// This . + public AuthorizationMessageHandler ConfigureHandler( + IEnumerable authorizedUrls, + IEnumerable? scopes = null, + [StringSyntax(StringSyntaxAttribute.Uri)] string? returnUrl = null) + { + if (_authorizedUris != null) + { + throw new InvalidOperationException("Handler already configured."); + } + + ArgumentNullException.ThrowIfNull(authorizedUrls); + + var uris = authorizedUrls.Select(uri => new Uri(uri, UriKind.Absolute)).ToArray(); + if (uris.Length == 0) + { + throw new ArgumentException("At least one URL must be configured.", nameof(authorizedUrls)); + } + + _authorizedUris = uris; + var scopesList = scopes?.ToArray(); + if (scopesList != null || returnUrl != null) + { + _tokenOptions = new AccessTokenRequestOptions + { + Scopes = scopesList, + ReturnUrl = returnUrl + }; + } + + return this; + } + + void IDisposable.Dispose() + { + if (_provider is AuthenticationStateProvider authStateProvider) + { + authStateProvider.AuthenticationStateChanged -= _authenticationStateChangedHandler; + } + Dispose(disposing: true); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/mergeBase.source b/eng/skill-evals/review-pull-request/fixtures/case-01/mergeBase.source new file mode 100644 index 000000000000..fb16f312fa28 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/mergeBase.source @@ -0,0 +1,137 @@ +=== mergeBase 10bc886bfa321718276619d1077cc14eaf48456f src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs:1-135 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using Microsoft.AspNetCore.Components.Authorization; + +namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication; + +/// +/// A that attaches access tokens to outgoing instances. +/// Access tokens will only be added when the request URI is within one of the base addresses configured using +/// . +/// +public class AuthorizationMessageHandler : DelegatingHandler, IDisposable +{ + private readonly IAccessTokenProvider _provider; + private readonly NavigationManager _navigation; + private readonly AuthenticationStateChangedHandler? _authenticationStateChangedHandler; + private AccessToken? _lastToken; + private AuthenticationHeaderValue? _cachedHeader; + private Uri[]? _authorizedUris; + private AccessTokenRequestOptions? _tokenOptions; + + /// + /// Initializes a new instance of . + /// + /// The to use for provisioning tokens. + /// The to use for performing redirections. + public AuthorizationMessageHandler( + IAccessTokenProvider provider, + NavigationManager navigation) + { + _provider = provider; + _navigation = navigation; + + // Invalidate the cached _lastToken when the authentication state changes + if (_provider is AuthenticationStateProvider authStateProvider) + { + _authenticationStateChangedHandler = _ => { _lastToken = null; }; + authStateProvider.AuthenticationStateChanged += _authenticationStateChangedHandler; + } + } + + /// + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var now = DateTimeOffset.Now; + if (_authorizedUris == null) + { + throw new InvalidOperationException($"The '{nameof(AuthorizationMessageHandler)}' is not configured. " + + $"Call '{nameof(AuthorizationMessageHandler.ConfigureHandler)}' and provide a list of endpoint urls to attach the token to."); + } + + if (request.RequestUri != null && _authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri))) + { + if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5)) + { + var tokenResult = _tokenOptions != null ? + await _provider.RequestAccessToken(_tokenOptions) : + await _provider.RequestAccessToken(); + + if (tokenResult.TryGetToken(out var token)) + { + _lastToken = token; + _cachedHeader = new AuthenticationHeaderValue("Bearer", _lastToken.Value); + } + else + { + throw new AccessTokenNotAvailableException(_navigation, tokenResult, _tokenOptions?.Scopes); + } + } + + // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request + // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might + // not be able to provision a token without user interaction). + request.Headers.Authorization = _cachedHeader; + } + + return await base.SendAsync(request, cancellationToken); + } + + /// + /// Configures this handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of + /// is a base of . + /// + /// The base addresses of endpoint URLs to which the token will be attached. + /// The list of scopes to use when requesting an access token. + /// The return URL to use in case there is an issue provisioning the token and a redirection to the + /// identity provider is necessary. + /// + /// This . + public AuthorizationMessageHandler ConfigureHandler( + IEnumerable authorizedUrls, + IEnumerable? scopes = null, + [StringSyntax(StringSyntaxAttribute.Uri)] string? returnUrl = null) + { + if (_authorizedUris != null) + { + throw new InvalidOperationException("Handler already configured."); + } + + ArgumentNullException.ThrowIfNull(authorizedUrls); + + var uris = authorizedUrls.Select(uri => new Uri(uri, UriKind.Absolute)).ToArray(); + if (uris.Length == 0) + { + throw new ArgumentException("At least one URL must be configured.", nameof(authorizedUrls)); + } + + _authorizedUris = uris; + var scopesList = scopes?.ToArray(); + if (scopesList != null || returnUrl != null) + { + _tokenOptions = new AccessTokenRequestOptions + { + Scopes = scopesList, + ReturnUrl = returnUrl + }; + } + + return this; + } + + void IDisposable.Dispose() + { + if (_provider is AuthenticationStateProvider authStateProvider) + { + authStateProvider.AuthenticationStateChanged -= _authenticationStateChangedHandler; + } + Dispose(disposing: true); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-01/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-01/provenance.json new file mode 100644 index 000000000000..42bd70409f97 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-01/provenance.json @@ -0,0 +1,103 @@ +{ + "repository": "dotnet/aspnetcore", + "pullRequest": 70106, + "sourceRoles": { + "mergeBase": "10bc886bfa321718276619d1077cc14eaf48456f", + "head": "2edf3761692afe15475075eb2fc0088566162045", + "baseTip": "05cf391d127a8267a4cc3a65eb76e3c3f8ef68d2" + }, + "files": [ + { + "file": "mergeBase.source", + "sha256": "07eb9db9eb2b00e052b7f9257e425952ae7a80356dfc0345218d12dc5d9b39a4", + "sources": [ + { + "role": "mergeBase", + "commit": "10bc886bfa321718276619d1077cc14eaf48456f", + "path": "src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs", + "blob": "ea7057399eaa038417ac823f641ced83a2d8b4e4", + "ranges": [ + [ + 1, + 135 + ] + ] + } + ] + }, + { + "file": "head.source", + "sha256": "8645348ad0f81cd9dfaf2ad46b77c2addd51f99dc7cb309222e53ed1c35e37b7", + "sources": [ + { + "role": "head", + "commit": "2edf3761692afe15475075eb2fc0088566162045", + "path": "src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs", + "blob": "6e0874be24b21f552d8282af628b5b0e6b1faa09", + "ranges": [ + [ + 1, + 148 + ] + ] + } + ] + }, + { + "file": "baseTip.source", + "sha256": "d54612b8db5a94ae8606f444dde3312af9963756aecf21f6566448924ada5e84", + "sources": [ + { + "role": "baseTip", + "commit": "05cf391d127a8267a4cc3a65eb76e3c3f8ef68d2", + "path": "src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs", + "blob": "ea7057399eaa038417ac823f641ced83a2d8b4e4", + "ranges": [ + [ + 1, + 135 + ] + ] + } + ] + }, + { + "file": "context.source", + "sha256": "b9afa9a838c193fdc8eb5cdfaf7bd72a574c284c61cf00fa518cdb863c375c71", + "sources": [ + { + "role": "head", + "commit": "2edf3761692afe15475075eb2fc0088566162045", + "path": "src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs", + "blob": "b4930efc93e180d06070080a82cf8a49d2ea1a63", + "ranges": [ + [ + 199, + 226 + ], + [ + 228, + 230 + ], + [ + 234, + 248 + ], + [ + 251, + 262 + ] + ] + } + ] + }, + { + "file": "change.diff", + "sha256": "60bc415e7be22ef4cb9c899f61bd30b061a14f51767e2a34ff45ffb7d95a26c6" + }, + { + "file": "case.source", + "sha256": "af4d0c5cd703a12a23d42804c7b79493c9e2edbc651aea6261be4cc2818678cc" + } + ] +} diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/baseTip.source b/eng/skill-evals/review-pull-request/fixtures/case-02/baseTip.source new file mode 100644 index 000000000000..f821ae268207 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/baseTip.source @@ -0,0 +1,1538 @@ +=== baseTip 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs:1-86 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +#if COMPONENTS +using Microsoft.AspNetCore.Components.Forms; +#endif +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping; + +internal sealed class FileConverter : FormDataConverter +{ + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + internal override bool TryRead(ref FormDataReader reader, Type type, FormDataMapperOptions options, out T? result, out bool found) + { + if (reader.FormFileCollection == null) + { + result = default; + found = false; + return true; + } + +#if COMPONENTS + if (typeof(T) == typeof(IBrowserFile)) + { + var targetFile = reader.FormFileCollection.GetFile(reader.CurrentPrefix.ToString()); + if (targetFile != null) + { + var browserFile = new BrowserFileFromFormFile(targetFile); + result = (T)(IBrowserFile)browserFile; + found = true; + return true; + } + } + + if (typeof(T) == typeof(IReadOnlyList)) + { + var targetFiles = reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); + var buffer = ReadOnlyCollectionBufferAdapter.CreateBuffer(); + for (var i = 0; i < targetFiles.Count; i++) + { + buffer = ReadOnlyCollectionBufferAdapter.Add(ref buffer, new BrowserFileFromFormFile(targetFiles[i])); + } + result = (T)(IReadOnlyList)ReadOnlyCollectionBufferAdapter.ToResult(buffer); + found = true; + return true; + } +#endif + + if (typeof(T) == typeof(IReadOnlyList)) + { + result = (T)reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); + found = true; + return true; + } + + if (typeof(T) == typeof(IFormFileCollection)) + { + result = (T)reader.FormFileCollection; + found = true; + return true; + } + + var formFileCollection = reader.FormFileCollection; + if (formFileCollection.Count == 0) + { + result = default; + found = false; + return true; + } + + var file = formFileCollection.GetFile(reader.CurrentPrefix.ToString()); + if (file != null) + { + result = (T)file; + found = true; + return true; + } + + result = default; + found = false; + return true; + } +} + +=== baseTip 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/Factories/ComplexType/ComplexTypeExpressionConverterFactoryOfT.cs:1-621 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; +using Microsoft.AspNetCore.Components.Endpoints.FormMapping.Metadata; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping; + +internal sealed class ComplexTypeExpressionConverterFactory(FormDataMetadataFactory factory) : ComplexTypeExpressionConverterFactory +{ + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + internal override CompiledComplexTypeConverter CreateConverter(Type type, FormDataMapperOptions options) + { + var body = CreateConverterBody(type, options); + return new CompiledComplexTypeConverter(body); + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private CompiledComplexTypeConverter.ConverterDelegate CreateConverterBody(Type type, FormDataMapperOptions options) + { + var metadata = factory.GetOrCreateMetadataFor(type, options) ?? + throw new InvalidOperationException($"Could not resolve metadata for type '{type.FullName}'."); + + var properties = metadata.Properties; + var constructorParameters = metadata.ConstructorParameters; + + var (readerParam, typeParam, optionsParam, resultParam, foundValueParam) = CreateFormDataConverterParameters(); + var parameters = new List() { readerParam, typeParam, optionsParam, resultParam, foundValueParam }; + + // Variables + var propertyFoundValue = Expression.Variable(typeof(bool), "foundValueForProperty"); + var succeeded = Expression.Variable(typeof(bool), "succeeded"); + var localFoundValueVar = Expression.Variable(typeof(bool), "localFoundValue"); + var exceptionVar = Expression.Variable(typeof(Exception), "mappingException"); + var variables = new List() { propertyFoundValue, succeeded, localFoundValueVar, exceptionVar }; + + var propertyValueLocals = new List(); + var constructorParameterValueLocals = new List(); + + var body = new List() + { + Expression.Assign(succeeded, Expression.Constant(true)), + }; + + var end = Expression.Label("done"); + + if (metadata.IsRecursive) + { + body.Add(CreatePrefixCheckForRecursiveTypes(readerParam, foundValueParam, succeeded, end)); + } + + MapConstructorParameters( + constructorParameters, + readerParam, + optionsParam, + propertyFoundValue, + succeeded, + localFoundValueVar, + exceptionVar, + variables, + constructorParameterValueLocals, + body); + + MapPropertyValues( + properties, + readerParam, + optionsParam, + propertyFoundValue, + succeeded, + localFoundValueVar, + exceptionVar, + variables, + propertyValueLocals, + body); + + body.Add(Expression.IfThen( + localFoundValueVar, + Expression.Block(CreateInstanceAndAssignProperties( + metadata, + resultParam, + constructorParameters, + constructorParameterValueLocals, + properties, + propertyValueLocals, + variables, + succeeded, + readerParam)))); + + // foundValue && !failures; + body.Add(Expression.Assign(foundValueParam, localFoundValueVar)); + body.Add(Expression.Label(end)); + body.Add(succeeded); + + variables.AddRange(constructorParameterValueLocals); + variables.AddRange(propertyValueLocals); + + return CreateConverterFunction(parameters, variables, body); + + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static IEnumerable CreateInstanceAndAssignProperties( + FormDataTypeMetadata model, + ParameterExpression resultParam, + IList constructorParameters, + List constructorParameterValueLocals, + IList props, + List propsLocals, + List variables, + ParameterExpression succeeded, + ParameterExpression context) + { + if (model.Constructor == null && !model.Type.IsValueType) + { + throw new InvalidOperationException($"Type '{model.Type}' does not have a constructor. " + + $"A single public constructor is required for mapping the type."); + } + + // If we got here it means that we found some values for the type. + // We need to check the required properties/constructor parameters to see if we have values for them. + // If we don't, we need to add a mapping error and set succeeded to false. + var checks = ReportMissingValues(context, constructorParameterValueLocals, constructorParameters, propsLocals, props, succeeded); + foreach (var missingValueCheck in checks) + { + yield return missingValueCheck; + } + + if (model.Constructor != null) + { + // try + // { + // result = new T(...); + // } + // catch(Exception ex) + // { + // reader.AddMappingError(ex.Message); + // succeeded = false; + // } + var exception = Expression.Variable(typeof(Exception), "constructorException"); + variables.Add(exception); + yield return Expression.TryCatch( + Expression.Assign( + resultParam, + Expression.New( + model.Constructor, + constructorParameterValueLocals.Select(GetValueLocalVariableValueExpression))), + Expression.Catch( + exception, + Expression.Block( + Expression.Call( + context, + nameof(FormDataReader.AddMappingError), + Array.Empty(), + exception, + Expression.Constant(null, typeof(string))), + Expression.Assign(succeeded, Expression.Constant(false, typeof(bool))), + resultParam))); + } + + // if(!succeeded && context.AttachInstanceToErrorsHandler != null && result != null) + // { + // context.AttachInstanceToErrors((object)result); + // } + + var failedAndHasHandler = Expression.And(Expression.Not(succeeded), HasHandler(context)); + + var clause = model.Type.IsValueType ? failedAndHasHandler : + Expression.And( + failedAndHasHandler, + Expression.NotEqual( + resultParam, + Expression.Constant(null, resultParam.Type))); + + yield return Expression.IfThen( + clause, + Expression.Call( + context, + nameof(FormDataReader.AttachInstanceToErrors), + Array.Empty(), + Expression.Convert(resultParam, typeof(object)))); + + if (!model.Type.IsValueType) + { + var assignments = new List(); + for (var i = 0; i < props.Count; i++) + { + assignments.Add(Expression.Assign(Expression.Property(resultParam, props[i].Property), GetValueLocalVariableValueExpression(propsLocals[i]))); + } + + // if(result != null) + // { + // result.Property1 = property1; + // result.Property2 = property2; + // ... + // } + yield return Expression.IfThen( + Expression.NotEqual(resultParam, Expression.Constant(null, resultParam.Type)), + Expression.Block(assignments)); + } + else + { + for (var i = 0; i < props.Count; i++) + { + yield return Expression.Assign(Expression.Property(resultParam, props[i].Property), GetValueLocalVariableValueExpression(propsLocals[i])); + } + } + + static BinaryExpression HasHandler(ParameterExpression context) + { + return Expression.NotEqual( + Expression.Property(context, nameof(FormDataReader.AttachInstanceToErrorsHandler)), + Expression.Constant(null, typeof(Action))); + } + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static IEnumerable ReportMissingValues( + Expression readerParam, + List constructorParameters, + IList constructorParameterMetadata, + List properties, + IList propertyMetadata, + ParameterExpression succeeded) + { + for (var i = 0; i < constructorParameters.Count; i++) + { + var parameter = constructorParameters[i]; + var metadata = constructorParameterMetadata[i]; + if (metadata.Required) + { + // if(!property.Item1) + // { + // reader.PushPrefix(metadata.Name); + // reader.AddMappingError( + // FommattableStringFactory.Create( + // "Missing required value for constructor property '{0}'.", + // metadata.Name)); + // reader.PopPrefix(metadata.Name); + // } + yield return Expression.IfThen( + Expression.Not(GetValueLocalVariableFoundExpression(parameter)), + Expression.Block( + PushPrefix(readerParam, metadata.Name), + AddMappingError(readerParam, "Missing required value for constructor parameter '{0}'.", metadata.Name), + PopPrefix(readerParam, metadata.Name), + Expression.Assign(succeeded, Expression.Constant(false, typeof(bool))))); + } + } + + for (var i = 0; i < properties.Count; i++) + { + var property = properties[i]; + var metadata = propertyMetadata[i]; + if (metadata.Required) + { + // if(!property.Item1) + // { + // reader.PushPrefix(metadata.Name); + // reader.AddMappingError( + // FommattableStringFactory.Create( + // "Missing required value for constructor property '{0}'.", + // metadata.Name)); + // reader.PopPrefix(metadata.Name); + // } + yield return Expression.IfThen( + Expression.Not(GetValueLocalVariableFoundExpression(property)), + Expression.Block( + PushPrefix(readerParam, metadata.Name), + AddMappingError(readerParam, "Missing required value for property '{0}'.", metadata.Name), + PopPrefix(readerParam, metadata.Name), + Expression.Assign(succeeded, Expression.Constant(false, typeof(bool))))); + } + } + + static MethodCallExpression PushPrefix(Expression readerParam, string prefix) + { + return Expression.Call( + readerParam, + nameof(FormDataReader.PushPrefix), + Array.Empty(), + Expression.Constant(prefix)); + } + + static MethodCallExpression AddMappingError(Expression readerParam, string message, string parameter) + { + // FormattableStringFactory.Create(message) + var formattableString = Expression.Call( + typeof(FormattableStringFactory), + nameof(FormattableStringFactory.Create), + Array.Empty(), + Expression.Constant(message), + Expression.NewArrayInit(typeof(object), Expression.Constant(parameter))); + + return Expression.Call( + readerParam, + nameof(FormDataReader.AddMappingError), + Array.Empty(), + formattableString, + Expression.Constant(null, typeof(string))); + } + + static MethodCallExpression PopPrefix(Expression readerParam, string prefix) + { + return Expression.Call( + readerParam, + nameof(FormDataReader.PopPrefix), + Array.Empty(), + Expression.Constant(prefix)); + } + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static void MapPropertyValues( + IList properties, + ParameterExpression readerParam, + ParameterExpression optionsParam, + ParameterExpression propertyFoundValue, + ParameterExpression succeeded, + ParameterExpression localFoundValueVar, + ParameterExpression exceptionVar, + List variables, + List propertyValueLocals, + List body) + { + // Create the property blocks + // var propertyConverter = options.ResolveConverter(typeof(string)); + // reader.PushPrefix("PropertyInfo"); + // succeeded &= propertyConverter.TryRead(ref reader, typeof(string), options, out propertyVar, out foundProperty); + // found ||= foundProperty; + // reader.PopPrefix("PropertyInfo"); + for (var i = 0; i < properties.Count; i++) + { + // Declare variable for the converter + var property = properties[i]; + var propertyConverterType = typeof(FormDataConverter<>).MakeGenericType(property.Type); + var propertyConverterVar = Expression.Variable(propertyConverterType, $"{property.Name}Converter"); + variables.Add(propertyConverterVar); + + // Declare variable for property value. + var propertyVar = CreateValueLocalVariable(property); + propertyValueLocals.Add(propertyVar); + + // Resolve and assign converter + // Create the block to try and map the property and update propsLocals. + // returnParam &= { PushPrefix(property.Name); var res = TryRead(...); PopPrefix(...); return res; } + // var propertyConverter = options.ResolveConverter()); + var propertyConverter = Expression.Assign( + propertyConverterVar, + Expression.Call( + optionsParam, + nameof(FormDataMapperOptions.ResolveConverter), + new[] { property.Type }, + Array.Empty())); + body.Add(propertyConverter); + + body.Add(Expression.TryCatchFinally( + // try + // { + // reader.PushPrefix("PropertyInfo"); + // succeeded &= propertyConverter.TryRead(ref reader, typeof(string), options, out propertyVar, out foundProperty); + // } + // finally + // { + // reader.PopPrefix("PropertyInfo"); + // } + body: Expression.Block( + // reader.PushPrefix("PropertyInfo"); + Expression.Call( + readerParam, + nameof(FormDataReader.PushPrefix), + Array.Empty(), + Expression.Constant(property.Name)), + + // succeeded &= propertyConverter.TryRead(ref reader, typeof(string), options, out propertyVar, out foundProperty); + Expression.AndAssign( + succeeded, + Expression.Call( + propertyConverterVar, + nameof(FormDataConverter.TryRead), + Type.EmptyTypes, + readerParam, + Expression.Constant(property.Type), + optionsParam, + GetValueLocalVariableValueExpression(propertyVar), + propertyFoundValue))), + // reader.PopPrefix("PropertyInfo"); + @finally: Expression.Call( + readerParam, + nameof(FormDataReader.PopPrefix), + Array.Empty(), + Expression.Constant(property.Name)), + handlers: Expression.Catch( + exceptionVar, + Expression.Block( + Expression.Call( + readerParam, + nameof(FormDataReader.AddMappingError), + Array.Empty(), + exceptionVar, + Expression.Constant(null, typeof(string))), + Expression.Assign(succeeded, Expression.Constant(false, typeof(bool))) + )))); + + // parameter.found = foundProperty; + body.Add(Expression.Assign(GetValueLocalVariableFoundExpression(propertyVar), propertyFoundValue)); + body.Add(Expression.OrAssign(localFoundValueVar, propertyFoundValue)); + } + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static void MapConstructorParameters( + IList constructorParameters, + ParameterExpression readerParam, + ParameterExpression optionsParam, + ParameterExpression propertyFoundValue, + ParameterExpression succeeded, + ParameterExpression localFoundValueVar, + ParameterExpression exceptionVar, + List variables, + List constructorParameterValueLocals, + List body) + { + // Create the constructor property blocks + + // var parameterConverter = options.ResolveConverter(typeof(string)); + // reader.PushPrefix("PropertyInfo"); + // succeeded &= parameterConverter.TryRead(ref reader, typeof(string), options, out constructorParameterVar, out foundProperty); + // found ||= foundProperty; + // reader.PopPrefix("PropertyInfo"); + for (var i = 0; i < constructorParameters.Count; i++) + { + // Declare variable for the converter + var constructorParameter = constructorParameters[i]; + var constructorParameterConverterType = typeof(FormDataConverter<>).MakeGenericType(constructorParameter.Type); + var constructorParameterConverterVar = Expression.Variable(constructorParameterConverterType, $"{constructorParameter.Name}Converter"); + variables.Add(constructorParameterConverterVar); + + // Declare variable for constructorParameter value. + var constructorParameterVar = CreateValueLocalVariable(constructorParameter); + constructorParameterValueLocals.Add(constructorParameterVar); + + // Resolve and assign converter + // Create the block to try and map the constructorParameter and update propsLocals. + // returnParam &= { PushPrefix(constructorParameter.Name); var res = TryRead(...); PopPrefix(...); return res; } + // var constructorParameterConverter = options.ResolveConverter()); + var constructorParameterConverter = Expression.Assign( + constructorParameterConverterVar, + Expression.Call( + optionsParam, + nameof(FormDataMapperOptions.ResolveConverter), + new[] { constructorParameter.Type }, + Array.Empty())); + body.Add(constructorParameterConverter); + + // try + // { + // reader.PushPrefix("PropertyInfo"); + // succeeded &= constructorParameterConverter.TryRead(ref reader, typeof(string), options, out constructorParameterVar, out foundProperty); + // if(!succeeded || !found) + // { + // reader.AddMappingError("Missing required value for constructor property {0}", constructorParameter.Name); + // } + // } + // finally + // { + // reader.PopPrefix("PropertyInfo"); + // } + body.Add(Expression.TryCatchFinally( + body: Expression.Block( + // reader.PushPrefix("PropertyInfo"); + Expression.Call( + readerParam, + nameof(FormDataReader.PushPrefix), + Array.Empty(), + Expression.Constant(constructorParameter.Name)), + // succeeded &= constructorParameterConverter.TryRead(ref reader, typeof(string), options, out constructorParameterVar, out foundProperty); + Expression.AndAssign( + succeeded, + Expression.Call( + constructorParameterConverterVar, + nameof(FormDataConverter.TryRead), + Type.EmptyTypes, + readerParam, + Expression.Constant(constructorParameter.Type), + optionsParam, + GetValueLocalVariableValueExpression(constructorParameterVar), + propertyFoundValue))), + // reader.PopPrefix("PropertyInfo"); + @finally: Expression.Call( + readerParam, + nameof(FormDataReader.PopPrefix), + Array.Empty(), + Expression.Constant(constructorParameter.Name)), + handlers: Expression.Catch( + exceptionVar, + Expression.Block( + Expression.Call( + readerParam, + nameof(FormDataReader.AddMappingError), + Array.Empty(), + exceptionVar, + Expression.Constant(null, typeof(string))), + Expression.Assign(succeeded, Expression.Constant(false, typeof(bool))) + )))); + + // parameter.found = foundProperty; + body.Add(Expression.Assign(GetValueLocalVariableFoundExpression(constructorParameterVar), propertyFoundValue)); + body.Add(Expression.OrAssign(localFoundValueVar, propertyFoundValue)); + } + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static Expression GetValueLocalVariableFoundExpression(ParameterExpression constructorParameterVar) + { + return Expression.PropertyOrField(constructorParameterVar, nameof(ValueTuple.Item1)); + } + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static Expression GetValueLocalVariableValueExpression(ParameterExpression constructorParameterVar) => + Expression.PropertyOrField(constructorParameterVar, nameof(ValueTuple.Item2)); + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static ParameterExpression CreateValueLocalVariable(IFormDataValue constructorParameter) + { + return Expression.Variable(typeof(ValueTuple<,>).MakeGenericType(typeof(bool), constructorParameter.Type), constructorParameter.Name); + } + + // For recursive types we need to do a prefix check. + // if(!reader.CurrentPrefixExists()) + // { + // found = false; + // return true; + // } + // + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + private static ConditionalExpression CreatePrefixCheckForRecursiveTypes(ParameterExpression readerParam, ParameterExpression foundValueParam, ParameterExpression succeeded, LabelTarget end) + { + return Expression.IfThen( + Expression.Not(Expression.Call(readerParam, nameof(FormDataReader.CurrentPrefixExists), Array.Empty())), + Expression.Block( + Expression.Assign(foundValueParam, Expression.Constant(false)), + Expression.Assign(succeeded, Expression.Constant(true)), + Expression.Goto(end))); + } + + private static CompiledComplexTypeConverter.ConverterDelegate CreateConverterFunction( + List parameters, + List variables, + List body) + { + var lambda = Expression.Lambda.ConverterDelegate>( + Expression.Block(variables, body), + parameters); + + return lambda.Compile(); + } + + private static FormDataConverterReadParameters CreateFormDataConverterParameters() + { + return new( + Expression.Parameter(typeof(FormDataReader).MakeByRefType(), "reader"), + Expression.Parameter(typeof(Type), "type"), + Expression.Parameter(typeof(FormDataMapperOptions), "options"), + Expression.Parameter(typeof(T).MakeByRefType(), "result"), + Expression.Parameter(typeof(bool).MakeByRefType(), "foundValue")); + } + + private readonly struct FormDataConverterReadParameters + { + public ParameterExpression ReaderParam { get; } + + public ParameterExpression TypeParam { get; } + + public ParameterExpression OptionsParam { get; } + + public ParameterExpression ResultParam { get; } + + public ParameterExpression FoundValueParam { get; } + + public FormDataConverterReadParameters( + ParameterExpression readerParam, + ParameterExpression typeParam, + ParameterExpression optionsParam, + ParameterExpression resultParam, + ParameterExpression foundValueParam) + { + ReaderParam = readerParam; + TypeParam = typeParam; + OptionsParam = optionsParam; + ResultParam = resultParam; + FoundValueParam = foundValueParam; + } + + public void Deconstruct( + out ParameterExpression readerParam, + out ParameterExpression typeParam, + out ParameterExpression optionsParam, + out ParameterExpression resultParam, + out ParameterExpression foundValueParam) + { + readerParam = ReaderParam; + typeParam = TypeParam; + optionsParam = OptionsParam; + resultParam = ResultParam; + foundValueParam = FoundValueParam; + } + } +} + +=== baseTip 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/Metadata/FormDataMetadataFactory.cs:1-428 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using Microsoft.Extensions.Internal; +using Microsoft.Extensions.Logging; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping.Metadata; + +internal partial class FormDataMetadataFactory(List factories, ILoggerFactory loggerFactory) +{ + private readonly object _lock = new object(); + private readonly FormMetadataContext _context = new(); + private readonly ParsableConverterFactory _parsableFactory = factories.OfType().Single(); + private readonly DictionaryConverterFactory _dictionaryFactory = factories.OfType().Single(); + private readonly FileConverterFactory _fileConverterFactory = factories.OfType().Single(); + private readonly CollectionConverterFactory _collectionFactory = factories.OfType().Single(); + private readonly ILogger _logger = loggerFactory.CreateLogger(); + + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + public FormDataTypeMetadata? GetOrCreateMetadataFor(Type type, FormDataMapperOptions options) + { + var shouldClearContext = !_context.ResolutionInProgress; + lock (_lock) + { + try + { + // We are walking the graph in order to detect recursive types. + // We evaluate whether a type is: + // 1. Primitive + // 2. Dictionary + // 3. Collection + // 4. Complex + // Only complex types can be recursive. + // We only compute metadata when we are dealing with objects, other classes of + // types are handled directly by the appropriate converters. + // We keep track of the metadata for the types because it is useful when we generate + // the specific object converter for a type. + // The code generation varies depending on whether there is recursion or not within + // the type graph. + if (shouldClearContext) + { + Log.StartResolveMetadataGraph(_logger, type); + _context.BeginResolveGraph(); + } + + // Try to get the metadata for the type or create and add a new instance. + var result = _context.TypeMetadata.TryGetValue(type, out var value) ? value : new FormDataTypeMetadata(type); + if (value == null) + { + Log.NoMetadataFound(_logger, type); + _context.TypeMetadata[type] = result; + } + else + { + Log.MetadataFound(_logger, type); + } + + if (type.IsGenericTypeDefinition) + { + Log.GenericTypeDefinitionNotSupported(_logger, type); + _context.TypeMetadata.Remove(type); + return null; + } + + // Check for cycles and mark any type as recursive if needed. + DetectCyclesAndMarkMetadataTypesAsRecursive(type, result); + + // We found the value on the existing metadata, we can return it. + if (value != null) + { + return result; + } + + // These blocks are evaluated in a specific order. + if (_parsableFactory.CanConvert(type, options) || type.IsEnum || + (Nullable.GetUnderlyingType(type) is { } underlyingType && + _parsableFactory.CanConvert(underlyingType, options))) + { + Log.PrimitiveType(_logger, type); + result.Kind = FormDataTypeKind.Primitive; + return result; + } + + if (_fileConverterFactory.CanConvert(type, options)) + { + result.Kind = FormDataTypeKind.File; + return result; + } + + if (WellKnownConverters.Converters.TryGetValue(type, out var converter)) + { + result.Kind = FormDataTypeKind.Primitive; + return result; + } + + if (_dictionaryFactory.CanConvert(type, options)) + { + Log.DictionaryType(_logger, type); + result.Kind = FormDataTypeKind.Dictionary; + var (keyType, valueType) = DictionaryConverterFactory.ResolveDictionaryTypes(type)!; + result.KeyType = GetOrCreateMetadataFor(keyType, options); + result.ValueType = GetOrCreateMetadataFor(valueType, options); + return result; + } + + if (_collectionFactory.CanConvert(type, options)) + { + Log.CollectionType(_logger, type); + result.Kind = FormDataTypeKind.Collection; + result.ElementType = GetOrCreateMetadataFor(CollectionConverterFactory.ResolveElementType(type)!, options); + return result; + } + + Log.ObjectType(_logger, type); + result.Kind = FormDataTypeKind.Object; + _context.Track(type); + var constructors = type.GetConstructors(); + + if (constructors.Length == 1) + { + result.Constructor = constructors[0]; + if (type.IsAbstract) + { + Log.AbstractClassesNotSupported(_logger, type); + _context.TypeMetadata.Remove(type); + return null; + } + } + else if (constructors.Length > 1) + { + // We can't select the constructor when there are multiple of them. + Log.MultiplePublicConstructorsFound(_logger, type); + return null; + } + else if (!type.IsValueType) + { + if (type.IsInterface) + { + Log.InterfacesNotSupported(_logger, type); + } + else if (type.IsAbstract) + { + Log.AbstractClassesNotSupported(_logger, type); + } + else + { + Log.NoPublicConstructorFound(_logger, type); + } + + _context.TypeMetadata.Remove(type); + // We can't bind to reference types without constructors. + return null; + } + + if (result.Constructor != null) + { + if (_logger.IsEnabled(LogLevel.Debug)) + { + var parameters = $"({string.Join(", ", result.Constructor.GetParameters().Select(p => p.ParameterType.Name))})"; + Log.ConstructorFound(_logger, type, parameters); + } + + var values = result.Constructor.GetParameters(); + + foreach (var parameter in values) + { + Log.ConstructorParameter(_logger, type, parameter.Name!, parameter.ParameterType); + var parameterTypeInfo = GetOrCreateMetadataFor(parameter.ParameterType, options); + if (parameterTypeInfo == null) + { + Log.ConstructorParameterTypeNotSupported(_logger, type, parameter.Name!, parameter.ParameterType); + _context.TypeMetadata.Remove(type); + return null; + } + + result.ConstructorParameters.Add(new FormDataParameterMetadata(parameter, parameterTypeInfo)); + } + } + + var candidateProperty = PropertyHelper.GetVisibleProperties(type); + foreach (var propertyHelper in candidateProperty) + { + var property = propertyHelper.Property; + Log.CandidateProperty(_logger, propertyHelper.Name, property.PropertyType); + var matchingConstructorParameter = result + .ConstructorParameters + .FirstOrDefault(p => string.Equals(p.Name, property.Name, StringComparison.OrdinalIgnoreCase)); + + if (matchingConstructorParameter != null) + { + Log.MatchingConstructorParameterFound(_logger, matchingConstructorParameter.Name, property.Name); + var dataMember = property.GetCustomAttribute(); + if (dataMember != null && dataMember.IsNameSetExplicitly && dataMember.Name != null) + { + Log.CustomParameterNameMetadata(_logger, dataMember.Name, property.Name); + matchingConstructorParameter.Name = dataMember.Name; + } + + // The propertyHelper is already present in the constructor, we don't need to add it again. + continue; + } + + var ignoreDataMember = property.GetCustomAttribute(); + if (ignoreDataMember != null) + { + Log.IgnoredProperty(_logger, property.Name); + // The propertyHelper is marked as ignored, we don't need to add it. + continue; + } + + if (property.SetMethod == null || !property.SetMethod.IsPublic) + { + Log.NonPublicSetter(_logger, property.Name); + // The property is readonly, we don't need to add it. + continue; + } + + var propertyTypeInfo = GetOrCreateMetadataFor(property.PropertyType, options); + if (propertyTypeInfo == null) + { + Log.PropertyTypeNotSupported(_logger, type, property.Name, property.PropertyType); + _context.TypeMetadata.Remove(type); + return null; + } + var propertyInfo = new FormDataPropertyMetadata(property, propertyTypeInfo); + + var dataMemberAttribute = property.GetCustomAttribute(); + if (dataMemberAttribute != null && dataMemberAttribute.IsNameSetExplicitly && dataMemberAttribute.Name != null) + { + Log.CustomParameterNameMetadata(_logger, dataMemberAttribute.Name, property.Name); + propertyInfo.Name = dataMemberAttribute.Name; + propertyInfo.Required = dataMemberAttribute.IsRequired; + Log.PropertyRequired(_logger, propertyInfo.Name); + } + + var requiredAttribute = property.GetCustomAttribute(); + if (requiredAttribute != null) + { + propertyInfo.Required = true; + Log.PropertyRequired(_logger, propertyInfo.Name); + } + + result.Properties.Add(propertyInfo); + } + + Log.MetadataComputed(_logger, type); + return result; + } + finally + { + _context.Untrack(type); + if (shouldClearContext) + { + Log.EndResolveMetadataGraph(_logger, type); + _context.EndResolveGraph(); + } + } + } + } + + internal bool HasMetadataFor(Type type) => _context.TypeMetadata.ContainsKey(type); + + private void DetectCyclesAndMarkMetadataTypesAsRecursive(Type type, FormDataTypeMetadata result) + { + // Mark any type as recursive if its already present in the current resolution graph or + // if there is a base type for it on the resolution graph. + // For example, given A and B : A. With A having a propertyHelper of type B. + // when we inspect B, we can tell that A is recursive because you can have A -> B -> B -> B -> ... + // The opposite scenario is not something we need to worry about because we don't support polymorphism, + // meaning that we will never create an instance of B if the declared type is A. + // In that scenario, A and B : A. With B having a propertyHelper of type A. + // The recursion stops at A, because A doesn't define the propertyHelper and we will never bind B to A. + // If in the future we support polymorphism, it's a matter or updating the logic below to account for it. + for (var i = 0; i < _context.CurrentTypes.Count; i++) + { + if (_context.CurrentTypes[i] == type) + { + // We found an exact match in the current resolution graph. + // This means that the type is recursive. + result.IsRecursive = true; + ReportRecursiveChain(type); + + } + else if (type.IsSubclassOf(_context.CurrentTypes[i])) + { + // We found a type that is assignable from the current type. + // This means that the type is recursive. + var existingType = _context.TypeMetadata[_context.CurrentTypes[i]]; + ReportRecursiveChain(type); + existingType.IsRecursive = true; + } + + // We don't need to check for interfaces here because we never map to an interface, so if we encounter one, we will fail, + // as we can't construct the converter to map the interface to a concrete instance. + } + + void ReportRecursiveChain(Type type) + { + if (_logger.IsEnabled(LogLevel.Debug)) + { + var chain = string.Join(" -> ", _context.CurrentTypes.Append(type).Select(t => t.Name)); + Log.RecursiveTypeFound(_logger, type, chain); + } + } + } + + private class FormMetadataContext + { + public Dictionary TypeMetadata { get; set; } = new(); + + public List CurrentTypes { get; set; } = new(); + + public bool ResolutionInProgress { get; internal set; } + + internal void BeginResolveGraph() + { + if (ResolutionInProgress) + { + throw new InvalidOperationException("Cannot begin a new resolution graph while one is already in progress."); + } + ResolutionInProgress = true; + } + + internal void EndResolveGraph() + { + if (!ResolutionInProgress) + { + throw new InvalidOperationException("Cannot end a resolution graph while one is not in progress."); + } + ResolutionInProgress = false; + CurrentTypes.Clear(); + } + + internal void Track(Type type) + { + CurrentTypes.Add(type); + } + + internal void Untrack(Type type) + { + CurrentTypes.Remove(type); + } + } + + private static partial class Log + { + [LoggerMessage(1, LogLevel.Debug, "Begin resolve metadata graph for type '{Type}'.", EventName = nameof(StartResolveMetadataGraph))] + public static partial void StartResolveMetadataGraph(ILogger logger, Type type); + + [LoggerMessage(2, LogLevel.Debug, "End resolve metadata graph for type '{Type}'.", EventName = nameof(EndResolveMetadataGraph))] + public static partial void EndResolveMetadataGraph(ILogger logger, Type type); + + [LoggerMessage(3, LogLevel.Debug, "Cached metadata found for type '{Type}'.", EventName = nameof(Metadata))] + public static partial void MetadataFound(ILogger logger, Type type); + + [LoggerMessage(4, LogLevel.Debug, "No cached metadata graph for type '{Type}'.", EventName = nameof(NoMetadataFound))] + public static partial void NoMetadataFound(ILogger logger, Type type); + + [LoggerMessage(5, LogLevel.Debug, "Recursive type '{Type}' found in the resolution graph '{Chain}'.", EventName = nameof(RecursiveTypeFound))] + public static partial void RecursiveTypeFound(ILogger logger, Type type, string chain); + + [LoggerMessage(6, LogLevel.Debug, "'{Type}' identified as primitive.", EventName = nameof(PrimitiveType))] + public static partial void PrimitiveType(ILogger logger, Type type); + + [LoggerMessage(7, LogLevel.Debug, "'{Type}' identified as dictionary.", EventName = nameof(DictionaryType))] + public static partial void DictionaryType(ILogger logger, Type type); + + [LoggerMessage(8, LogLevel.Debug, "'{Type}' identified as collection.", EventName = nameof(CollectionType))] + public static partial void CollectionType(ILogger logger, Type type); + + [LoggerMessage(9, LogLevel.Debug, "'{Type}' identified as object.", EventName = nameof(ObjectType))] + public static partial void ObjectType(ILogger logger, Type type); + + [LoggerMessage(10, LogLevel.Debug, "Constructor found for type '{Type}' with parameters '{Parameters}'.", EventName = nameof(ConstructorFound))] + public static partial void ConstructorFound(ILogger logger, Type type, string parameters); + + [LoggerMessage(11, LogLevel.Debug, "Constructor parameter '{Name}' of type '{ParameterType}' found for type '{Type}'.", EventName = nameof(ConstructorParameter))] + public static partial void ConstructorParameter(ILogger logger, Type type, string name, Type parameterType); + + [LoggerMessage(12, LogLevel.Debug, "Candidate property '{Name}' of type '{PropertyType}'.", EventName = nameof(CandidateProperty))] + public static partial void CandidateProperty(ILogger logger, string name, Type propertyType); + + [LoggerMessage(13, LogLevel.Debug, "Candidate property {PropertyName} has a matching constructor parameter '{ConstructorParameterName}'.", EventName = nameof(MatchingConstructorParameterFound))] + public static partial void MatchingConstructorParameterFound(ILogger logger, string constructorParameterName, string propertyName); + + [LoggerMessage(14, LogLevel.Debug, "Candidate property or constructor parameter {PropertyName} defines a custom name '{CustomName}'.", EventName = nameof(CustomParameterNameMetadata))] + public static partial void CustomParameterNameMetadata(ILogger logger, string customName, string propertyName); + + [LoggerMessage(15, LogLevel.Debug, "Candidate property {Name} will not be mapped. It has been explicitly ignored.", EventName = nameof(IgnoredProperty))] + public static partial void IgnoredProperty(ILogger logger, string name); + + [LoggerMessage(16, LogLevel.Debug, "Candidate property {Name} will not be mapped. It has no public setter.", EventName = nameof(NonPublicSetter))] + public static partial void NonPublicSetter(ILogger logger, string name); + + [LoggerMessage(17, LogLevel.Debug, "Candidate property {Name} is marked as required.", EventName = nameof(PropertyRequired))] + public static partial void PropertyRequired(ILogger logger, string name); + + [LoggerMessage(18, LogLevel.Debug, "Metadata created for {Type}.", EventName = nameof(MetadataComputed))] + public static partial void MetadataComputed(ILogger logger, Type type); + + [LoggerMessage(19, LogLevel.Debug, "Can not map type generic type definition '{Type}'.", EventName = nameof(GenericTypeDefinitionNotSupported))] + public static partial void GenericTypeDefinitionNotSupported(ILogger logger, Type type); + + [LoggerMessage(20, LogLevel.Debug, "Unable to select a constructor. Multiple public constructors found for type '{Type}'.", EventName = nameof(MultiplePublicConstructorsFound))] + public static partial void MultiplePublicConstructorsFound(ILogger logger, Type type); + + [LoggerMessage(21, LogLevel.Debug, "Can not map interface type '{Type}'.", EventName = nameof(InterfacesNotSupported))] + public static partial void InterfacesNotSupported(ILogger logger, Type type); + + [LoggerMessage(22, LogLevel.Debug, "Can not map abstract type '{Type}'.", EventName = nameof(AbstractClassesNotSupported))] + public static partial void AbstractClassesNotSupported(ILogger logger, Type type); + + [LoggerMessage(23, LogLevel.Debug, "Unable to select a constructor. No public constructors found for type '{Type}'.", EventName = nameof(NoPublicConstructorFound))] + public static partial void NoPublicConstructorFound(ILogger logger, Type type); + + [LoggerMessage(24, LogLevel.Debug, "Can not map type '{Type}'. Constructor parameter {Name} of type {ParameterType} is not supported.", EventName = nameof(ConstructorParameterTypeNotSupported))] + public static partial void ConstructorParameterTypeNotSupported(ILogger logger, Type type, string name, Type parameterType); + + [LoggerMessage(25, LogLevel.Debug, "Can not map type '{Type}'. Property {Name} of type {PropertyType} is not supported.", EventName = nameof(PropertyTypeNotSupported))] + public static partial void PropertyTypeNotSupported(ILogger logger, Type type, string name, Type propertyType); + } +} + +=== baseTip 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/Metadata/FormDataParameterMetadata.cs:1-25 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Reflection; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping.Metadata; +internal class FormDataParameterMetadata(ParameterInfo parameter, FormDataTypeMetadata parameterTypeInfo) : IFormDataValue +{ + public ParameterInfo Parameter { get; } = parameter; + public string Name { get; set; } = parameter.Name!; + public Type Type { get; set; } = parameter.ParameterType; + + public bool Required => true; + + internal FormDataTypeMetadata ParameterMetadata { get; } = parameterTypeInfo; +} + +internal interface IFormDataValue +{ + public string Name { get; } + + public Type Type { get; } + + public bool Required { get; } +} + +=== baseTip 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/FormDataReader.cs:1-318 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Runtime.CompilerServices; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.Primitives; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping; + +[DebuggerDisplay($"{{{nameof(DebuggerDisplay)}(),nq}}")] +internal struct FormDataReader : IDisposable +{ + private readonly IReadOnlyDictionary _readOnlyMemoryKeys; + private readonly Memory _prefixBuffer; + private Memory _currentPrefixBuffer; + private int _currentDepth; + private int _errorCount; + + // As an implementation detail, reuse FormKey for the values. + // It's just a thin wrapper over ReadOnlyMemory that caches + // the computed hash code. + + private PrefixResolver _prefixResolver; + + public FormDataReader(IReadOnlyDictionary formCollection, CultureInfo culture, Memory buffer) + { + _readOnlyMemoryKeys = formCollection; + Culture = culture; + _prefixBuffer = buffer; + } + + public FormDataReader(IReadOnlyDictionary formCollection, CultureInfo culture, Memory buffer, IFormFileCollection formFileCollection) + : this(formCollection, culture, buffer) + { + FormFileCollection = formFileCollection; + } + + internal ReadOnlyMemory CurrentPrefix => _currentPrefixBuffer; + + public IFormatProvider Culture { get; } + + public IFormFileCollection? FormFileCollection { get; internal set; } + + public int MaxRecursionDepth { get; set; } = 64; + + public int MaxCollectionSize { get; set; } = FormReader.DefaultValueCountLimit; + + public Action? ErrorHandler { get; set; } + + public Action? AttachInstanceToErrorsHandler { get; set; } + + public int MaxErrorCount { get; set; } = 200; + + public void AddMappingError(FormattableString errorMessage, string? attemptedValue) + { + ArgumentNullException.ThrowIfNull(errorMessage); + + if (ErrorHandler == null) + { + throw new FormDataMappingException(new FormDataMappingError(_currentPrefixBuffer.ToString(), errorMessage, attemptedValue)); + } + + _errorCount++; + if (_errorCount == MaxErrorCount) + { + ErrorHandler.Invoke( + _currentPrefixBuffer.ToString(), + FormattableStringFactory.Create($"Maximum number of errors ({MaxErrorCount}) reached. Further errors will be suppressed."), + null); + } + + if (_errorCount >= MaxErrorCount) + { + return; + } + + ErrorHandler.Invoke(_currentPrefixBuffer.ToString(), errorMessage, attemptedValue); + } + + public void AddMappingError(Exception exception, string? attemptedValue) + { + ArgumentNullException.ThrowIfNull(exception); + + // Avoid re-wrapping the exception if it is already a FormDataMappingException + // and we don't have an ErrorHandler configured. + if (exception is FormDataMappingException && ErrorHandler == null) + { + throw exception; + } + + var errorMessage = FormattableStringFactory.Create(exception.Message); + AddMappingError(errorMessage, attemptedValue); + } + + public void AttachInstanceToErrors(object value) + { + if (AttachInstanceToErrorsHandler == null) + { + return; + } + + AttachInstanceToErrorsHandler(_currentPrefixBuffer.ToString(), value); + } + + internal FormKeyCollection GetKeys() + { + // Scan the input dictionary for keys matching the current prefix followed by a bracket segment. + // This avoids building a large upfront dictionary of all prefix→key mappings. + var prefix = _currentPrefixBuffer; + var result = new HashSet(); + + foreach (var kvp in _readOnlyMemoryKeys) + { + var key = kvp.Key.Value; + + // The key must start with the current prefix (case-insensitive). + if (key.Length <= prefix.Length || + !key.Span[..prefix.Length].Equals(prefix.Span, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + // Immediately after the prefix, there must be a '['. + if (key.Span[prefix.Length] != '[') + { + continue; + } + + // Find the closing ']' after the '['. + var remaining = key[prefix.Length..]; + var closeIndex = remaining.Span[1..].IndexOf(']'); + if (closeIndex == -1) + { + // Malformed key — no closing bracket. Skip it. + continue; + } + + // Extract "[value]" (closeIndex is relative to position 1, so add 2 for the full segment). + var segment = remaining[..(closeIndex + 2)]; + result.Add(new FormKey(segment)); + + // Allow one extra item through so collection/dictionary binding can still detect overflow + // and report the existing max-size error instead of silently truncating the input. + if (result.Count > MaxCollectionSize) + { + break; + } + } + + return result.Count > 0 + ? new FormKeyCollection(result) + : FormKeyCollection.Empty; + } + + // This only ever gets invoked if we have a recursive type. + // Recursive types make an existential check for the current prefix to determine if they + // need to continue mapping data. + // At that point, we are placing the keys into a sorted array, and we use binary search to + // determine if the prefix exists. + // We only make this search on recursive paths, as opposed to in every new scope that we push. + internal bool CurrentPrefixExists() + { + if (CurrentPrefix.Span.Length == 0) + { + // Avoid creating the prefix array at the root level. + return _readOnlyMemoryKeys.Count > 0; + } + + if (!_prefixResolver.HasValues) + { + _prefixResolver = new PrefixResolver(_readOnlyMemoryKeys.Keys, _readOnlyMemoryKeys.Count); + } + + return _prefixResolver.HasPrefix(_currentPrefixBuffer); + } + + internal void PopPrefix(string key) + { + PopPrefix(key.AsSpan()); + } + + internal void PopPrefix(ReadOnlySpan key) + { + if (_currentDepth > MaxRecursionDepth) + { + return; + } + + _currentDepth--; + Debug.Assert(_currentDepth >= 0); + var keyLength = key.Length; + // If keyLength is bigger than the current scope keyLength typically means there is a + // bug where some part of the code has not popped the scope appropriately. + Debug.Assert(_currentPrefixBuffer.Length >= keyLength); + if (_currentPrefixBuffer.Length == keyLength || _currentPrefixBuffer.Span[^(keyLength + 1)] != '.') + { + _currentPrefixBuffer = _currentPrefixBuffer[..^keyLength]; + } + else + { + _currentPrefixBuffer = _currentPrefixBuffer[..^(keyLength + 1)]; + } + } + + internal void PushPrefix(string key) + { + PushPrefix(key.AsSpan()); + } + + internal void PushPrefix(scoped ReadOnlySpan key) + { + _currentDepth++; + // We automatically append a "." before adding the suffix, except when its the first element pushed to the + // scope, or when we are accessing a property after a collection or an indexer like items[1]. + var separator = _currentPrefixBuffer.Length > 0 && key[0] != '[' + ? ".".AsSpan() + : "".AsSpan(); + if (_currentDepth > MaxRecursionDepth) + { + throw new InvalidOperationException($"The maximum recursion depth of '{MaxRecursionDepth}' was exceeded for '{_currentPrefixBuffer}{separator}{key}'."); + } + + Debug.Assert(_prefixBuffer.Length >= (_currentPrefixBuffer.Length + separator.Length)); + + separator.CopyTo(_prefixBuffer.Span[_currentPrefixBuffer.Length..]); + + var startingPoint = _currentPrefixBuffer.Length + separator.Length; + _currentPrefixBuffer = _prefixBuffer.Slice(0, startingPoint + key.Length); + key.CopyTo(_prefixBuffer[startingPoint..].Span); + } + + internal readonly bool TryGetValue([NotNullWhen(true)] out string? value) + { + var foundSingleValue = _readOnlyMemoryKeys.TryGetValue(new FormKey(_currentPrefixBuffer), out var result) || result.Count == 1; + if (foundSingleValue) + { + value = result[0]; + } + else + { + value = null; + } + + return foundSingleValue; + } + + internal readonly bool TryGetValues(out StringValues values) => + _readOnlyMemoryKeys.TryGetValue(new FormKey(_currentPrefixBuffer), out values); + + internal string GetPrefix() => _currentPrefixBuffer.ToString(); + + internal string GetLastPrefixSegment() + { + var index = _currentPrefixBuffer.Span.LastIndexOfAny(".["); + if (index == -1) + { + return _currentPrefixBuffer.ToString(); + } + if (_currentPrefixBuffer.Span[index] == '.') + { + return _currentPrefixBuffer.Span[(index + 1)..].ToString(); + } + else + { + // Return the value without the closing bracket ] + return _currentPrefixBuffer.Span[(index + 1)..^1].ToString(); + } + } + + public void Dispose() + { + _prefixResolver.Dispose(); + } + + internal readonly struct FormKeyCollection : IEnumerable> + { + private readonly HashSet _values; + internal static readonly FormKeyCollection Empty; + + public bool HasValues() => _values != null; + + public FormKeyCollection(HashSet values) => _values = values; + + public Enumerator GetEnumerator() => new Enumerator(_values.GetEnumerator()); + + IEnumerator> IEnumerable>.GetEnumerator() => GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + internal struct Enumerator : IEnumerator> + { + private HashSet.Enumerator _enumerator; + + public Enumerator(HashSet.Enumerator enumerator) + { + _enumerator = enumerator; + } + + public ReadOnlyMemory Current => _enumerator.Current.Value; + + object IEnumerator.Current => _enumerator.Current; + + void IDisposable.Dispose() => _enumerator.Dispose(); + + public bool MoveNext() => _enumerator.MoveNext(); + + void IEnumerator.Reset() { } + } + } + + private readonly string DebuggerDisplay => + $"Key count = {_readOnlyMemoryKeys.Count}, Prefix = {_currentPrefixBuffer}, Error count = {_errorCount}, Current depth = {_currentDepth}"; +} + +=== baseTip 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/FormDataMapper.cs:1-48 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.Extensions.Logging; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping; + +internal static partial class FormDataMapper +{ + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + public static T? Map( + FormDataReader reader, + FormDataMapperOptions options) + { + FormDataConverter? converter; + try + { + converter = options.ResolveConverter(); + if (converter == null) + { + Log.CannotResolveConverter(options.Logger, typeof(T), null); + return default; + } + } + catch (Exception ex) + { + Log.CannotResolveConverter(options.Logger, typeof(T), ex); + return default; + } + + if (converter.TryRead(ref reader, typeof(T), options, out var result, out _)) + { + return result; + } + + // Always return the result, even if it has failures. This is because we do not want + // to loose the data that we were able to deserialize. + return result; + } + + private static partial class Log + { + [LoggerMessage(1, LogLevel.Warning, "Cannot resolve converter for type '{Type}'.", EventName = "CannotResolveConverter")] + public static partial void CannotResolveConverter(ILogger logger, Type type, Exception? ex); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/case.source b/eng/skill-evals/review-pull-request/fixtures/case-02/case.source new file mode 100644 index 000000000000..a6e91438784d --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/case.source @@ -0,0 +1,8 @@ +Repository: dotnet/aspnetcore +Pull request: https://github.com/dotnet/aspnetcore/pull/69782 +Head: cfe304ed94f2c9de0e1069947ba51c8c82690ba7 +Merge base: 4f556f73a610b386e5ec29355a300e493d30c4c5 +Base tip: 4f556f73a610b386e5ec29355a300e493d30c4c5 +The source files are excerpts, not a complete ready version-2 review bundle. +provenance.json maps every excerpt to its original source path and lines. +C1: Changing found to false for an unmatched IReadOnlyList causes a required constructor parameter to report a mapping error where the old mapper supplied an empty collection. Consider mapping a complex type with constructor IReadOnlyList files and a populated non-file property, with form files named otherFile and none named files. diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/change.diff b/eng/skill-evals/review-pull-request/fixtures/case-02/change.diff new file mode 100644 index 000000000000..e7645aff4bd1 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/change.diff @@ -0,0 +1,34 @@ +diff --git a/src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs b/src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs +index fb2d1b74ea..1218cae3d7 100644 +--- a/src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs ++++ b/src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs +@@ -44,22 +44,25 @@ internal sealed class FileConverter : FormDataConverter + buffer = ReadOnlyCollectionBufferAdapter.Add(ref buffer, new BrowserFileFromFormFile(targetFiles[i])); + } + result = (T)(IReadOnlyList)ReadOnlyCollectionBufferAdapter.ToResult(buffer); +- found = true; ++ found = targetFiles.Count > 0; + return true; + } + #endif + + if (typeof(T) == typeof(IReadOnlyList)) + { +- result = (T)reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); +- found = true; ++ var targetFiles = reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); ++ result = (T)targetFiles; ++ found = targetFiles.Count > 0; + return true; + } + + if (typeof(T) == typeof(IFormFileCollection)) + { + result = (T)reader.FormFileCollection; +- found = true; ++ found = reader.CurrentPrefix.Span.IndexOf('[') < 0 ++ ? reader.FormFileCollection.Count > 0 ++ : reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()).Count > 0; + return true; + } + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/context.source b/eng/skill-evals/review-pull-request/fixtures/case-02/context.source new file mode 100644 index 000000000000..992e68d82656 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/context.source @@ -0,0 +1,19 @@ +=== head cfe304ed94f2c9de0e1069947ba51c8c82690ba7 src/Components/Endpoints/test/Binding/FormDataMapperTests.cs:2512-2528 === + public void CanDeserialize_ComplexType_IReadOnlyListFormFileWithNoMatches_IsNotFound() + { + var formFileCollection = new FormFileCollection + { + new FormFile(Stream.Null, 0, 10, "otherFile", "file.txt"), + }; + var data = new Dictionary(); + var reader = CreateFormDataReader(data, CultureInfo.InvariantCulture, formFileCollection); + reader.PushPrefix("file"); + var converter = new FileConverter>(); + + var succeeded = converter.TryRead(ref reader, typeof(IReadOnlyList), default!, out var result, out var found); + + Assert.True(succeeded); + Assert.False(found); + Assert.Empty(result); + } + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/head.source b/eng/skill-evals/review-pull-request/fixtures/case-02/head.source new file mode 100644 index 000000000000..9ffd38a2455f --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/head.source @@ -0,0 +1,91 @@ +=== head cfe304ed94f2c9de0e1069947ba51c8c82690ba7 src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs:1-89 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +#if COMPONENTS +using Microsoft.AspNetCore.Components.Forms; +#endif +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping; + +internal sealed class FileConverter : FormDataConverter +{ + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + internal override bool TryRead(ref FormDataReader reader, Type type, FormDataMapperOptions options, out T? result, out bool found) + { + if (reader.FormFileCollection == null) + { + result = default; + found = false; + return true; + } + +#if COMPONENTS + if (typeof(T) == typeof(IBrowserFile)) + { + var targetFile = reader.FormFileCollection.GetFile(reader.CurrentPrefix.ToString()); + if (targetFile != null) + { + var browserFile = new BrowserFileFromFormFile(targetFile); + result = (T)(IBrowserFile)browserFile; + found = true; + return true; + } + } + + if (typeof(T) == typeof(IReadOnlyList)) + { + var targetFiles = reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); + var buffer = ReadOnlyCollectionBufferAdapter.CreateBuffer(); + for (var i = 0; i < targetFiles.Count; i++) + { + buffer = ReadOnlyCollectionBufferAdapter.Add(ref buffer, new BrowserFileFromFormFile(targetFiles[i])); + } + result = (T)(IReadOnlyList)ReadOnlyCollectionBufferAdapter.ToResult(buffer); + found = targetFiles.Count > 0; + return true; + } +#endif + + if (typeof(T) == typeof(IReadOnlyList)) + { + var targetFiles = reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); + result = (T)targetFiles; + found = targetFiles.Count > 0; + return true; + } + + if (typeof(T) == typeof(IFormFileCollection)) + { + result = (T)reader.FormFileCollection; + found = reader.CurrentPrefix.Span.IndexOf('[') < 0 + ? reader.FormFileCollection.Count > 0 + : reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()).Count > 0; + return true; + } + + var formFileCollection = reader.FormFileCollection; + if (formFileCollection.Count == 0) + { + result = default; + found = false; + return true; + } + + var file = formFileCollection.GetFile(reader.CurrentPrefix.ToString()); + if (file != null) + { + result = (T)file; + found = true; + return true; + } + + result = default; + found = false; + return true; + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/mergeBase.source b/eng/skill-evals/review-pull-request/fixtures/case-02/mergeBase.source new file mode 100644 index 000000000000..528e2e1a1123 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/mergeBase.source @@ -0,0 +1,88 @@ +=== mergeBase 4f556f73a610b386e5ec29355a300e493d30c4c5 src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs:1-86 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +#if COMPONENTS +using Microsoft.AspNetCore.Components.Forms; +#endif +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping; + +internal sealed class FileConverter : FormDataConverter +{ + [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] + [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] + internal override bool TryRead(ref FormDataReader reader, Type type, FormDataMapperOptions options, out T? result, out bool found) + { + if (reader.FormFileCollection == null) + { + result = default; + found = false; + return true; + } + +#if COMPONENTS + if (typeof(T) == typeof(IBrowserFile)) + { + var targetFile = reader.FormFileCollection.GetFile(reader.CurrentPrefix.ToString()); + if (targetFile != null) + { + var browserFile = new BrowserFileFromFormFile(targetFile); + result = (T)(IBrowserFile)browserFile; + found = true; + return true; + } + } + + if (typeof(T) == typeof(IReadOnlyList)) + { + var targetFiles = reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); + var buffer = ReadOnlyCollectionBufferAdapter.CreateBuffer(); + for (var i = 0; i < targetFiles.Count; i++) + { + buffer = ReadOnlyCollectionBufferAdapter.Add(ref buffer, new BrowserFileFromFormFile(targetFiles[i])); + } + result = (T)(IReadOnlyList)ReadOnlyCollectionBufferAdapter.ToResult(buffer); + found = true; + return true; + } +#endif + + if (typeof(T) == typeof(IReadOnlyList)) + { + result = (T)reader.FormFileCollection.GetFiles(reader.CurrentPrefix.ToString()); + found = true; + return true; + } + + if (typeof(T) == typeof(IFormFileCollection)) + { + result = (T)reader.FormFileCollection; + found = true; + return true; + } + + var formFileCollection = reader.FormFileCollection; + if (formFileCollection.Count == 0) + { + result = default; + found = false; + return true; + } + + var file = formFileCollection.GetFile(reader.CurrentPrefix.ToString()); + if (file != null) + { + result = (T)file; + found = true; + return true; + } + + result = default; + found = false; + return true; + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-02/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-02/provenance.json new file mode 100644 index 000000000000..0965e2678f3f --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-02/provenance.json @@ -0,0 +1,151 @@ +{ + "repository": "dotnet/aspnetcore", + "pullRequest": 69782, + "sourceRoles": { + "mergeBase": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "head": "cfe304ed94f2c9de0e1069947ba51c8c82690ba7", + "baseTip": "4f556f73a610b386e5ec29355a300e493d30c4c5" + }, + "files": [ + { + "file": "mergeBase.source", + "sha256": "8abba8f0360a7d24e52517cecef7e365f689fa554df5dd81ad58aa6e7d9f5f4a", + "sources": [ + { + "role": "mergeBase", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs", + "blob": "fb2d1b74eae55c6c61cfb3bfbf30b4f08c2c79ff", + "ranges": [ + [ + 1, + 86 + ] + ] + } + ] + }, + { + "file": "head.source", + "sha256": "69b46771aa41acfbc6394eb67e7024eaf1900485561a562cbd78dff3e2b15571", + "sources": [ + { + "role": "head", + "commit": "cfe304ed94f2c9de0e1069947ba51c8c82690ba7", + "path": "src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs", + "blob": "1218cae3d76bff951a6711a966648ed08fc66b6b", + "ranges": [ + [ + 1, + 89 + ] + ] + } + ] + }, + { + "file": "baseTip.source", + "sha256": "70227fa96f82af98184a4ee45d5f34fcad6aae1c595f2efce558235dc5b335a6", + "sources": [ + { + "role": "baseTip", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/Converters/FileConverter.cs", + "blob": "fb2d1b74eae55c6c61cfb3bfbf30b4f08c2c79ff", + "ranges": [ + [ + 1, + 86 + ] + ] + }, + { + "role": "baseTip", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/Factories/ComplexType/ComplexTypeExpressionConverterFactoryOfT.cs", + "blob": "96146387c11ca2a7fa96a06b9e1fbdea515923b6", + "ranges": [ + [ + 1, + 621 + ] + ] + }, + { + "role": "baseTip", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/Metadata/FormDataMetadataFactory.cs", + "blob": "ff2fa90f11333969775a6b426c46581310936114", + "ranges": [ + [ + 1, + 428 + ] + ] + }, + { + "role": "baseTip", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/Metadata/FormDataParameterMetadata.cs", + "blob": "1d631872df400af8e691dbed26218491bb3daed2", + "ranges": [ + [ + 1, + 25 + ] + ] + }, + { + "role": "baseTip", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/FormDataReader.cs", + "blob": "f142f0e9e003ea913fbc66149ca9634449e99b1b", + "ranges": [ + [ + 1, + 318 + ] + ] + }, + { + "role": "baseTip", + "commit": "4f556f73a610b386e5ec29355a300e493d30c4c5", + "path": "src/Components/Endpoints/src/FormMapping/FormDataMapper.cs", + "blob": "00873d0f9baf500d71c719697aabd3d10cfc632a", + "ranges": [ + [ + 1, + 48 + ] + ] + } + ] + }, + { + "file": "context.source", + "sha256": "8217b34af259159122162b8dc3ed55bbac2546d86c7dca8ed69cdb8a6cf2230b", + "sources": [ + { + "role": "head", + "commit": "cfe304ed94f2c9de0e1069947ba51c8c82690ba7", + "path": "src/Components/Endpoints/test/Binding/FormDataMapperTests.cs", + "blob": "1c8d7e66f14c3cb1264589608657ed6bdb7bbb30", + "ranges": [ + [ + 2512, + 2528 + ] + ] + } + ] + }, + { + "file": "change.diff", + "sha256": "19e641ec597c9b3d9d3d3985178bc2e34713fa628eeb0616cca4ba757b025f56" + }, + { + "file": "case.source", + "sha256": "4325461840a90e04aef5ad5eff7734c3e386343a21e45aa158a4474710b12985" + } + ] +} diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/baseTip.source b/eng/skill-evals/review-pull-request/fixtures/case-03/baseTip.source new file mode 100644 index 000000000000..67c86497d5b8 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/baseTip.source @@ -0,0 +1,127 @@ +=== baseTip 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 src/Components/Components/src/RenderHandle.cs:1-125 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Components.HotReload; +using Microsoft.AspNetCore.Components.RenderTree; +using Microsoft.AspNetCore.Components.Sections; + +namespace Microsoft.AspNetCore.Components; + +/// +/// Allows a component to interact with its renderer. +/// +public readonly struct RenderHandle +{ + private readonly Renderer? _renderer; + private readonly int _componentId; + + internal RenderHandle(Renderer renderer, int componentId) + { + _renderer = renderer ?? throw new ArgumentNullException(nameof(renderer)); + _componentId = componentId; + } + + internal ComponentsMetrics? ComponentMetrics => _renderer?.ComponentMetrics; + internal ComponentsActivitySource? ComponentActivitySource => _renderer?.ComponentActivitySource; + internal SectionRegistry SectionRegistry => _renderer?.SectionRegistry ?? throw new InvalidOperationException("No renderer has been initialized."); + + /// + /// Gets the associated with the component. + /// + public Dispatcher Dispatcher + { + get + { + if (_renderer == null) + { + ThrowNotInitialized(); + } + + return _renderer.Dispatcher; + } + } + + /// + /// Gets a value that indicates whether the has been + /// initialized and is ready to use. + /// + public bool IsInitialized => _renderer is not null; + + /// + /// Gets a value that determines if the is triggering a render in response to a metadata update (hot-reload) change. + /// + public bool IsRenderingOnMetadataUpdate => HotReloadManager.IsSupported && (_renderer?.IsRenderingOnMetadataUpdate ?? false); + + internal bool IsFirstHotReloadRender() => IsRenderingOnMetadataUpdate && _renderer?.IsFirstHotReloadRender(_componentId) == true; + + internal bool IsRendererDisposed => _renderer?.Disposed + ?? throw new InvalidOperationException("No renderer has been initialized."); + + /// + /// Gets the the component is running on. + /// + public RendererInfo RendererInfo => _renderer?.RendererInfo ?? throw new InvalidOperationException("No renderer has been initialized."); + + /// + /// Retrieves the assigned to the component. + /// + /// The assigned to the component. + public IComponentRenderMode? RenderMode + { + get + { + if (_renderer == null) + { + throw new InvalidOperationException("No renderer has been initialized."); + } + + return _renderer.GetComponentRenderMode(_componentId); + } + } + + /// + /// Gets the associated with the . + /// + public ResourceAssetCollection Assets + { + get + { + return _renderer?.Assets ?? throw new InvalidOperationException("No renderer has been initialized."); + } + } + + /// + /// Notifies the renderer that the component should be rendered. + /// + /// The content that should be rendered. + public void Render(RenderFragment renderFragment) + { + if (_renderer == null) + { + ThrowNotInitialized(); + } + + _renderer.AddToRenderQueue(_componentId, renderFragment); + } + + /// + /// Dispatches an to the . + /// + /// The that will be dispatched to the renderer. + /// A that will be completed when the exception has finished dispatching. + public Task DispatchExceptionAsync(Exception exception) + { + var renderer = _renderer; + var componentId = _componentId; + return Dispatcher.InvokeAsync(() => renderer!.HandleComponentException(exception, componentId)); + } + + [DoesNotReturn] + private static void ThrowNotInitialized() + { + throw new InvalidOperationException("The render handle is not yet assigned."); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/case.source b/eng/skill-evals/review-pull-request/fixtures/case-03/case.source new file mode 100644 index 000000000000..61014c106768 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/case.source @@ -0,0 +1,8 @@ +Repository: dotnet/aspnetcore +Pull request: https://github.com/dotnet/aspnetcore/pull/70304 +Head: fd7be3828242ffabf3f64d230bfb511bbe42f553 +Merge base: 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 +Base tip: 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 +The source files are excerpts, not a complete ready version-2 review bundle. +provenance.json maps every excerpt to its original source path and lines. +C1: The new _rendererIsDisposed guard removes previously functioning ErrorBoundary delivery for DispatchExceptionAsync called by background work after Renderer.Dispose completes. diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/change.diff b/eng/skill-evals/review-pull-request/fixtures/case-03/change.diff new file mode 100644 index 000000000000..8dbf27563705 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/change.diff @@ -0,0 +1,20 @@ +diff --git a/src/Components/Components/src/RenderTree/Renderer.cs b/src/Components/Components/src/RenderTree/Renderer.cs +index 43130ce396..1b66058ffd 100644 +--- a/src/Components/Components/src/RenderTree/Renderer.cs ++++ b/src/Components/Components/src/RenderTree/Renderer.cs +@@ -1180,7 +1180,14 @@ public abstract partial class Renderer : IDisposable, IAsyncDisposable + } + + internal void HandleComponentException(Exception exception, int componentId) +- => HandleExceptionViaErrorBoundary(exception, GetRequiredComponentState(componentId)); ++ { ++ if (_rendererIsDisposed) ++ { ++ return; ++ } ++ ++ HandleExceptionViaErrorBoundary(exception, GetRequiredComponentState(componentId)); ++ } + + /// + /// If the exception can be routed to an error boundary around , do so. diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/context.source b/eng/skill-evals/review-pull-request/fixtures/case-03/context.source new file mode 100644 index 000000000000..139698b0fd40 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/context.source @@ -0,0 +1,116 @@ +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/test/RendererTest.cs:6095-6106 === + public async Task DispatchExceptionAsync_AfterRendererIsDisposed_DoesNotThrow() + { + var renderer = new TestRenderer(); + var component = new DispatchExceptionComponent(); + var componentId = renderer.AssignRootComponentId(component); + await renderer.RenderRootComponentAsync(componentId); + renderer.Dispose(); + + await component.DispatchAsync(new InvalidTimeZoneException("Test exception")); + + Assert.Empty(renderer.HandledExceptions); + } + +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/test/RendererTest.cs:6109-6121 === + public async Task DispatchExceptionAsync_AfterComponentIsRemoved_Throws() + { + var renderer = new TestRenderer(); + var component = new DispatchExceptionComponent(); + var componentId = renderer.AssignRootComponentId(component); + await renderer.RenderRootComponentAsync(componentId); + await renderer.Dispatcher.InvokeAsync(() => renderer.RemoveRootComponent(componentId)); + + var exception = await Assert.ThrowsAsync(() => component.DispatchAsync(new InvalidTimeZoneException("Test exception"))); + + Assert.Equal($"The renderer does not have a component with ID {componentId}.", exception.Message); + Assert.Empty(renderer.HandledExceptions); + } + +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/test/RendererTest.cs:6232-6258 === + public async Task DispatchExceptionAsync_LiveComponent_UsesClosestErrorBoundary() + { + var renderer = new TestRenderer(); + var rootComponentId = renderer.AssignRootComponentId(new TestComponent(builder => + { + TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder => + { + builder.OpenComponent(0); + builder.CloseComponent(); + }); + })); + await renderer.RenderRootComponentAsync(rootComponentId); + var batch = Assert.Single(renderer.Batches); + var componentFrame = Assert.Single(batch.GetComponentFrames()); + var component = (DispatchExceptionComponent)componentFrame.Component; + var errorBoundaries = batch.GetComponentFrames() + .Select(frame => (TestErrorBoundary)frame.Component).ToArray(); + var exception = new InvalidTimeZoneException("Test exception"); + + await component.DispatchAsync(exception); + + Assert.Collection(errorBoundaries, + boundary => Assert.Null(boundary.ReceivedException), + boundary => Assert.Same(exception, boundary.ReceivedException)); + Assert.Empty(renderer.HandledExceptions); + Assert.Equal(componentFrame.ComponentId, Assert.Single(renderer.Batches[1].DisposedComponentIDs)); + } + +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/test/RendererTest.cs:6291-6294 === + private class DispatchExceptionComponent : ComponentBase + { + public Task DispatchAsync(Exception exception) => DispatchExceptionAsync(exception); + } + + +=== https://github.com/dotnet/aspnetcore/issues/66322 === +### Describe the bug + +I originally reported this issue on the .NET MAUI side: https://github.com/dotnet/maui/issues/34855. While investigating, I encountered several exceptions, and I believe the specific case described below belongs in this repository. + +Consider the following: + +```csharp +@code { + private bool _loading; + + protected override async Task OnInitializedAsync() + { + await base.OnInitializedAsync(); + _ = BackgroundWork(); + } + + private async Task BackgroundWork() + { + _loading = true; + await InvokeAsync(StateHasChanged); + + try + { + await Task.Delay(5000); + throw new Exception("Exception"); + } + catch (Exception exception) + { + // MainLayout needs to be wrapped in ErrorBoundary + await DispatchExceptionAsync(exception); + } + finally + { + _loading = false; + await InvokeAsync(StateHasChanged); + } + } +} +``` + +If the browser is closed while `Task.Delay` is still in progress and the WebView is **explicitly disposed**(!!!) via `BlazorWebView.DisposeAsync()`, an exception `Renderer does not have a component with ID XX` is thrown. +If the WebView is not explicitly disposed, a different exception occurs instead, related to the `WebView2` control already being disposed. + +This behavior has been reproduced in WPF. I have not tested WinForms, but I expect similar behavior since most of the code is shared (aside from the dispatcher). I have also not verified whether this affects MAUI Hybrid. + + +### Expected Behavior + +Not to throw exception when webview is disposed. + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/head.source b/eng/skill-evals/review-pull-request/fixtures/case-03/head.source new file mode 100644 index 000000000000..4f8cffe2c414 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/head.source @@ -0,0 +1,182 @@ +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/src/RenderTree/Renderer.cs:802-805 === + internal ComponentState GetRequiredComponentState(int componentId) + => _componentStateById.TryGetValue(componentId, out var componentState) + ? componentState + : throw new ArgumentException($"The renderer does not have a component with ID {componentId}."); + +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/src/RenderTree/Renderer.cs:1182-1190 === + internal void HandleComponentException(Exception exception, int componentId) + { + if (_rendererIsDisposed) + { + return; + } + + HandleExceptionViaErrorBoundary(exception, GetRequiredComponentState(componentId)); + } + +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/src/RenderTree/Renderer.cs:1196-1240 === + private void HandleExceptionViaErrorBoundary(Exception error, ComponentState? errorSourceOrNull) + { + // We only get here in specific situations. Currently, all of them are when we're + // already on the sync context (and if not, we have a bug we want to know about). + Dispatcher.AssertAccess(); + + // We don't allow NavigationException instances to be caught by error boundaries. + // These are special exceptions whose purpose is to be as invisible as possible to + // user code and bubble all the way up to get handled by the framework as a redirect. + if (error is NavigationException) + { + HandleException(error); + return; + } + + // Find the closest error boundary, if any + var candidate = errorSourceOrNull; + while (candidate is not null) + { + if (candidate.Component is IErrorBoundary errorBoundary) + { + // Don't just trust the error boundary to dispose its subtree - force it to do so by + // making it render an empty fragment. Ensures that failed components don't continue to + // operate, which would be a whole new kind of edge case to support forever. + AddToRenderQueue(candidate.ComponentId, builder => { }); + + try + { + errorBoundary.HandleException(error); + } + catch (Exception errorBoundaryException) + { + // If *notifying* about an exception fails, it's OK for that to be fatal + HandleException(errorBoundaryException); + } + + return; // Handled successfully + } + + candidate = candidate.LogicalParentComponentState; + } + + // It's unhandled, so treat as fatal + HandleException(error); + } + +=== head fd7be3828242ffabf3f64d230bfb511bbe42f553 src/Components/Components/src/RenderTree/Renderer.cs:1246-1361 === + protected virtual void Dispose(bool disposing) + { + // Unlike other Renderer APIs, we need Dispose to be thread-safe + // (and not require being called only from the sync context) + // because other classes many need to dispose a Renderer during their own Dispose (rather than DisposeAsync) + // and we don't want to force that other code to deal with calling InvokeAsync from a synchronous method. + lock (_lockObject) + { + if (_rendererIsDisposed) + { + // quitting synchronously as soon as possible is avoiding + // possible async dispatch to another thread and + // possible deadlock on synchronous `done.Wait()` below. + return; + } + } + + if (!Dispatcher.CheckAccess()) + { + // It's important that we only call the components' Dispose/DisposeAsync lifecycle methods + // on the sync context, like other lifecycle methods. In almost all cases we'd already be + // on the sync context here since DisposeAsync dispatches, but just in case someone is using + // Dispose directly, we'll dispatch and block. + var done = Dispatcher.InvokeAsync(() => Dispose(disposing)); + + // only block caller when this is not finalizer + if (disposing) + { + done.Wait(); + } + + return; + } + + lock (_lockObject) + { + _rendererIsDisposed = true; + } + + if (HotReload.HotReloadManager.IsSupported && HotReloadManager != null && _hotReloadInitialized && _hotReloadRenderHandler is not null) + { + HotReloadManager.OnDeltaApplied -= _hotReloadRenderHandler.RerenderOnHotReload; + } + + // It's important that we handle all exceptions here before reporting any of them. + // This way we can dispose all components before an error handler kicks in. + List exceptions = null; + List asyncDisposables = null; + foreach (var componentState in _componentStateById.Values) + { + Log.DisposingComponent(_logger, componentState); + + try + { + var task = componentState.DisposeAsync(); + if (task.IsCompletedSuccessfully) + { + // If it's a IValueTaskSource backed ValueTask, + // inform it its result has been read so it can reset + task.GetAwaiter().GetResult(); + } + else + { + asyncDisposables ??= new(); + asyncDisposables.Add(task.AsTask()); + } + } + catch (Exception exception) + { + exceptions ??= new List(); + exceptions.Add(exception); + } + } + + _componentStateById.Clear(); // So we know they were all disposed + _componentStateByComponent.Clear(); + _batchBuilder.Dispose(); + + NotifyExceptions(exceptions); + + if (asyncDisposables?.Count >= 1) + { + _disposeTask = HandleAsyncExceptions(asyncDisposables); + } + + async Task HandleAsyncExceptions(List tasks) + { + List asyncExceptions = null; + foreach (var task in tasks) + { + try + { + await task; + } + catch (Exception exception) + { + asyncExceptions ??= new List(); + asyncExceptions.Add(exception); + } + } + + NotifyExceptions(asyncExceptions); + } + + void NotifyExceptions(List exceptions) + { + if (exceptions?.Count > 1) + { + HandleException(new AggregateException("Exceptions were encountered while disposing components.", exceptions)); + } + else if (exceptions?.Count == 1) + { + HandleException(exceptions[0]); + } + } + } + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/mergeBase.source b/eng/skill-evals/review-pull-request/fixtures/case-03/mergeBase.source new file mode 100644 index 000000000000..f7cadb6f4a2e --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/mergeBase.source @@ -0,0 +1,175 @@ +=== mergeBase 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 src/Components/Components/src/RenderTree/Renderer.cs:802-805 === + internal ComponentState GetRequiredComponentState(int componentId) + => _componentStateById.TryGetValue(componentId, out var componentState) + ? componentState + : throw new ArgumentException($"The renderer does not have a component with ID {componentId}."); + +=== mergeBase 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 src/Components/Components/src/RenderTree/Renderer.cs:1182-1183 === + internal void HandleComponentException(Exception exception, int componentId) + => HandleExceptionViaErrorBoundary(exception, GetRequiredComponentState(componentId)); + +=== mergeBase 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 src/Components/Components/src/RenderTree/Renderer.cs:1189-1233 === + private void HandleExceptionViaErrorBoundary(Exception error, ComponentState? errorSourceOrNull) + { + // We only get here in specific situations. Currently, all of them are when we're + // already on the sync context (and if not, we have a bug we want to know about). + Dispatcher.AssertAccess(); + + // We don't allow NavigationException instances to be caught by error boundaries. + // These are special exceptions whose purpose is to be as invisible as possible to + // user code and bubble all the way up to get handled by the framework as a redirect. + if (error is NavigationException) + { + HandleException(error); + return; + } + + // Find the closest error boundary, if any + var candidate = errorSourceOrNull; + while (candidate is not null) + { + if (candidate.Component is IErrorBoundary errorBoundary) + { + // Don't just trust the error boundary to dispose its subtree - force it to do so by + // making it render an empty fragment. Ensures that failed components don't continue to + // operate, which would be a whole new kind of edge case to support forever. + AddToRenderQueue(candidate.ComponentId, builder => { }); + + try + { + errorBoundary.HandleException(error); + } + catch (Exception errorBoundaryException) + { + // If *notifying* about an exception fails, it's OK for that to be fatal + HandleException(errorBoundaryException); + } + + return; // Handled successfully + } + + candidate = candidate.LogicalParentComponentState; + } + + // It's unhandled, so treat as fatal + HandleException(error); + } + +=== mergeBase 1c94b15aa54d3d490d0ee060b7d496db3cb291e7 src/Components/Components/src/RenderTree/Renderer.cs:1239-1354 === + protected virtual void Dispose(bool disposing) + { + // Unlike other Renderer APIs, we need Dispose to be thread-safe + // (and not require being called only from the sync context) + // because other classes many need to dispose a Renderer during their own Dispose (rather than DisposeAsync) + // and we don't want to force that other code to deal with calling InvokeAsync from a synchronous method. + lock (_lockObject) + { + if (_rendererIsDisposed) + { + // quitting synchronously as soon as possible is avoiding + // possible async dispatch to another thread and + // possible deadlock on synchronous `done.Wait()` below. + return; + } + } + + if (!Dispatcher.CheckAccess()) + { + // It's important that we only call the components' Dispose/DisposeAsync lifecycle methods + // on the sync context, like other lifecycle methods. In almost all cases we'd already be + // on the sync context here since DisposeAsync dispatches, but just in case someone is using + // Dispose directly, we'll dispatch and block. + var done = Dispatcher.InvokeAsync(() => Dispose(disposing)); + + // only block caller when this is not finalizer + if (disposing) + { + done.Wait(); + } + + return; + } + + lock (_lockObject) + { + _rendererIsDisposed = true; + } + + if (HotReload.HotReloadManager.IsSupported && HotReloadManager != null && _hotReloadInitialized && _hotReloadRenderHandler is not null) + { + HotReloadManager.OnDeltaApplied -= _hotReloadRenderHandler.RerenderOnHotReload; + } + + // It's important that we handle all exceptions here before reporting any of them. + // This way we can dispose all components before an error handler kicks in. + List exceptions = null; + List asyncDisposables = null; + foreach (var componentState in _componentStateById.Values) + { + Log.DisposingComponent(_logger, componentState); + + try + { + var task = componentState.DisposeAsync(); + if (task.IsCompletedSuccessfully) + { + // If it's a IValueTaskSource backed ValueTask, + // inform it its result has been read so it can reset + task.GetAwaiter().GetResult(); + } + else + { + asyncDisposables ??= new(); + asyncDisposables.Add(task.AsTask()); + } + } + catch (Exception exception) + { + exceptions ??= new List(); + exceptions.Add(exception); + } + } + + _componentStateById.Clear(); // So we know they were all disposed + _componentStateByComponent.Clear(); + _batchBuilder.Dispose(); + + NotifyExceptions(exceptions); + + if (asyncDisposables?.Count >= 1) + { + _disposeTask = HandleAsyncExceptions(asyncDisposables); + } + + async Task HandleAsyncExceptions(List tasks) + { + List asyncExceptions = null; + foreach (var task in tasks) + { + try + { + await task; + } + catch (Exception exception) + { + asyncExceptions ??= new List(); + asyncExceptions.Add(exception); + } + } + + NotifyExceptions(asyncExceptions); + } + + void NotifyExceptions(List exceptions) + { + if (exceptions?.Count > 1) + { + HandleException(new AggregateException("Exceptions were encountered while disposing components.", exceptions)); + } + else if (exceptions?.Count == 1) + { + HandleException(exceptions[0]); + } + } + } + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-03/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-03/provenance.json new file mode 100644 index 000000000000..6dd3c117dfe3 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-03/provenance.json @@ -0,0 +1,131 @@ +{ + "repository": "dotnet/aspnetcore", + "pullRequest": 70304, + "sourceRoles": { + "mergeBase": "1c94b15aa54d3d490d0ee060b7d496db3cb291e7", + "head": "fd7be3828242ffabf3f64d230bfb511bbe42f553", + "baseTip": "1c94b15aa54d3d490d0ee060b7d496db3cb291e7" + }, + "files": [ + { + "file": "mergeBase.source", + "sha256": "ecb8038853cbc557a8bf189df33bf00820761e1cc05b088fe0ada1e70a1f0236", + "sources": [ + { + "role": "mergeBase", + "commit": "1c94b15aa54d3d490d0ee060b7d496db3cb291e7", + "path": "src/Components/Components/src/RenderTree/Renderer.cs", + "blob": "43130ce39615fad333f5e7ecf9401c0f4d0dc540", + "ranges": [ + [ + 802, + 805 + ], + [ + 1182, + 1183 + ], + [ + 1189, + 1233 + ], + [ + 1239, + 1354 + ] + ] + } + ] + }, + { + "file": "head.source", + "sha256": "1f92291015003c6ac6993efec14449443ef38d470899beb1c0e7d086424fd824", + "sources": [ + { + "role": "head", + "commit": "fd7be3828242ffabf3f64d230bfb511bbe42f553", + "path": "src/Components/Components/src/RenderTree/Renderer.cs", + "blob": "1b66058ffdc00d9a7f657057dadd8331815acb31", + "ranges": [ + [ + 802, + 805 + ], + [ + 1182, + 1190 + ], + [ + 1196, + 1240 + ], + [ + 1246, + 1361 + ] + ] + } + ] + }, + { + "file": "baseTip.source", + "sha256": "19fad0c5eb14bb14491bf45e2d097eed8d22016472bacd515dbc799e1d98d6db", + "sources": [ + { + "role": "baseTip", + "commit": "1c94b15aa54d3d490d0ee060b7d496db3cb291e7", + "path": "src/Components/Components/src/RenderHandle.cs", + "blob": "bc5e2eb02a019506941d1db8d572ff899b392096", + "ranges": [ + [ + 1, + 125 + ] + ] + } + ] + }, + { + "file": "context.source", + "sha256": "5f4ff01204f825cfab5d6e2dd22f619c1f17bb95608ccae181b1891455635c66", + "sources": [ + { + "role": "head", + "commit": "fd7be3828242ffabf3f64d230bfb511bbe42f553", + "path": "src/Components/Components/test/RendererTest.cs", + "blob": "8c5f99d695e75e9f5fd3d97b229d13e46e4cdb02", + "ranges": [ + [ + 6095, + 6106 + ], + [ + 6109, + 6121 + ], + [ + 6232, + 6258 + ], + [ + 6291, + 6294 + ] + ] + } + ], + "issue": { + "url": "https://github.com/dotnet/aspnetcore/issues/66322", + "updatedAt": "2026-10-07T19:08:14Z" + } + }, + { + "file": "change.diff", + "sha256": "7d4f8a6cb6d9989d849a9a3c485e85238cbb1c844408c7ab9b724807f98ac975" + }, + { + "file": "case.source", + "sha256": "769c32c864e5c768a7e2351f3bcf188ee703912c8bce2a07cbb0e61bdf5be807" + } + ] +} diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/baseTip.source b/eng/skill-evals/review-pull-request/fixtures/case-04/baseTip.source new file mode 100644 index 000000000000..f78793112cca --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/baseTip.source @@ -0,0 +1,517 @@ +=== baseTip 66e2adb4e0297e445686cb7a70d6c9aa84dcf3af src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts:1-515 === +import * as Msal from '@azure/msal-browser'; + +interface AccessTokenRequestOptions { + scopes: string[]; + returnUrl: string; +} + +interface AccessTokenResult { + status: AccessTokenResultStatus; + token?: AccessToken; +} + +interface AccessToken { + value: string; + expires: Date | null; + grantedScopes: string[]; +} + +enum AccessTokenResultStatus { + Success = "success", + RequiresRedirect = "requiresRedirect" +} + +enum AuthenticationResultStatus { + Redirect = "redirect", + Success = "success", + Failure = "failure", + OperationCompleted = "operationCompleted" +} + +interface AuthenticationResult { + status: AuthenticationResultStatus; + state?: any; + message?: string; +} + +interface AuthorizeService { + getUser(): Promise; + getAccessToken(request?: AccessTokenRequestOptions): Promise; + signIn(state: any): Promise; + completeSignIn(state: any): Promise; + signOut(state: any): Promise; + completeSignOut(url: string): Promise; +} + +// These are the values for the .NET logger LogLevel. +// We only use debug and trace +export enum LogLevel { + Trace = 0, + Debug = 1 +} + +interface JavaScriptLoggingOptions { + debugEnabled: boolean; + traceEnabled: boolean; +} + +export class Logger { + public debug: boolean; + public trace: boolean; + public constructor(options: JavaScriptLoggingOptions) { + this.debug = options.debugEnabled; + this.trace = options.traceEnabled; + } + + log(level: LogLevel, message: string): void { + if ((level == LogLevel.Trace && this.trace) || + (level == LogLevel.Debug && this.debug)) { + const levelString = level == LogLevel.Trace ? 'trce' : 'dbug'; + console.debug( + // Logs in the following format to keep consistency with the way ASP.NET Core logs to the console while avoiding the + // additional overhead of passing the logger as a JSObjectReference + // dbug: Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationService[0] + // <> + // trce: Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationService[0] + // <> + `${levelString}: Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationService[0] + ${message}`); + } + } +} + +export interface AuthenticationContext { + state?: unknown; + interactiveRequest: InteractiveAuthenticationRequest; +} + +export interface InteractiveAuthenticationRequest { + interaction: string; + scopes?: string[]; + additionalRequestParameters?: { [key: string]: any }; +}; + +interface AuthorizeServiceConfiguration extends Msal.Configuration { + defaultAccessTokenScopes: string[]; + additionalScopesToConsent: string[]; + loginMode: string; +} + +class MsalAuthorizeService implements AuthorizeService { + private readonly _msalApplication: Msal.PublicClientApplication; + private _account: Msal.AccountInfo | null | undefined; + private _redirectCallback: Promise | undefined; + + constructor(private readonly _settings: AuthorizeServiceConfiguration, private readonly _logger: Logger) { + if (this._settings.auth?.knownAuthorities?.length == 0) { + this._settings.auth.knownAuthorities = [new URL(this._settings.auth.authority!).hostname] + } + + this._settings.system = this._settings.system || {}; + + this._settings.system.navigationClient = { + async navigateInternal(url: string, options: Msal.NavigationOptions): Promise { + // We always replace the URL + _logger.log(LogLevel.Trace, `Navigating to ${url}`); + location.replace(url); + return false; + }, + async navigateExternal(url: string, options: Msal.NavigationOptions): Promise { + // We always replace the URL + _logger.log(LogLevel.Trace, `Navigating to ${url}`); + location.replace(url); + return false; + } + } + + this._settings.system.loggerOptions = { + logLevel: _logger.trace ? Msal.LogLevel.Trace : (_logger.debug ? Msal.LogLevel.Verbose : Msal.LogLevel.Warning), + loggerCallback: (level, message, containsPii) => { + if (containsPii) { + return; + } + if (level === Msal.LogLevel.Trace) { + _logger.log(LogLevel.Trace, message); + return; + } + + // We only have Debug/Trace, so anything above, we only log when Debug is enabled. + _logger.log(LogLevel.Debug, message); + return; + } + }; + + this._msalApplication = new Msal.PublicClientApplication(this._settings); + } + + async initialize(): Promise { + await this._msalApplication.initialize(); + } + + getAccount() { + if (this._account) { + return this._account; + } + + const accounts = this._msalApplication.getAllAccounts(); + if (accounts && accounts.length) { + return accounts[0]; + } + + return null; + } + + async getUser() { + const account = this.getAccount(); + if (!account) { + return; + } + + return account.idTokenClaims; + } + + async getAccessToken(request?: AccessTokenRequestOptions): Promise { + try { + this.trace('getAccessToken', request); + const newToken = await this.getTokenCore(request?.scopes); + return { + status: AccessTokenResultStatus.Success, + token: newToken + }; + } catch (e) { + return { + status: AccessTokenResultStatus.RequiresRedirect + }; + } + } + + async getTokenCore(scopes?: string[]): Promise { + const account = this.getAccount(); + if (!account) { + throw new Error('Failed to retrieve token, no account found.'); + } + + const silentRequest = { + redirectUri: this._settings.auth?.redirectUri, + account: account, + scopes: scopes || this._settings.defaultAccessTokenScopes + }; + + this.debug(`Provisioning a token silently for scopes '${silentRequest.scopes}'`) + this.trace('_msalApplication.acquireTokenSilent', silentRequest); + const response = await this._msalApplication.acquireTokenSilent(silentRequest); + this.trace('_msalApplication.acquireTokenSilent-response', response); + + if (response.scopes.length === 0 || response.accessToken === '') { + throw new Error('Scopes not granted.'); + } + + const result = { + value: response.accessToken, + grantedScopes: response.scopes, + expires: response.expiresOn + }; + + this.trace('getAccessToken-result', result); + + return result; + } + + async signIn(context: AuthenticationContext) { + this.trace('signIn', context); + try { + // Before we start any sign-in flow, clear out any previous state so that it doesn't pile up. + this.purgeState(); + + const { state, interactiveRequest } = context; + + if (interactiveRequest && interactiveRequest.interaction === 'GetToken') { + this.debug('Acquiring additional token.'); + const request: Msal.RedirectRequest = { + scopes: interactiveRequest.scopes || [], + state: this.saveState(context.state), + ...interactiveRequest.additionalRequestParameters + }; + this.trace('getInteractiveToken-Request', request); + await this._msalApplication.acquireTokenRedirect(request); + return this.success(state); + } else { + const request: Partial = { + redirectUri: this._settings.auth.redirectUri!, + state: this.saveState(context.state), + ...interactiveRequest?.additionalRequestParameters + }; + + request.scopes = request.scopes || this._settings.defaultAccessTokenScopes || []; + + const result = await this.signInCore(request); + this.trace('signIn-Response', result); + if (!result) { + return this.redirect(); + } else if (this.isMsalError(result)) { + return this.error(result.errorMessage); + } + + return this.success(state); + } + } catch (e) { + const message = (e as Error).message; + this.debug(`Sign in error '${message}'`); + return this.error(message); + } + } + + async signInCore(request: Partial): Promise { + this.trace('signIn-Request', request); + const loginMode = this._settings.loginMode.toLowerCase(); + if (loginMode === 'redirect') { + return this.signInWithRedirect(request as Msal.RedirectRequest); + } else { + return this.signInWithPopup(request as Msal.PopupRequest); + } + } + + private async signInWithRedirect(request: Msal.RedirectRequest) { + try { + this.debug('Starting sign-in redirect.'); + return await this._msalApplication.loginRedirect(request); + } catch (e) { + this.debug(`Sign-in redirect failed: '${(e as Error).message}'.`); + return e as any; + } + } + + private async signInWithPopup(request: Msal.PopupRequest) { + try { + this.debug('Starting sign-in pop-up'); + return await this._msalApplication.loginPopup(request); + } catch (e) { + // If the user explicitly cancelled the pop-up, avoid performing a redirect. + if (this.isMsalError(e) && e.errorCode !== Msal.BrowserAuthErrorCodes.userCancelled) { + this.signInWithRedirect(request); + } else { + this.debug(`Sign-in pop-up failed: '${(e as Error).message}'.`); + return e as any; + } + } + } + + async completeSignIn() { + // Make sure that the redirect handler has completed execution before + // completing sign in. + try { + this.debug('Completing sign-in redirect.'); + var authenticationResult = await this._redirectCallback; + this.trace('completeSignIn-result', authenticationResult); + if (authenticationResult) { + this.trace('completeSignIn-success', authenticationResult); + return authenticationResult; + } + this.debug('No authentication result.'); + return this.operationCompleted(); + } catch (e) { + this.debug(`completeSignIn-error:'${(e as Error).message}'`); + return this.error((e as Error).message); + } + } + + async signOut(context: AuthenticationContext) { + this.trace('signOut', context); + try { + // Before we start any sign-in flow, clear out any previous state so that it doesn't pile up. + this.purgeState(); + + const { state, interactiveRequest } = context; + + const request: Partial = { + postLogoutRedirectUri: this._settings.auth.postLogoutRedirectUri, + state: this.saveState(state), + ...interactiveRequest?.additionalRequestParameters + }; + this.trace('signOut-Request', request); + + await this._msalApplication.logoutRedirect(request); + + // We are about to be redirected. + return this.redirect(); + } catch (e) { + return this.error((e as Error).message); + } + } + + async completeSignOut(url: string) { + this.trace('completeSignOut-request', url); + try { + this.debug('Completing sign-out redirect.'); + var authenticationResult = await this._redirectCallback; + this.trace('completeSignOut-result', authenticationResult); + if (authenticationResult) { + this.trace('completeSignOut-success', authenticationResult); + return authenticationResult; + } + this.debug('No authentication result.'); + return this.operationCompleted(); + } catch (e) { + this.debug(`completeSignOut-error:'${(e as Error).message}'`); + return this.error((e as Error).message); + } + } + + // msal.js only allows a string as the account state and it simply attaches it to the sign-in request state. + // Given that we don't want to serialize the entire state and put it in the query string, we need to serialize the + // state ourselves and pass an identifier to retrieve it while in the callback flow. + saveState(state: T): string { + const identifier = window.crypto.randomUUID(); + sessionStorage.setItem(`${AuthenticationService._infrastructureKey}.AuthorizeService.${identifier}`, JSON.stringify(state)); + return identifier; + } + + retrieveState(url: string | null, providedState: string | null = null, isLogout: boolean = false): T | undefined { + let stateFromUrl; + // Parse the state key from the `search` query parameter in the URL if provided + if (url) { + const parsedUrl = new URL(url); + stateFromUrl = parsedUrl.searchParams && parsedUrl.searchParams.getAll('state'); + } + + // Chose the provided state from MSAL. Otherwise, choose the state computed from the URL + const state = providedState || stateFromUrl; + + if (!state) { + return undefined; + } + + const stateKey = `${AuthenticationService._infrastructureKey}.AuthorizeService.${state}`; + const stateString = sessionStorage.getItem(stateKey); + if (stateString) { + sessionStorage.removeItem(stateKey); + const savedState = JSON.parse(stateString); + return savedState; + } + + return undefined; + } + + purgeState() { + for (let i = 0; i < sessionStorage.length; i++) { + const key = sessionStorage.key(i); + if (key?.startsWith(AuthenticationService._infrastructureKey)) { + sessionStorage.removeItem(key); + } + } + } + + initializeMsalHandler() { + this._redirectCallback = this.completeAuthentication(); + } + + private async completeAuthentication() { + try { + const result = await this._msalApplication.handleRedirectPromise(); + const res = this.handleResult(result); + return res; + } catch (error) { + if (this.isMsalError(error)) { + return this.error(error.errorMessage); + } else { + return this.error((error as Error).message); + } + }; + } + + private handleResult(result: Msal.AuthenticationResult | null) { + const logoutState = this.retrieveState(location.href, undefined); + if (result) { + this._account = result.account; + return this.success(this.retrieveState(null, result.state)); + } else if (logoutState) { + return this.success(logoutState); + } else { + return this.operationCompleted(); + } + } + + private isMsalError(resultOrError: any): resultOrError is Msal.AuthError { + return resultOrError?.errorCode; + } + + private error(message: string) { + return { status: AuthenticationResultStatus.Failure, errorMessage: message }; + } + + private success(state: any) { + return { status: AuthenticationResultStatus.Success, state }; + } + + private redirect() { + return { status: AuthenticationResultStatus.Redirect }; + } + + private operationCompleted() { + return { status: AuthenticationResultStatus.OperationCompleted }; + } + + private debug(message: string) { + this._logger?.log(LogLevel.Debug, message); + } + + private trace(message: string, data: any) { + this._logger?.log(LogLevel.Trace, `${message}: ${JSON.stringify(data)}`); + } +} + +export class AuthenticationService { + + static _infrastructureKey = 'Microsoft.Authentication.WebAssembly.Msal'; + private static _initialization: Promise | undefined; + static instance: MsalAuthorizeService; + + public static async init(settings: AuthorizeServiceConfiguration, jsLoggingOptions: JavaScriptLoggingOptions) { + if (!AuthenticationService._initialization) { + const instance = new MsalAuthorizeService(settings, new Logger(jsLoggingOptions)); + AuthenticationService.instance = instance; + AuthenticationService._initialization = instance.initialize() + .then(() => instance.initializeMsalHandler()) + .catch(error => { + AuthenticationService._initialization = undefined; + throw error; + }); + } + return AuthenticationService._initialization; + } + + public static getUser() { + return AuthenticationService.instance.getUser(); + } + + public static getAccessToken(request: AccessTokenRequestOptions) { + return AuthenticationService.instance.getAccessToken(request); + } + + public static signIn(state: any) { + return AuthenticationService.instance.signIn(state); + } + + // url is not used in the msal.js implementation but we keep it here + // as it is part of the default RemoteAuthenticationService contract implementation. + // The unused parameter here just reflects that. + public static completeSignIn(url: string) { + return AuthenticationService.instance.completeSignIn(); + } + + public static signOut(state: any) { + return AuthenticationService.instance.signOut(state); + } + + public static completeSignOut(url: string) { + return AuthenticationService.instance.completeSignOut(url); + } +} + +declare global { + interface Window { AuthenticationService: AuthenticationService; } +} + +window.AuthenticationService = AuthenticationService; + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/case.source b/eng/skill-evals/review-pull-request/fixtures/case-04/case.source new file mode 100644 index 000000000000..c0e0d2cdd231 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/case.source @@ -0,0 +1,8 @@ +Repository: dotnet/aspnetcore +Pull request: https://github.com/dotnet/aspnetcore/pull/69721 +Head: 153f8ef684a760e30b43609e54a9d22027dc6b62 +Merge base: 66e2adb4e0297e445686cb7a70d6c9aa84dcf3af +Base tip: 66e2adb4e0297e445686cb7a70d6c9aa84dcf3af +The source files are excerpts, not a complete ready version-2 review bundle. +provenance.json maps every excerpt to its original source path and lines. +C1: The new RemoteMsalAuthenticationStartup token endpoint changes the observed result of NavigateDirectlyToLoginCallbackRestartsLoginWithoutInteropFailure because that browser scenario completes an exchange through this endpoint before its assertions. The concern is the asserted browser-test effect, not an independent endpoint policy claim. diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/change.diff b/eng/skill-evals/review-pull-request/fixtures/case-04/change.diff new file mode 100644 index 000000000000..7feba2a36173 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/change.diff @@ -0,0 +1,108 @@ +diff --git a/src/Components/test/testassets/Components.TestServer/RemoteMsalAuthenticationStartup.cs b/src/Components/test/testassets/Components.TestServer/RemoteMsalAuthenticationStartup.cs +new file mode 100644 +index 0000000000..6e4e181c18 +--- /dev/null ++++ b/src/Components/test/testassets/Components.TestServer/RemoteMsalAuthenticationStartup.cs +@@ -0,0 +1,102 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++using System.Globalization; ++using System.Reflection; ++using Components.TestServer.RazorComponents; ++using Microsoft.AspNetCore.Mvc; ++using Microsoft.IdentityModel.JsonWebTokens; ++using Microsoft.IdentityModel.Tokens; ++ ++namespace TestServer; ++ ++public class RemoteMsalAuthenticationStartup ++{ ++ public void ConfigureServices(IServiceCollection services) ++ { ++ services.AddRazorComponents() ++ .AddInteractiveWebAssemblyComponents(); ++ } ++ ++ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ++ { ++ app.Map("/subdir", app => ++ { ++ app.UseRouting(); ++ ++ app.UseAntiforgery(); ++ app.UseEndpoints(endpoints => ++ { ++ var contentRootStaticAssetsPath = Path.Combine(env.ContentRootPath, "Components.TestServer.staticwebassets.endpoints.json"); ++ if (File.Exists(contentRootStaticAssetsPath)) ++ { ++ endpoints.MapStaticAssets(contentRootStaticAssetsPath); ++ } ++ else ++ { ++ endpoints.MapStaticAssets(); ++ } ++ ++ endpoints.MapRazorComponents() ++ .AddAdditionalAssemblies(Assembly.Load("Components.WasmMsalRemoteAuthentication")) ++ .AddInteractiveWebAssemblyRenderMode(options => options.PathPrefix = "/WasmMsalRemoteAuthentication"); ++ ++ var oidcEndpoints = endpoints.MapGroup("oidc"); ++ ++ var issuer = ""; ++ oidcEndpoints.MapGet(".well-known/openid-configuration", (HttpRequest request, [FromHeader] string host) => ++ { ++ issuer = $"{(request.IsHttps ? "https" : "http")}://{host}"; ++ return Results.Json(new ++ { ++ issuer, ++ authorization_endpoint = $"{issuer}/subdir/oidc/authorize", ++ token_endpoint = $"{issuer}/subdir/oidc/token", ++ }); ++ }); ++ ++ var lastCode = ""; ++ var interactiveAuthorizationRequests = 0; ++ oidcEndpoints.MapGet("authorize", (string redirect_uri, string? state, string? prompt) => ++ { ++ if (prompt == "none") ++ { ++ return Results.Redirect($"{redirect_uri}?error=interaction_required&state={state}"); ++ } ++ ++ interactiveAuthorizationRequests++; ++ lastCode = Random.Shared.Next().ToString(CultureInfo.InvariantCulture); ++ return Results.Redirect($"{redirect_uri}?code={lastCode}&state={state}"); ++ }); ++ ++ oidcEndpoints.MapGet("interactive-authorization-requests", () => interactiveAuthorizationRequests); ++ ++ var jwtHandler = new JsonWebTokenHandler(); ++ oidcEndpoints.MapPost("token", ([FromForm] string code) => ++ { ++ if (string.IsNullOrEmpty(lastCode) && code != lastCode) ++ { ++ return Results.BadRequest("Bad code"); ++ } ++ ++ return Results.Json(new ++ { ++ token_type = "Bearer", ++ scope = "openid profile", ++ expires_in = 3600, ++ id_token = jwtHandler.CreateToken(new SecurityTokenDescriptor ++ { ++ Issuer = issuer, ++ Audience = "s6BhdRkqt3", ++ Claims = new Dictionary ++ { ++ ["sub"] = "248289761001", ++ ["name"] = "Jane Doe", ++ }, ++ }), ++ }); ++ }).DisableAntiforgery(); ++ }); ++ }); ++ } ++} diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/context.source b/eng/skill-evals/review-pull-request/fixtures/case-04/context.source new file mode 100644 index 000000000000..4aac59a38f84 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/context.source @@ -0,0 +1,164 @@ +=== head 153f8ef684a760e30b43609e54a9d22027dc6b62 src/Components/test/E2ETest/Tests/RemoteMsalAuthenticationTest.cs:1-37 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; +using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; +using Microsoft.AspNetCore.E2ETesting; +using OpenQA.Selenium; +using TestServer; +using Xunit.Abstractions; + +namespace Microsoft.AspNetCore.Components.E2ETest.Tests; + +public class RemoteMsalAuthenticationTest : + ServerTestBase> +{ + public RemoteMsalAuthenticationTest( + BrowserFixture browserFixture, + TrimmingServerFixture serverFixture, + ITestOutputHelper output) + : base(browserFixture, serverFixture, output) + { + } + + [Fact] + public void NavigateDirectlyToLoginCallbackRestartsLoginWithoutInteropFailure() + { + Navigate("/subdir/msal-authentication/login-callback"); + + Browser.True(() => (bool?)((IJavaScriptExecutor)Browser).ExecuteScript( + "return window.__msalSignInCalled") == true); + + var browserLog = Browser.Manage().Logs.GetLog(LogType.Browser); + Assert.DoesNotContain(browserLog, entry => entry.Message.Contains( + "The value 'AuthenticationService.isTopLevelWindow' is not a function.", + StringComparison.Ordinal)); + } +} + +=== head 153f8ef684a760e30b43609e54a9d22027dc6b62 src/Components/test/testassets/Components.TestServer/RazorComponents/RemoteMsalAuthenticationApp.razor:1-30 === + + + + + + + + + + + + + + + + + + + +=== head 153f8ef684a760e30b43609e54a9d22027dc6b62 src/Components/test/testassets/Components.WasmMsalRemoteAuthentication/Program.cs:1-31 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.AspNetCore.Components.WebAssembly.Hosting; + +var builder = WebAssemblyHostBuilder.CreateDefault(args); +var authorityBaseUriBuilder = new UriBuilder(builder.HostEnvironment.BaseAddress) +{ + Host = "localhost", + Path = "subdir/oidc", +}; + +builder.Services.AddMsalAuthentication(options => +{ + options.ProviderOptions.Authentication.Authority = authorityBaseUriBuilder.Uri.AbsoluteUri; + options.ProviderOptions.Authentication.ClientId = "s6BhdRkqt3"; + options.ProviderOptions.Authentication.RedirectUri = "msal-authentication/login-callback"; + options.ProviderOptions.Authentication.PostLogoutRedirectUri = "msal-authentication/logout-callback"; + options.ProviderOptions.LoginMode = "redirect"; + options.AuthenticationPaths.LogInPath = "msal-authentication/login"; + options.AuthenticationPaths.LogInCallbackPath = "msal-authentication/login-callback"; + options.AuthenticationPaths.LogInFailedPath = "msal-authentication/login-failed"; + options.AuthenticationPaths.LogOutPath = "msal-authentication/logout"; + options.AuthenticationPaths.LogOutCallbackPath = "msal-authentication/logout-callback"; + options.AuthenticationPaths.LogOutFailedPath = "msal-authentication/logout-failed"; + options.AuthenticationPaths.LogOutSucceededPath = "msal-authentication/logged-out"; + options.AuthenticationPaths.ProfilePath = "msal-authentication/profile"; + options.AuthenticationPaths.RegisterPath = "msal-authentication/register"; +}); + +await builder.Build().RunAsync(); + +=== head 153f8ef684a760e30b43609e54a9d22027dc6b62 src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts:472-484 === + public static async init(settings: AuthorizeServiceConfiguration, jsLoggingOptions: JavaScriptLoggingOptions) { + if (!AuthenticationService._initialization) { + const instance = new MsalAuthorizeService(settings, new Logger(jsLoggingOptions)); + AuthenticationService.instance = instance; + AuthenticationService._initialization = instance.initialize() + .then(() => instance.initializeMsalHandler()) + .catch(error => { + AuthenticationService._initialization = undefined; + throw error; + }); + } + return AuthenticationService._initialization; + } + +=== head 153f8ef684a760e30b43609e54a9d22027dc6b62 src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts:220-262 === + async signIn(context: AuthenticationContext) { + this.trace('signIn', context); + try { + // Before we start any sign-in flow, clear out any previous state so that it doesn't pile up. + this.purgeState(); + + const { state, interactiveRequest } = context; + + if (interactiveRequest && interactiveRequest.interaction === 'GetToken') { + this.debug('Acquiring additional token.'); + const request: Msal.RedirectRequest = { + scopes: interactiveRequest.scopes || [], + state: this.saveState(context.state), + ...interactiveRequest.additionalRequestParameters + }; + this.trace('getInteractiveToken-Request', request); + await this._msalApplication.acquireTokenRedirect(request); + return this.success(state); + } else { + const request: Partial = { + redirectUri: this._settings.auth.redirectUri!, + state: this.saveState(context.state), + ...interactiveRequest?.additionalRequestParameters + }; + + request.scopes = request.scopes || this._settings.defaultAccessTokenScopes || []; + + const result = await this.signInCore(request); + this.trace('signIn-Response', result); + if (!result) { + return this.redirect(); + } else if (this.isMsalError(result)) { + return this.error(result.errorMessage); + } + + return this.success(state); + } + } catch (e) { + const message = (e as Error).message; + this.debug(`Sign in error '${message}'`); + return this.error(message); + } + } + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/head.source b/eng/skill-evals/review-pull-request/fixtures/case-04/head.source new file mode 100644 index 000000000000..bd4b34cdb118 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/head.source @@ -0,0 +1,104 @@ +=== head 153f8ef684a760e30b43609e54a9d22027dc6b62 src/Components/test/testassets/Components.TestServer/RemoteMsalAuthenticationStartup.cs:1-102 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Globalization; +using System.Reflection; +using Components.TestServer.RazorComponents; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; + +namespace TestServer; + +public class RemoteMsalAuthenticationStartup +{ + public void ConfigureServices(IServiceCollection services) + { + services.AddRazorComponents() + .AddInteractiveWebAssemblyComponents(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.Map("/subdir", app => + { + app.UseRouting(); + + app.UseAntiforgery(); + app.UseEndpoints(endpoints => + { + var contentRootStaticAssetsPath = Path.Combine(env.ContentRootPath, "Components.TestServer.staticwebassets.endpoints.json"); + if (File.Exists(contentRootStaticAssetsPath)) + { + endpoints.MapStaticAssets(contentRootStaticAssetsPath); + } + else + { + endpoints.MapStaticAssets(); + } + + endpoints.MapRazorComponents() + .AddAdditionalAssemblies(Assembly.Load("Components.WasmMsalRemoteAuthentication")) + .AddInteractiveWebAssemblyRenderMode(options => options.PathPrefix = "/WasmMsalRemoteAuthentication"); + + var oidcEndpoints = endpoints.MapGroup("oidc"); + + var issuer = ""; + oidcEndpoints.MapGet(".well-known/openid-configuration", (HttpRequest request, [FromHeader] string host) => + { + issuer = $"{(request.IsHttps ? "https" : "http")}://{host}"; + return Results.Json(new + { + issuer, + authorization_endpoint = $"{issuer}/subdir/oidc/authorize", + token_endpoint = $"{issuer}/subdir/oidc/token", + }); + }); + + var lastCode = ""; + var interactiveAuthorizationRequests = 0; + oidcEndpoints.MapGet("authorize", (string redirect_uri, string? state, string? prompt) => + { + if (prompt == "none") + { + return Results.Redirect($"{redirect_uri}?error=interaction_required&state={state}"); + } + + interactiveAuthorizationRequests++; + lastCode = Random.Shared.Next().ToString(CultureInfo.InvariantCulture); + return Results.Redirect($"{redirect_uri}?code={lastCode}&state={state}"); + }); + + oidcEndpoints.MapGet("interactive-authorization-requests", () => interactiveAuthorizationRequests); + + var jwtHandler = new JsonWebTokenHandler(); + oidcEndpoints.MapPost("token", ([FromForm] string code) => + { + if (string.IsNullOrEmpty(lastCode) && code != lastCode) + { + return Results.BadRequest("Bad code"); + } + + return Results.Json(new + { + token_type = "Bearer", + scope = "openid profile", + expires_in = 3600, + id_token = jwtHandler.CreateToken(new SecurityTokenDescriptor + { + Issuer = issuer, + Audience = "s6BhdRkqt3", + Claims = new Dictionary + { + ["sub"] = "248289761001", + ["name"] = "Jane Doe", + }, + }), + }); + }).DisableAntiforgery(); + }); + }); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/mergeBase.source b/eng/skill-evals/review-pull-request/fixtures/case-04/mergeBase.source new file mode 100644 index 000000000000..3c3c0a87005c --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/mergeBase.source @@ -0,0 +1,109 @@ +=== mergeBase 66e2adb4e0297e445686cb7a70d6c9aa84dcf3af src/Components/test/testassets/Components.TestServer/RemoteAuthenticationStartup.cs:1-107 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Globalization; +using System.Reflection; +using Components.TestServer.RazorComponents; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; + +namespace TestServer; + +public class RemoteAuthenticationStartup +{ + public void ConfigureServices(IServiceCollection services) + { + services.AddRazorComponents() + .AddInteractiveWebAssemblyComponents(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.Map("/subdir", app => + { + app.UseRouting(); + + app.UseAntiforgery(); + app.UseEndpoints(endpoints => + { + var contentRootStaticAssetsPath = Path.Combine(env.ContentRootPath, "Components.TestServer.staticwebassets.endpoints.json"); + if (File.Exists(contentRootStaticAssetsPath)) + { + endpoints.MapStaticAssets(contentRootStaticAssetsPath); + } + else + { + endpoints.MapStaticAssets(); + } + + endpoints.MapRazorComponents() + .AddAdditionalAssemblies(Assembly.Load("Components.WasmRemoteAuthentication")) + .AddInteractiveWebAssemblyRenderMode(options => options.PathPrefix = "/WasmRemoteAuthentication"); + + var oidcEndpoints = endpoints.MapGroup("oidc"); + + // This is designed to test a single login at a time. + var issuer = ""; + oidcEndpoints.MapGet(".well-known/openid-configuration", (HttpRequest request, [FromHeader] string host) => + { + issuer = $"{(request.IsHttps ? "https" : "http")}://{host}"; + return Results.Json(new + { + issuer, + authorization_endpoint = $"{issuer}/subdir/oidc/authorize", + token_endpoint = $"{issuer}/subdir/oidc/token", + }); + }); + + var lastCode = ""; + oidcEndpoints.MapGet("authorize", (string redirect_uri, string? state, string? prompt, bool? preservedExtraQueryParams) => + { + // Require interaction so silent sign-in does not skip RedirectToLogin.razor. + if (prompt == "none") + { + return Results.Redirect($"{redirect_uri}?error=interaction_required&state={state}"); + } + + // Verify that the extra query parameters added by RedirectToLogin.razor are preserved. + if (preservedExtraQueryParams != true) + { + return Results.Redirect($"{redirect_uri}?error=invalid_request&error_description=extraQueryParams%20not%20preserved&state={state}"); + } + + lastCode = Random.Shared.Next().ToString(CultureInfo.InvariantCulture); + return Results.Redirect($"{redirect_uri}?code={lastCode}&state={state}"); + }); + + var jwtHandler = new JsonWebTokenHandler(); + oidcEndpoints.MapPost("token", ([FromForm] string code) => + { + if (string.IsNullOrEmpty(lastCode) && code != lastCode) + { + return Results.BadRequest("Bad code"); + } + + return Results.Json(new + { + token_type = "Bearer", + scope = "openid profile", + expires_in = 3600, + id_token = jwtHandler.CreateToken(new SecurityTokenDescriptor + { + Issuer = issuer, + Audience = "s6BhdRkqt3", + Claims = new Dictionary + { + ["sub"] = "248289761001", + ["name"] = "Jane Doe", + }, + }), + }); + }).DisableAntiforgery(); + }); + }); + } +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json new file mode 100644 index 000000000000..285509429ad1 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json @@ -0,0 +1,131 @@ +{ + "repository": "dotnet/aspnetcore", + "pullRequest": 69721, + "sourceRoles": { + "mergeBase": "66e2adb4e0297e445686cb7a70d6c9aa84dcf3af", + "head": "153f8ef684a760e30b43609e54a9d22027dc6b62", + "baseTip": "66e2adb4e0297e445686cb7a70d6c9aa84dcf3af" + }, + "files": [ + { + "file": "mergeBase.source", + "sha256": "bf3e50473d2061531eb249607c88b04e66e2fffd45233f89ebe2f0f3dc77a851", + "sources": [ + { + "role": "mergeBase", + "commit": "66e2adb4e0297e445686cb7a70d6c9aa84dcf3af", + "path": "src/Components/test/testassets/Components.TestServer/RemoteAuthenticationStartup.cs", + "blob": "e0ea4303ef8ed4915e575f8a1a28d4bd8d3cae31", + "ranges": [ + [ + 1, + 107 + ] + ] + } + ] + }, + { + "file": "head.source", + "sha256": "3035f16602cd1b9dded50443993ad5665076a44190f19edce62ef4da5adf716b", + "sources": [ + { + "role": "head", + "commit": "153f8ef684a760e30b43609e54a9d22027dc6b62", + "path": "src/Components/test/testassets/Components.TestServer/RemoteMsalAuthenticationStartup.cs", + "blob": "6e4e181c18555c54edc082c8f247636957a2adc6", + "ranges": [ + [ + 1, + 102 + ] + ] + } + ] + }, + { + "file": "baseTip.source", + "sha256": "ecaafa0098b41c0079385e460596f80f6825379340fc44d27d636c3d88633f56", + "sources": [ + { + "role": "baseTip", + "commit": "66e2adb4e0297e445686cb7a70d6c9aa84dcf3af", + "path": "src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts", + "blob": "9f921f557fff57c06052bf35ce550d2788ce451c", + "ranges": [ + [ + 1, + 515 + ] + ] + } + ] + }, + { + "file": "context.source", + "sha256": "aec831d5ab8146c1d8a2f67b1d62c0a70f7359b94161f225b929a0a0e1a01ffa", + "sources": [ + { + "role": "head", + "commit": "153f8ef684a760e30b43609e54a9d22027dc6b62", + "path": "src/Components/test/E2ETest/Tests/RemoteMsalAuthenticationTest.cs", + "blob": "cac01175d2486ef842a4c5093f9160ee8fa633a0", + "ranges": [ + [ + 1, + 37 + ] + ] + }, + { + "role": "head", + "commit": "153f8ef684a760e30b43609e54a9d22027dc6b62", + "path": "src/Components/test/testassets/Components.TestServer/RazorComponents/RemoteMsalAuthenticationApp.razor", + "blob": "d9ec11afcc97013f3f3b59c56d4172e72f55a426", + "ranges": [ + [ + 1, + 30 + ] + ] + }, + { + "role": "head", + "commit": "153f8ef684a760e30b43609e54a9d22027dc6b62", + "path": "src/Components/test/testassets/Components.WasmMsalRemoteAuthentication/Program.cs", + "blob": "6962660265d363fcac65712941520f375e9b9b4a", + "ranges": [ + [ + 1, + 31 + ] + ] + }, + { + "role": "head", + "commit": "153f8ef684a760e30b43609e54a9d22027dc6b62", + "path": "src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts", + "blob": "61da3cba0ebbb29922c1549c7567594a46daee67", + "ranges": [ + [ + 472, + 484 + ], + [ + 220, + 262 + ] + ] + } + ] + }, + { + "file": "change.diff", + "sha256": "07956bec2265b888b034c331638e353a762f9f6bd7001f60d773498d3d8b89cf" + }, + { + "file": "case.source", + "sha256": "43116be262a937b2c1d227222b1cb45d1023c3f23c3ce29b73947f512794a2da" + } + ] +} diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/baseTip.source b/eng/skill-evals/review-pull-request/fixtures/case-05/baseTip.source new file mode 100644 index 000000000000..cb0e32dbee4f --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/baseTip.source @@ -0,0 +1,160 @@ +=== baseTip 2a731a48bdbe8747100ce19282d8b96bb93b876e src/Components/Web.JS/src/Services/NavigationUtils.ts:1-158 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +import { WebRendererId } from '../Rendering/WebRendererId'; + +let interactiveRouterRendererId: WebRendererId | undefined = undefined; +let programmaticEnhancedNavigationHandler: typeof performProgrammaticEnhancedNavigation | undefined; +let enhancedNavigationListener: typeof notifyEnhancedNavigationListeners | undefined; + +/** + * Checks if a click event corresponds to an tag referencing a URL within the base href, and that interception + * isn't bypassed (e.g., by a 'download' attribute or the user holding a meta key while clicking). + * @param event The event that occurred + * @param callbackIfIntercepted A callback that will be invoked if the event corresponds to a click on an that can be intercepted. + */ +export function handleClickForNavigationInterception(event: MouseEvent, callbackIfIntercepted: (absoluteInternalHref: string) => void): void { + if (event.button !== 0 || eventHasSpecialKey(event)) { + // Don't stop ctrl/meta-click (etc) from opening links in new tabs/windows + return; + } + + if (event.defaultPrevented) { + return; + } + + // Intercept clicks on all elements where the href is within the URI space + // We must explicitly check if it has an 'href' attribute, because if it doesn't, the result might be null or an empty string depending on the browser + const anchorTarget = findAnchorTarget(event); + + if (anchorTarget && canProcessAnchor(anchorTarget)) { + const anchorHref = anchorTarget.getAttribute('href')!; + + const absoluteHref = toAbsoluteUri(anchorHref); + + if (isWithinBaseUriSpace(absoluteHref)) { + event.preventDefault(); + callbackIfIntercepted(absoluteHref); + } + } +} + +export function isWithinBaseUriSpace(href: string) { + const baseUriWithoutTrailingSlash = toBaseUriWithoutTrailingSlash(document.baseURI!); + const nextChar = href.charAt(baseUriWithoutTrailingSlash.length); + + return href.startsWith(baseUriWithoutTrailingSlash) + && (nextChar === '' || nextChar === '/' || nextChar === '?' || nextChar === '#'); +} + +export function isSamePageWithHash(oldUrl: string, newUrl: string): boolean { + const a = new URL(oldUrl); + const b = new URL(newUrl); + return a.origin === b.origin && a.pathname === b.pathname + && a.search === b.search && b.hash !== ''; +} + +export function isForSamePath(url1: string, url2: string) { + // We are going to use the scheme, host, port and path to determine if the two URLs are compatible. + // We do not account for the query string as we want to allow for the query string to change. + // (Blazor doesn't use the query string for routing purposes). + const parsedUrl1 = new URL(url1); + const parsedUrl2 = new URL(url2); + return parsedUrl1.protocol === parsedUrl2.protocol + && parsedUrl1.host === parsedUrl2.host + && parsedUrl1.port === parsedUrl2.port + && parsedUrl1.pathname === parsedUrl2.pathname; +} + +export function performScrollToElementOnTheSamePage(absoluteHref : string): void { + const hashIndex = absoluteHref.indexOf('#'); + if (hashIndex === absoluteHref.length - 1) { + return; + } + + const identifier = absoluteHref.substring(hashIndex + 1); + scrollToElement(identifier); +} + +export function scrollToElement(identifier: string): void { + document.getElementById(identifier)?.scrollIntoView(); +} + +export function attachEnhancedNavigationListener(listener: typeof enhancedNavigationListener) { + enhancedNavigationListener = listener; +} + +export function notifyEnhancedNavigationListeners(internalDestinationHref: string, interceptedLink: boolean) { + enhancedNavigationListener?.(internalDestinationHref, interceptedLink); +} + +export function hasProgrammaticEnhancedNavigationHandler(): boolean { + return programmaticEnhancedNavigationHandler !== undefined; +} + +export function attachProgrammaticEnhancedNavigationHandler(handler: typeof programmaticEnhancedNavigationHandler) { + programmaticEnhancedNavigationHandler = handler; +} + +export function performProgrammaticEnhancedNavigation(absoluteInternalHref: string, replace: boolean): void { + if (!programmaticEnhancedNavigationHandler) { + throw new Error('No enhanced programmatic navigation handler has been attached'); + } + + programmaticEnhancedNavigationHandler(absoluteInternalHref, replace); +} + +function toBaseUriWithoutTrailingSlash(baseUri: string) { + return baseUri.substring(0, baseUri.lastIndexOf('/')); +} + +let testAnchor: HTMLAnchorElement; +export function toAbsoluteUri(relativeUri: string): string { + testAnchor = testAnchor || document.createElement('a'); + testAnchor.href = relativeUri; + return testAnchor.href; +} + +function eventHasSpecialKey(event: MouseEvent) { + return event.ctrlKey || event.shiftKey || event.altKey || event.metaKey; +} + +function canProcessAnchor(anchorTarget: HTMLAnchorElement | SVGAElement) { + const targetAttributeValue = anchorTarget.getAttribute('target'); + const opensInSameFrame = !targetAttributeValue || targetAttributeValue === '_self'; + return opensInSameFrame && anchorTarget.hasAttribute('href') && !anchorTarget.hasAttribute('download'); +} + +function findAnchorTarget(event: MouseEvent): HTMLAnchorElement | SVGAElement | null { + const path = event.composedPath && event.composedPath(); + if (path) { + // This logic works with events that target elements within a shadow root, + // as long as the shadow mode is 'open'. For closed shadows, we can't possibly + // know what internal element was clicked. + for (let i = 0; i < path.length; i++) { + const candidate = path[i]; + if (candidate instanceof HTMLAnchorElement || candidate instanceof SVGAElement) { + return candidate; + } + } + } + return null; +} + +export function hasInteractiveRouter(): boolean { + return interactiveRouterRendererId !== undefined; +} + +export function getInteractiveRouterRendererId() : WebRendererId | undefined { + return interactiveRouterRendererId; +} + +export function setHasInteractiveRouter(rendererId: WebRendererId) { + if (interactiveRouterRendererId !== undefined && interactiveRouterRendererId !== rendererId) { + throw new Error('Only one interactive runtime may enable navigation interception at a time.'); + } + + interactiveRouterRendererId = rendererId; +} + diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/case.source b/eng/skill-evals/review-pull-request/fixtures/case-05/case.source new file mode 100644 index 000000000000..39049a02c31d --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/case.source @@ -0,0 +1,8 @@ +Repository: dotnet/aspnetcore +Pull request: https://github.com/dotnet/aspnetcore/pull/70299 +Head: 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 +Merge base: 2a731a48bdbe8747100ce19282d8b96bb93b876e +Base tip: 2a731a48bdbe8747100ce19282d8b96bb93b876e +The source files are excerpts, not a complete ready version-2 review bundle. +provenance.json maps every excerpt to its original source path and lines. +C1: After listener reordering, an unprevented anchor whose @onclick calls NavigationManager.NavigateTo can land on its href in Interactive WebAssembly but on the programmatic destination in Interactive Server. Is the different final navigation intended? diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/change.diff b/eng/skill-evals/review-pull-request/fixtures/case-05/change.diff new file mode 100644 index 000000000000..f62044083cb4 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/change.diff @@ -0,0 +1,83 @@ +diff --git a/src/Components/Web.JS/src/Services/NavigationEnhancement.ts b/src/Components/Web.JS/src/Services/NavigationEnhancement.ts +index 7bd29bee95..dd06e2cf5b 100644 +--- a/src/Components/Web.JS/src/Services/NavigationEnhancement.ts ++++ b/src/Components/Web.JS/src/Services/NavigationEnhancement.ts +@@ -4,6 +4,7 @@ + import { synchronizeDomContent } from '../Rendering/DomMerging/DomSync'; + import { attachProgrammaticEnhancedNavigationHandler, handleClickForNavigationInterception, hasInteractiveRouter, isForSamePath, notifyEnhancedNavigationListeners, performScrollToElementOnTheSamePage, isSamePageWithHash } from './NavigationUtils'; + import { scheduleScrollReset, ScrollResetSchedule } from '../Rendering/Renderer'; ++import { isDispatchingClick, setClickListenerRegisteredCallback } from '../Rendering/Events/EventDelegatorListeners'; + + /* + In effect, we have two separate client-side navigation mechanisms: +@@ -37,6 +38,8 @@ const acceptHeader = 'text/html; blazor-enhanced-nav=on'; + let currentEnhancedNavigationAbortController: AbortController | null; + let navigationEnhancementCallbacks: NavigationEnhancementCallbacks; + let performingEnhancedPageLoad: boolean; ++let clickListenerReorderPending = false; ++const capturedClickEvents = new Set(); + + // This gets initialized to the current URL when we load. + // After that, it gets updated every time we successfully complete a navigation. +@@ -59,6 +62,8 @@ export function hasNeverStartedAnyEnhancedPageLoad() { + + export function attachProgressivelyEnhancedNavigationListener(callbacks: NavigationEnhancementCallbacks) { + navigationEnhancementCallbacks = callbacks; ++ setClickListenerRegisteredCallback(onClickListenerRegistered); ++ window.addEventListener('click', onClickCapture, true); + document.addEventListener('click', onDocumentClick); + document.addEventListener('submit', onDocumentSubmit); + window.addEventListener('popstate', onPopState); +@@ -67,6 +72,10 @@ export function attachProgressivelyEnhancedNavigationListener(callbacks: Navigat + } + + export function detachProgressivelyEnhancedNavigationListener() { ++ setClickListenerRegisteredCallback(undefined); ++ clickListenerReorderPending = false; ++ window.removeEventListener('click', onClickCapture, true); ++ capturedClickEvents.clear(); + document.removeEventListener('click', onDocumentClick); + document.removeEventListener('submit', onDocumentSubmit); + window.removeEventListener('popstate', onPopState); +@@ -88,7 +97,41 @@ function performProgrammaticEnhancedNavigation(absoluteInternalHref: string, rep + performEnhancedPageLoad(absoluteInternalHref, /* interceptedLink */ false); + } + ++function onClickCapture(event: MouseEvent) { ++ // Window capture observes even native document listeners registered before Blazor starts. ++ capturedClickEvents.add(event); ++ // Microtasks can run between browser-invoked listeners, so release the event after the dispatch task. ++ setTimeout(() => capturedClickEvents.delete(event), 0); ++} ++ ++function isDispatchingBrowserClick(except?: MouseEvent): boolean { ++ for (const event of capturedClickEvents) { ++ if (event !== except && event.eventPhase !== Event.NONE) { ++ return true; ++ } ++ } ++ ++ return false; ++} ++ ++function onClickListenerRegistered(isDispatchingClick: boolean, currentClick?: MouseEvent) { ++ // Removing a listener during dispatch skips it for that click. Let it run before reordering. ++ if (isDispatchingClick || isDispatchingBrowserClick(currentClick)) { ++ clickListenerReorderPending = true; ++ return; ++ } ++ ++ clickListenerReorderPending = false; ++ document.removeEventListener('click', onDocumentClick); ++ document.addEventListener('click', onDocumentClick); ++} ++ + function onDocumentClick(event: MouseEvent) { ++ // A nested click must not remove this listener from an outer click's dispatch. ++ if (clickListenerReorderPending && !isDispatchingClick()) { ++ onClickListenerRegistered(false, event); ++ } ++ + if (hasInteractiveRouter()) { + return; + } diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/context.source b/eng/skill-evals/review-pull-request/fixtures/case-05/context.source new file mode 100644 index 000000000000..06958e3203c0 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/context.source @@ -0,0 +1,87 @@ +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/test/testassets/TestContentPackage/InteractiveNavigationComponent.razor:1-41 === +@inject NavigationManager Navigation + + +Navigate with an unprevented link +Navigate with a prevented link + +
+ +
+ +
+ +
+ + +@code { + private void NavigateToAnotherPage() + { + Navigation.NavigateTo("nav"); + } + + private void RefreshWithNavigateTo() + { + Navigation.NavigateTo(Navigation.Uri, replace: true); + } + + private void ReloadWithNavigateTo() + { + Navigation.NavigateTo(Navigation.Uri, forceLoad: true, replace: true); + } + + private void RefreshWithRefresh() + { + Navigation.Refresh(); + } + + private void ReloadWithRefresh() + { + Navigation.Refresh(forceReload: true); + } +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Rendering/Events/EventDelegatorListeners.ts:1-33 === +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +let clickListenerRegisteredCallback: ((isDispatchingClick: boolean) => void) | undefined; +let clickDispatchDepth = 0; + +export function setClickListenerRegisteredCallback(callback: typeof clickListenerRegisteredCallback): void { + clickListenerRegisteredCallback = callback; +} + +export function isDispatchingClick(): boolean { + return clickDispatchDepth > 0; +} + +export function notifyGlobalListenerAdded(eventName: string): void { + if (eventName === 'click') { + clickListenerRegisteredCallback?.(clickDispatchDepth > 0); + } +} + +export function dispatchGlobalEvent(event: Event, listener: EventListener): void { + if (event.type !== 'click') { + listener(event); + return; + } + + clickDispatchDepth++; + try { + listener(event); + } finally { + clickDispatchDepth--; + } +} + + +=== Existing feedback discussion_r4487936812 at commit 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 === +**[P2] [QUESTION] Confirm whether `` with `@onclick` calling `NavigateTo` (without `@onclick:preventDefault`) should differ between Interactive WebAssembly and Interactive Server** + +Because `onDocumentClick` is now moved after the renderer's click delegate, consider a link such as `` (without `@onclick:preventDefault`) on a page where enhanced navigation is active: +- **Before this PR:** `onDocumentClick` ran first (`/other`), and then the `@onclick` handler's `Nav.NavigateTo("/counter")` ran second and won in both Interactive WebAssembly and Interactive Server (landing on `/counter`). +- **With this PR:** In Interactive WebAssembly, `@onclick` runs synchronously during the click event and starts programmatic enhanced navigation to `/counter`, and then `onDocumentClick` runs second on the un-prevented ``, aborting `/counter` (`NavigationEnhancement.ts:226`) and landing on `/other` (matching native browser order where an un-prevented link's default action runs after click handlers). However, in Interactive Server, `@onclick` runs asynchronously over SignalR after `onDocumentClick`, so `/counter` still wins. + +Is this Interactive WebAssembly (`/other`) vs. Interactive Server (`/counter`) difference intended when `@onclick` calls `NavigateTo` without `@onclick:preventDefault` (for example under `InteractiveAuto`), or should programmatic enhanced navigation initiated during the click take precedence? diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/head.source b/eng/skill-evals/review-pull-request/fixtures/case-05/head.source new file mode 100644 index 000000000000..8dc71d74ba59 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/head.source @@ -0,0 +1,122 @@ +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:63-72 === +export function attachProgressivelyEnhancedNavigationListener(callbacks: NavigationEnhancementCallbacks) { + navigationEnhancementCallbacks = callbacks; + setClickListenerRegisteredCallback(onClickListenerRegistered); + window.addEventListener('click', onClickCapture, true); + document.addEventListener('click', onDocumentClick); + document.addEventListener('submit', onDocumentSubmit); + window.addEventListener('popstate', onPopState); + + attachProgrammaticEnhancedNavigationHandler(performProgrammaticEnhancedNavigation); +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:84-98 === +function performProgrammaticEnhancedNavigation(absoluteInternalHref: string, replace: boolean) : void { + const originalLocation = location.href; + + if (replace) { + history.replaceState(null, /* ignored title */ '', absoluteInternalHref); + } else { + history.pushState(null, /* ignored title */ '', absoluteInternalHref); + } + + if (!isForSamePath(absoluteInternalHref, originalLocation)) { + scheduleScrollReset(ScrollResetSchedule.AfterDocumentUpdate); + } + + performEnhancedPageLoad(absoluteInternalHref, /* interceptedLink */ false); +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:129-159 === +function onDocumentClick(event: MouseEvent) { + // A nested click must not remove this listener from an outer click's dispatch. + if (clickListenerReorderPending && !isDispatchingClick()) { + onClickListenerRegistered(false, event); + } + + if (hasInteractiveRouter()) { + return; + } + + if (event.target instanceof Element && !enhancedNavigationIsEnabledForElement(event.target)) { + return; + } + + handleClickForNavigationInterception(event, absoluteInternalHref => { + const originalLocation = location.href; + + const shouldScrollToHash = isSamePageWithHash(originalLocation, absoluteInternalHref); + history.pushState(null, /* ignored title */ '', absoluteInternalHref); + + if (shouldScrollToHash) { + performScrollToElementOnTheSamePage(absoluteInternalHref); + } else { + const isSelfNavigation = isForSamePath(absoluteInternalHref, originalLocation); + performEnhancedPageLoad(absoluteInternalHref, /* interceptedLink */ true); + if (!isSelfNavigation) { + scheduleScrollReset(ScrollResetSchedule.AfterDocumentUpdate); + } + } + }); +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:100-105 === +function onClickCapture(event: MouseEvent) { + // Window capture observes even native document listeners registered before Blazor starts. + capturedClickEvents.add(event); + // Microtasks can run between browser-invoked listeners, so release the event after the dispatch task. + setTimeout(() => capturedClickEvents.delete(event), 0); +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:107-115 === +function isDispatchingBrowserClick(except?: MouseEvent): boolean { + for (const event of capturedClickEvents) { + if (event !== except && event.eventPhase !== Event.NONE) { + return true; + } + } + + return false; +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:117-127 === +function onClickListenerRegistered(isDispatchingClick: boolean, currentClick?: MouseEvent) { + // Removing a listener during dispatch skips it for that click. Let it run before reordering. + if (isDispatchingClick || isDispatchingBrowserClick(currentClick)) { + clickListenerReorderPending = true; + return; + } + + clickListenerReorderPending = false; + document.removeEventListener('click', onDocumentClick); + document.addEventListener('click', onDocumentClick); +} + +=== head 0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6 src/Components/Web.JS/src/Services/NavigationEnhancement.ts:243-269 === +export async function performEnhancedPageLoad(internalDestinationHref: string, interceptedLink: boolean, fetchOptions?: RequestInit, treatAsRedirectionFromMethod?: 'get' | 'post', changeUrl = true) { + performingEnhancedPageLoad = true; + + // First, stop any preceding enhanced page load + currentEnhancedNavigationAbortController?.abort(); + + // Notify any interactive runtimes that an enhanced navigation is starting + notifyEnhancedNavigationListeners(internalDestinationHref, interceptedLink); + + // Notify handlers that enhanced navigation is starting + navigationEnhancementCallbacks.enhancedNavigationStarted(); + + // Now request the new page via fetch, and a special header that tells the server we want it to inject + // framing boundaries to distinguish the initial document and each subsequent streaming SSR update. + currentEnhancedNavigationAbortController = new AbortController(); + const abortSignal = currentEnhancedNavigationAbortController.signal; + const responsePromise = fetch(internalDestinationHref, Object.assign({ + signal: abortSignal, + mode: 'no-cors', // If there's a redirection to an external origin, even if it enables CORS, we don't want to receive its content and patch it into our DOM on this origin + headers: { + // Because of no-cors, we can only send CORS-safelisted headers, so communicate the info about + // enhanced nav as a MIME type parameter + 'accept': acceptHeader, + }, + }, fetchOptions)); + let isNonRedirectedPostToADifferentUrlMessage: string | null = null; + await getResponsePartsWithFraming( diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/mergeBase.source b/eng/skill-evals/review-pull-request/fixtures/case-05/mergeBase.source new file mode 100644 index 000000000000..26e2c9001c9e --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/mergeBase.source @@ -0,0 +1,83 @@ +=== mergeBase 2a731a48bdbe8747100ce19282d8b96bb93b876e src/Components/Web.JS/src/Services/NavigationEnhancement.ts:60-67 === +export function attachProgressivelyEnhancedNavigationListener(callbacks: NavigationEnhancementCallbacks) { + navigationEnhancementCallbacks = callbacks; + document.addEventListener('click', onDocumentClick); + document.addEventListener('submit', onDocumentSubmit); + window.addEventListener('popstate', onPopState); + + attachProgrammaticEnhancedNavigationHandler(performProgrammaticEnhancedNavigation); +} + +=== mergeBase 2a731a48bdbe8747100ce19282d8b96bb93b876e src/Components/Web.JS/src/Services/NavigationEnhancement.ts:75-89 === +function performProgrammaticEnhancedNavigation(absoluteInternalHref: string, replace: boolean) : void { + const originalLocation = location.href; + + if (replace) { + history.replaceState(null, /* ignored title */ '', absoluteInternalHref); + } else { + history.pushState(null, /* ignored title */ '', absoluteInternalHref); + } + + if (!isForSamePath(absoluteInternalHref, originalLocation)) { + scheduleScrollReset(ScrollResetSchedule.AfterDocumentUpdate); + } + + performEnhancedPageLoad(absoluteInternalHref, /* interceptedLink */ false); +} + +=== mergeBase 2a731a48bdbe8747100ce19282d8b96bb93b876e src/Components/Web.JS/src/Services/NavigationEnhancement.ts:91-116 === +function onDocumentClick(event: MouseEvent) { + if (hasInteractiveRouter()) { + return; + } + + if (event.target instanceof Element && !enhancedNavigationIsEnabledForElement(event.target)) { + return; + } + + handleClickForNavigationInterception(event, absoluteInternalHref => { + const originalLocation = location.href; + + const shouldScrollToHash = isSamePageWithHash(originalLocation, absoluteInternalHref); + history.pushState(null, /* ignored title */ '', absoluteInternalHref); + + if (shouldScrollToHash) { + performScrollToElementOnTheSamePage(absoluteInternalHref); + } else { + const isSelfNavigation = isForSamePath(absoluteInternalHref, originalLocation); + performEnhancedPageLoad(absoluteInternalHref, /* interceptedLink */ true); + if (!isSelfNavigation) { + scheduleScrollReset(ScrollResetSchedule.AfterDocumentUpdate); + } + } + }); +} + +=== mergeBase 2a731a48bdbe8747100ce19282d8b96bb93b876e src/Components/Web.JS/src/Services/NavigationEnhancement.ts:200-226 === +export async function performEnhancedPageLoad(internalDestinationHref: string, interceptedLink: boolean, fetchOptions?: RequestInit, treatAsRedirectionFromMethod?: 'get' | 'post', changeUrl = true) { + performingEnhancedPageLoad = true; + + // First, stop any preceding enhanced page load + currentEnhancedNavigationAbortController?.abort(); + + // Notify any interactive runtimes that an enhanced navigation is starting + notifyEnhancedNavigationListeners(internalDestinationHref, interceptedLink); + + // Notify handlers that enhanced navigation is starting + navigationEnhancementCallbacks.enhancedNavigationStarted(); + + // Now request the new page via fetch, and a special header that tells the server we want it to inject + // framing boundaries to distinguish the initial document and each subsequent streaming SSR update. + currentEnhancedNavigationAbortController = new AbortController(); + const abortSignal = currentEnhancedNavigationAbortController.signal; + const responsePromise = fetch(internalDestinationHref, Object.assign({ + signal: abortSignal, + mode: 'no-cors', // If there's a redirection to an external origin, even if it enables CORS, we don't want to receive its content and patch it into our DOM on this origin + headers: { + // Because of no-cors, we can only send CORS-safelisted headers, so communicate the info about + // enhanced nav as a MIME type parameter + 'accept': acceptHeader, + }, + }, fetchOptions)); + let isNonRedirectedPostToADifferentUrlMessage: string | null = null; + await getResponsePartsWithFraming( diff --git a/eng/skill-evals/review-pull-request/fixtures/case-05/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-05/provenance.json new file mode 100644 index 000000000000..32289e60edb5 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-05/provenance.json @@ -0,0 +1,145 @@ +{ + "repository": "dotnet/aspnetcore", + "pullRequest": 70299, + "sourceRoles": { + "mergeBase": "2a731a48bdbe8747100ce19282d8b96bb93b876e", + "head": "0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6", + "baseTip": "2a731a48bdbe8747100ce19282d8b96bb93b876e" + }, + "files": [ + { + "file": "mergeBase.source", + "sha256": "19d83bf27940b4b66a5957ce363efd9c17c1d4757788b77891aa708cc5c01574", + "sources": [ + { + "role": "mergeBase", + "commit": "2a731a48bdbe8747100ce19282d8b96bb93b876e", + "path": "src/Components/Web.JS/src/Services/NavigationEnhancement.ts", + "blob": "7bd29bee95bb154787994017aceb0d29960ebebb", + "ranges": [ + [ + 60, + 67 + ], + [ + 75, + 89 + ], + [ + 91, + 116 + ], + [ + 200, + 226 + ] + ] + } + ] + }, + { + "file": "head.source", + "sha256": "2d34778b27f6c9fab6ae76e225d9bc1bd335b5422d54a6f94f0bb2c0ee4e25d0", + "sources": [ + { + "role": "head", + "commit": "0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6", + "path": "src/Components/Web.JS/src/Services/NavigationEnhancement.ts", + "blob": "dd06e2cf5beb414f8760fabfe97424414a032220", + "ranges": [ + [ + 63, + 72 + ], + [ + 84, + 98 + ], + [ + 129, + 159 + ], + [ + 100, + 105 + ], + [ + 107, + 115 + ], + [ + 117, + 127 + ], + [ + 243, + 269 + ] + ] + } + ] + }, + { + "file": "baseTip.source", + "sha256": "5eac5e1629c5d668ca00cd19a8e9ee49f11393e210323de6f78d97e274ac4d3a", + "sources": [ + { + "role": "baseTip", + "commit": "2a731a48bdbe8747100ce19282d8b96bb93b876e", + "path": "src/Components/Web.JS/src/Services/NavigationUtils.ts", + "blob": "9976eafc898cdc52039a75029da0c8dcfcdb6fb0", + "ranges": [ + [ + 1, + 158 + ] + ] + } + ] + }, + { + "file": "context.source", + "sha256": "f8f95a6e4bf3d5556b291e3294f880939669309ed03a29bc8dd0c6261bc58aaa", + "sources": [ + { + "role": "head", + "commit": "0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6", + "path": "src/Components/test/testassets/TestContentPackage/InteractiveNavigationComponent.razor", + "blob": "71217ca2ee717f7a6e9abd1adb7df6369413f2c1", + "ranges": [ + [ + 1, + 41 + ] + ] + }, + { + "role": "head", + "commit": "0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6", + "path": "src/Components/Web.JS/src/Rendering/Events/EventDelegatorListeners.ts", + "blob": "6b3737d7c0fecb9b8ae6805fe9744cb149e4c04e", + "ranges": [ + [ + 1, + 33 + ] + ] + } + ], + "feedback": { + "url": "https://github.com/dotnet/aspnetcore/pull/70299#discussion_r4487936812", + "commit": "0317f5f729136a3a4f7320ab8bff3aa7d66fe5d6", + "updatedAt": "2026-11-06T01:08:38Z", + "role": "frozen existing feedback, not a target contract or runtime trace" + } + }, + { + "file": "change.diff", + "sha256": "eb4815b07d61137eead6c4526cafa73e5c352547fe00acb53297b9c4b419e5e9" + }, + { + "file": "case.source", + "sha256": "7e72e1a5ecbfcc32c1be9ac2bbdd3bc2a66291542ab2baef7dca26efa02f122a" + } + ] +} diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/Dependencies.cs.source b/eng/skill-evals/review-pull-request/fixtures/case-06/baseTip.source similarity index 100% rename from eng/skill-evals/review-pull-request/fixtures/catch-policy/Dependencies.cs.source rename to eng/skill-evals/review-pull-request/fixtures/case-06/baseTip.source diff --git a/eng/skill-evals/review-pull-request/fixtures/case-06/case.source b/eng/skill-evals/review-pull-request/fixtures/case-06/case.source new file mode 100644 index 000000000000..bf9bd1ffa2c6 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-06/case.source @@ -0,0 +1 @@ +C1: The added inner catch prevents a diagnostic sink failure from reaching the caller of SendMessageAsync. Remove the inner catch so the sink exception propagates. diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngine.diff b/eng/skill-evals/review-pull-request/fixtures/case-06/change.diff similarity index 100% rename from eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngine.diff rename to eng/skill-evals/review-pull-request/fixtures/case-06/change.diff index 9523a4649cd3..20f237e3708c 100644 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngine.diff +++ b/eng/skill-evals/review-pull-request/fixtures/case-06/change.diff @@ -5,6 +5,7 @@ diff --git a/ConversationEngine.cs.source b/ConversationEngine.cs.source { Error = processingError; Status = "Error"; + StatusChanged?.Invoke(Status); + try + { + _sink.Write(processingError); @@ -12,6 +13,5 @@ diff --git a/ConversationEngine.cs.source b/ConversationEngine.cs.source + catch (Exception) + { + } - StatusChanged?.Invoke(Status); return; } diff --git a/eng/skill-evals/review-pull-request/fixtures/case-06/context.source b/eng/skill-evals/review-pull-request/fixtures/case-06/context.source new file mode 100644 index 000000000000..8418afe3187b --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-06/context.source @@ -0,0 +1,40 @@ +Selected scenario +Construct ConversationEngine with FailingClient and ThrowingDiagnosticSink. +Register StatusObserver.OnStatusChanged, then await SendMessageAsync. +These are the only implementations in scope for this bounded scenario. + +Originating issue +Report conversation-processing failures through the configured diagnostic sink. + +Target-base contract +Processing failures are exposed in Error and the Error status; notify status observers. + +PR rationale and test +The author says the nested catch preserves successful task completion. +A new test awaits SendMessageAsync and asserts that Error is the client's Failure. +Its complete implementation follows below. + +Existing feedback +None. + +using System.Threading.Tasks; +using Xunit; + +public class ConversationEngineTests +{ + [Fact] + public async Task ProcessingFailureIsExposed() + { + var client = new FailingClient(); + var sink = new ThrowingDiagnosticSink(); + var observer = new StatusObserver(); + var engine = new ConversationEngine(client, sink); + engine.StatusChanged += observer.OnStatusChanged; + + await engine.SendMessageAsync(); + + Assert.Same(client.Failure, engine.Error); + Assert.Equal("Error", engine.Status); + Assert.Equal(1, observer.NotificationCount); + } +} diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/head/ConversationEngine.cs.source b/eng/skill-evals/review-pull-request/fixtures/case-06/head.source similarity index 100% rename from eng/skill-evals/review-pull-request/fixtures/catch-policy/head/ConversationEngine.cs.source rename to eng/skill-evals/review-pull-request/fixtures/case-06/head.source index 4330356e319a..e8d30b309c04 100644 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/head/ConversationEngine.cs.source +++ b/eng/skill-evals/review-pull-request/fixtures/case-06/head.source @@ -26,6 +26,7 @@ public sealed class ConversationEngine { Error = processingError; Status = "Error"; + StatusChanged?.Invoke(Status); try { _sink.Write(processingError); @@ -33,7 +34,6 @@ public sealed class ConversationEngine catch (Exception) { } - StatusChanged?.Invoke(Status); return; } } diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/old/ConversationEngine.cs.source b/eng/skill-evals/review-pull-request/fixtures/case-06/mergeBase.source similarity index 100% rename from eng/skill-evals/review-pull-request/fixtures/catch-policy/old/ConversationEngine.cs.source rename to eng/skill-evals/review-pull-request/fixtures/case-06/mergeBase.source diff --git a/eng/skill-evals/review-pull-request/fixtures/case-06/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-06/provenance.json new file mode 100644 index 000000000000..0105c8582c94 --- /dev/null +++ b/eng/skill-evals/review-pull-request/fixtures/case-06/provenance.json @@ -0,0 +1,36 @@ +{ + "repository": "dotnet/aspnetcore", + "pullRequest": 70312, + "fixtureKind": "synthetic public catch-policy example, not framework production source", + "revision": "4bb1a49fbbf7c217286f289cf975019491c83f16", + "transformations": [ + "Normalize scenario prompt to the single-candidate format.", + "Combine scenario and head test as context." + ], + "files": [ + { + "file": "mergeBase.source", + "sha256": "a41b5ee85d9f19c0b1002d988efe4adf5c479acba95e000f453dba7bcc715bb3" + }, + { + "file": "head.source", + "sha256": "6d6ba76ae43c4cb27de0c6579f5532c174b40d87de929717da0f6c2120631b24" + }, + { + "file": "baseTip.source", + "sha256": "e1621fa56245d23a6d234585cfc2da3f54dd148ee9a7ec2c7689000373b0046c" + }, + { + "file": "context.source", + "sha256": "3ad5fafd5ac86b76d82480d12cf889a520631431276567fb1bb45f069944b90b" + }, + { + "file": "change.diff", + "sha256": "fd8229c834dda082f4f4ae0dbd9d799c7c819df5b469ed2476e89f662fed840c" + }, + { + "file": "case.source", + "sha256": "71d7ca9d0dae95d9bba4e689d8979e1784db68c85a5bfcb65d82403e8f9d7ddd" + } + ] +} diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngineTests.cs.source b/eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngineTests.cs.source deleted file mode 100644 index 43fb5be02639..000000000000 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/ConversationEngineTests.cs.source +++ /dev/null @@ -1,21 +0,0 @@ -using System.Threading.Tasks; -using Xunit; - -public class ConversationEngineTests -{ - [Fact] - public async Task ProcessingFailureIsExposed() - { - var client = new FailingClient(); - var sink = new ThrowingDiagnosticSink(); - var observer = new StatusObserver(); - var engine = new ConversationEngine(client, sink); - engine.StatusChanged += observer.OnStatusChanged; - - await engine.SendMessageAsync(); - - Assert.Same(client.Failure, engine.Error); - Assert.Equal("Error", engine.Status); - Assert.Equal(1, observer.NotificationCount); - } -} diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/best-effort.txt b/eng/skill-evals/review-pull-request/fixtures/catch-policy/best-effort.txt deleted file mode 100644 index 9810331939f3..000000000000 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/best-effort.txt +++ /dev/null @@ -1,20 +0,0 @@ -Selected scenario -Construct ConversationEngine with FailingClient and ThrowingDiagnosticSink. -Register StatusObserver.OnStatusChanged, then await SendMessageAsync. -These are the only implementations in scope for this bounded scenario. - -Originating issue -Report conversation-processing failures through the configured diagnostic sink. - -Target-base contract -Processing failures are exposed in Error and the Error status. -Error reporting is best-effort: suppress diagnostic sink failures, preserve the -processing failure in Error, notify status observers, and complete the task normally. - -PR rationale and test -The author says the nested catch preserves successful task completion. -A new test awaits SendMessageAsync and asserts that Error is the client's Failure. -Its complete implementation is in ConversationEngineTests.cs.source. - -Existing feedback -None. diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/existing-question.txt b/eng/skill-evals/review-pull-request/fixtures/catch-policy/existing-question.txt deleted file mode 100644 index 5fe17f7e0a42..000000000000 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/existing-question.txt +++ /dev/null @@ -1,23 +0,0 @@ -Selected scenario -Construct ConversationEngine with FailingClient and ThrowingDiagnosticSink. -Register StatusObserver.OnStatusChanged, then await SendMessageAsync. -These are the only implementations in scope for this bounded scenario. - -Originating issue -Report conversation-processing failures through the configured diagnostic sink. - -Target-base contract -Processing failures are exposed in Error and the Error status; notify status observers. -No target-base policy specifies whether diagnostic sink failures must propagate or -be suppressed. No additional primary contract evidence is available. - -PR rationale and test -The author says the nested catch preserves successful task completion. -A new test awaits SendMessageAsync and asserts that Error is the client's Failure. -Its complete implementation is in ConversationEngineTests.cs.source. - -Existing feedback -Thread feedback-17, on the newly added inner catch in ConversationEngine.cs: -"This empty handler swallows any exception thrown by the diagnostic sink, so the -caller never observes a sink failure. Should sink failures propagate instead?" -No reply or resolution is available. diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/nonthrowing.txt b/eng/skill-evals/review-pull-request/fixtures/catch-policy/nonthrowing.txt deleted file mode 100644 index ef162676fe48..000000000000 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/nonthrowing.txt +++ /dev/null @@ -1,24 +0,0 @@ -Selected scenario -Construct ConversationEngine with FailingClient and RecordingDiagnosticSink. -Register StatusObserver.OnStatusChanged, then await SendMessageAsync. -These are the only implementations in scope for this bounded scenario. -ThrowingDiagnosticSink is not registered, selected, or called in this scenario. - -Originating issue -Report conversation-processing failures through the configured diagnostic sink. - -Target-base contract -Processing failures are exposed in Error and the Error status. -If the configured diagnostic sink fails during error reporting, the returned task -must fault with that sink failure. This applies to newly introduced reporting call -sites as well as existing ones. - -PR rationale and test -The author says the nested catch preserves successful task completion. -A new test awaits SendMessageAsync and asserts that Error is the client's Failure. -Its complete implementation is in ConversationEngineTests.cs.source. That separate -test configures ThrowingDiagnosticSink, not the RecordingDiagnosticSink selected -above. It is not evidence that the throwing sink is selected in this scenario. - -Existing feedback -None. diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/propagation.txt b/eng/skill-evals/review-pull-request/fixtures/catch-policy/propagation.txt deleted file mode 100644 index ea905f90c5a1..000000000000 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/propagation.txt +++ /dev/null @@ -1,21 +0,0 @@ -Selected scenario -Construct ConversationEngine with FailingClient and ThrowingDiagnosticSink. -Register StatusObserver.OnStatusChanged, then await SendMessageAsync. -These are the only implementations in scope for this bounded scenario. - -Originating issue -Report conversation-processing failures through the configured diagnostic sink. - -Target-base contract -Processing failures are exposed in Error and the Error status. -If the configured diagnostic sink fails during error reporting, the returned task -must fault with that sink failure. This applies to newly introduced reporting call -sites as well as existing ones. - -PR rationale and test -The author says the nested catch preserves successful task completion. -A new test awaits SendMessageAsync and asserts that Error is the client's Failure. -Its complete implementation is in ConversationEngineTests.cs.source. - -Existing feedback -None. diff --git a/eng/skill-evals/review-pull-request/fixtures/catch-policy/unspecified.txt b/eng/skill-evals/review-pull-request/fixtures/catch-policy/unspecified.txt deleted file mode 100644 index 253934caaa5f..000000000000 --- a/eng/skill-evals/review-pull-request/fixtures/catch-policy/unspecified.txt +++ /dev/null @@ -1,20 +0,0 @@ -Selected scenario -Construct ConversationEngine with FailingClient and ThrowingDiagnosticSink. -Register StatusObserver.OnStatusChanged, then await SendMessageAsync. -These are the only implementations in scope for this bounded scenario. - -Originating issue -Report conversation-processing failures through the configured diagnostic sink. - -Target-base contract -Processing failures are exposed in Error and the Error status; notify status observers. -No target-base policy specifies whether diagnostic sink failures must propagate or -be suppressed. No additional primary contract evidence is available. - -PR rationale and test -The author says the nested catch preserves successful task completion. -A new test awaits SendMessageAsync and asserts that Error is the client's Failure. -Its complete implementation is in ConversationEngineTests.cs.source. - -Existing feedback -None. diff --git a/eng/skill-evals/test_review_fixtures.ps1 b/eng/skill-evals/test_review_fixtures.ps1 index f2d347a51314..aa7b523e2158 100644 --- a/eng/skill-evals/test_review_fixtures.ps1 +++ b/eng/skill-evals/test_review_fixtures.ps1 @@ -3,9 +3,18 @@ $ErrorActionPreference = 'Stop' Set-StrictMode -Version 3 -$componentRoot = (Resolve-Path (Join-Path $PSScriptRoot 'review-candidate-verifier')).Path -$repoRoot = (Resolve-Path (Join-Path $componentRoot '../../..')).Path +$suiteRoot = (Resolve-Path (Join-Path $PSScriptRoot 'review-pull-request')).Path +$specPath = Join-Path $suiteRoot 'eval.vally.yaml' +$json = Get-Content $specPath -Raw | & npx ` + --yes ` + --registry=https://packagefeedproxy.microsoft.io/npm/ ` + 'yaml@2.9.1' --json --single --strict +if ($LASTEXITCODE -ne 0) { + throw 'Could not parse the review fixture specification.' +} +$spec = $json | ConvertFrom-Json -AsHashtable -Depth 100 $script:checks = 0 +$componentRoot = Join-Path (Split-Path $suiteRoot -Parent) 'review-candidate-verifier' function Assert-True { param([bool]$Condition, [string]$Message) @@ -22,10 +31,212 @@ function Test-FileHash { return (Get-FileHash $Path -Algorithm SHA256).Hash -eq $Hash } +Assert-True ($spec.stimuli.Count -eq 6) 'The suite must retain five PR cases and one catch-policy case.' +Assert-True (-not (Test-Path (Join-Path $suiteRoot 'catch-policy.vally.yaml'))) ( + 'The superseded standalone catch-policy specification remains.' +) +Assert-True (-not (Test-Path (Join-Path $suiteRoot 'fixtures/catch-policy'))) ( + 'The superseded standalone catch-policy fixtures remain.' +) +Assert-True ( + @(Get-ChildItem (Join-Path $suiteRoot 'fixtures') -Recurse -File -Filter '*.txt').Count -eq 0 +) 'The synthetic text fixtures remain.' foreach ($package in 'case-a', 'case-b', 'case-c') { $bundleIndex = Get-Content (Join-Path $componentRoot "fixtures/$package/bundle-index.json") -Raw Assert-True (-not $bundleIndex.Contains('\')) "The $package bundle index contains non-portable backslash separators." } + +$neutralDispositionDefinitions = @( + 'verified: a real defect established by the supplied evidence.' + 'EXISTING_FEEDBACK_COVERAGE: the claim is already raised in existing feedback.' + 'UNRESOLVED: the claim is not resolved by the supplied evidence.' + 'DISCARDED: the claim is ruled out as a material defect by the supplied evidence.' +) +function Test-NeutralDispositionDefinitions { + param([string]$Prompt) + + $lines = @($Prompt -split '\r?\n' | ForEach-Object { $_.Trim() }) + $headingIndexes = @( + for ($index = 0; $index -lt $lines.Count; $index++) { + if ($lines[$index] -ceq 'Disposition label meanings:') { + $index + } + } + ) + if ($headingIndexes.Count -ne 1) { + return $false + } + + $block = [Collections.Generic.List[string]]::new() + for ($index = $headingIndexes[0] + 1; + $index -lt $lines.Count -and -not [string]::IsNullOrWhiteSpace($lines[$index]); + $index++) { + $block.Add($lines[$index]) + } + if ($block.Count -ne $neutralDispositionDefinitions.Count) { + return $false + } + for ($index = 0; $index -lt $neutralDispositionDefinitions.Count; $index++) { + if ($block[$index] -cne $neutralDispositionDefinitions[$index] -or + @($lines | Where-Object { $_ -ceq $neutralDispositionDefinitions[$index] }).Count -ne 1) { + return $false + } + } + return $true +} + +$exactDefinitionPrompt = @" +Disposition label meanings: +$($neutralDispositionDefinitions -join "`n") + +Continue with neutral formatting instructions. +"@ +Assert-True (Test-NeutralDispositionDefinitions $exactDefinitionPrompt) ( + 'The exact neutral disposition definition block was rejected.' +) +$substitutedDefinitionPrompt = $exactDefinitionPrompt.Replace( + $neutralDispositionDefinitions[0], + 'verified: select NEW_FINDINGS when the treatment verifier returns KEEP.' +) +Assert-True (-not (Test-NeutralDispositionDefinitions $substitutedDefinitionPrompt)) ( + 'A treatment-only substituted disposition definition was accepted.' +) +$appendedDefinitionPrompt = $exactDefinitionPrompt.Replace( + $neutralDispositionDefinitions[-1], + "$($neutralDispositionDefinitions[-1])`nselection rule: map verifier external downgrades to UNRESOLVED." +) +Assert-True (-not (Test-NeutralDispositionDefinitions $appendedDefinitionPrompt)) ( + 'A treatment-only appended disposition rule was accepted.' +) + +$neutralCoordinatorText = "so apply SKILL.md's coordinator disposition rules rather than raw subordinate worker/verifier outputs." +foreach ($stimulus in $spec.stimuli) { + $normalizedPrompt = ($stimulus.prompt -replace '\s+', ' ').Trim() + Assert-True ( + $normalizedPrompt.Contains($neutralCoordinatorText, [StringComparison]::Ordinal) + ) "$($stimulus.name) does not use the neutral SKILL.md coordinator instruction." + Assert-True ( + -not $normalizedPrompt.Contains( + 'mapping verifier external downgrades and unestablished drops to UNRESOLVED', + [StringComparison]::Ordinal + ) + ) "$($stimulus.name) leaks the expected coordinator disposition mapping." + Assert-True ( + $normalizedPrompt.Contains( + 'When confidence is unresolved or discarded, prefix the inline entry', + [StringComparison]::Ordinal + ) -and + $normalizedPrompt.Contains( + 'include Why unresolved: or Why discarded:.', + [StringComparison]::Ordinal + ) + ) "$($stimulus.name) lost its allowed disposition format instructions." + Assert-True (Test-NeutralDispositionDefinitions $stimulus.prompt) ( + "$($stimulus.name) does not contain exactly the neutral disposition label definitions." + ) +} + +$supportFiles = @($spec.agent_environment.files) +Assert-True ( + @($supportFiles | Where-Object { $_.src -match 'SKILL\.md$|\.agent\.md$' }).Count -eq 0 +) 'The standard suite stages treatment instructions into its baseline.' +Assert-True ($spec.scoring.weights.program -eq 1) 'Disposition is not the primary deterministic gate.' +foreach ($key in 'skill-invocation', 'tool-calls', 'prompt') { + Assert-True ($spec.scoring.weights[$key] -eq 0) "The $key grader confounds disposition quality." +} + +foreach ($stimulus in $spec.stimuli) { + $caseRoot = Join-Path $suiteRoot "fixtures/$($stimulus.name)" + $provenance = Get-Content (Join-Path $caseRoot 'provenance.json') -Raw | + ConvertFrom-Json -AsHashtable -Depth 100 + Assert-True ($stimulus.name -match '^case-\d\d$') 'A stimulus name reveals its source or answer.' + Assert-True ($provenance.repository -eq 'dotnet/aspnetcore') 'A fixture comes from another repository.' + if ($stimulus.name -ne 'case-06') { + Assert-True ( + @($provenance.sourceRoles.Keys | Sort-Object) -join ',' -eq 'baseTip,head,mergeBase' + ) 'A frozen source role is missing.' + } else { + Assert-True ($provenance.fixtureKind -like 'synthetic public*') 'The catch example is misrepresented as production source.' + foreach ($caseFile in Get-ChildItem $caseRoot -File) { + $text = Get-Content $caseFile.FullName -Raw + Assert-True ( + $text -notmatch 'No target-base policy|No additional primary contract|unspecified\.txt|suppression-policy absence' + ) "The catch case file $($caseFile.Name) includes an answer hint." + } + foreach ($fileName in 'head.source', 'change.diff') { + $text = Get-Content (Join-Path $caseRoot $fileName) -Raw + $notificationIndex = $text.IndexOf('StatusChanged?.Invoke(Status);', [StringComparison]::Ordinal) + $sinkIndex = $text.IndexOf('_sink.Write(processingError);', [StringComparison]::Ordinal) + Assert-True ($notificationIndex -ge 0 -and $sinkIndex -gt $notificationIndex) ( + "The catch case $fileName must notify observers before invoking the diagnostic sink." + ) + } + } + + foreach ($file in $provenance.files) { + $path = Join-Path $caseRoot $file.file + Assert-True (Test-FileHash $path $file.sha256) "Frozen fixture hash mismatch: $path." + if ($file.ContainsKey('sources')) { + foreach ($source in $file.sources) { + Assert-True ( + $source.commit -eq $provenance.sourceRoles[$source.role] + ) "Source role mismatch: $path." + Assert-True ( + $source.blob -match '^[0-9a-f]{40}$' -and $source.ranges.Count -gt 0 + ) "Source blob or ranges are missing: $path." + } + } + } + + $trialFiles = @($supportFiles) + @($stimulus.agent_environment.files) + $requiredReads = @( + $stimulus.graders | + Where-Object { $_.type -eq 'tool-calls' } | + ForEach-Object { $_.config.required } + ) + foreach ($file in $trialFiles) { + $path = Join-Path $suiteRoot $file.src + $content = Get-Content $path -Raw + $matchingReads = @($requiredReads | Where-Object { + $file.dest -match $_.pattern -and $content -match $_.result + }) + Assert-True ($matchingReads.Count -gt 0) "No actual-byte read guard covers $($stimulus.name)/$($file.dest)." + } + Assert-True ( + @($requiredReads | Where-Object { + $_.pattern -eq 'review-pull-request' -and $_.result -eq 'Return result; never publish' + }).Count -eq 1 + ) 'The skill acquisition needs one real-content receipt, not two conjunctive tool choices.' +} + +$sampleRoot = Join-Path $suiteRoot 'fixtures/case-01' +$sample = Get-Content (Join-Path $sampleRoot 'provenance.json') -Raw | + ConvertFrom-Json -AsHashtable -Depth 100 +$file = $sample.files[0] +Assert-True ( + -not (Test-FileHash (Join-Path $sampleRoot $file.file) ('0' * 64)) +) 'A wrong snapshot hash passes the integrity check.' + +$repoRoot = (Resolve-Path (Join-Path $suiteRoot '../../..')).Path +$evalRoot = Split-Path $suiteRoot -Parent +foreach ($experimentName in 'review-vs-baseline', 'review-smoke') { + $experimentText = Get-Content (Join-Path $evalRoot "$experimentName.experiment.yaml") -Raw | + & npx --yes --registry=https://packagefeedproxy.microsoft.io/npm/ 'yaml@2.9.1' --json --single --strict + if ($LASTEXITCODE -ne 0) { + throw "Could not parse $experimentName." + } + $experiment = $experimentText | ConvertFrom-Json -AsHashtable -Depth 100 + $baseline = $experiment.variants.baseline.environment + $skilled = $experiment.variants.skilled.environment + Assert-True ($baseline.skills.Count -eq 0 -and -not $baseline.ContainsKey('files')) ( + 'Baseline receives additional treatment files.' + ) + Assert-True ($skilled.skills.Count -eq 1) 'The skilled variant lacks its skill.' + Assert-True (@($skilled.files | Where-Object dest -like '*.agent.md').Count -eq 2) ( + 'Only the skilled variant must receive both reviewer profiles.' + ) +} + $componentText = Get-Content (Join-Path $componentRoot 'eval.vally.yaml') -Raw | & npx --yes --registry=https://packagefeedproxy.microsoft.io/npm/ 'yaml@2.9.1' --json --single --strict if ($LASTEXITCODE -ne 0) { @@ -54,6 +265,26 @@ $checkoutRoot = Join-Path ([IO.Path]::GetTempPath()) ( ) New-Item -ItemType Directory -Path $checkoutRoot | Out-Null try { + $fixturePaths = @( + Get-ChildItem (Join-Path $suiteRoot 'fixtures') -Recurse -File -Force | + ForEach-Object { [IO.Path]::GetRelativePath($repoRoot, $_.FullName).Replace('\', '/') } + ) + & git -C $repoRoot -c core.autocrlf=true checkout-index ` + "--prefix=$checkoutRoot$([IO.Path]::DirectorySeparatorChar)" -- @fixturePaths + if ($LASTEXITCODE -ne 0) { + throw 'Could not materialize the tracked fixture files through Git.' + } + foreach ($stimulus in $spec.stimuli) { + $relativeRoot = "eng/skill-evals/review-pull-request/fixtures/$($stimulus.name)" + $checkedOutRoot = Join-Path $checkoutRoot $relativeRoot + $provenance = Get-Content (Join-Path $checkedOutRoot 'provenance.json') -Raw | + ConvertFrom-Json -AsHashtable -Depth 100 + foreach ($file in $provenance.files) { + Assert-True ( + Test-FileHash (Join-Path $checkedOutRoot $file.file) $file.sha256 + ) "Git checkout changed the frozen bytes of $relativeRoot/$($file.file)." + } + } $componentRelative = 'eng/skill-evals/review-candidate-verifier/fixtures' $componentPaths = @( Get-ChildItem (Join-Path $componentRoot 'fixtures') -Recurse -File -Force | diff --git a/eng/skill-evals/test_run.ps1 b/eng/skill-evals/test_run.ps1 index 9249917f8f88..591618787242 100644 --- a/eng/skill-evals/test_run.ps1 +++ b/eng/skill-evals/test_run.ps1 @@ -186,8 +186,8 @@ stimuli: Read-Invocations | Where-Object { $_.Arguments[0] -eq 'experiment' } ) - Assert-True ($validateInvocations.Count -eq 2) ( - 'Default validation did not resolve generic experiments.' + Assert-True ($validateInvocations.Count -eq 4) ( + 'Default validation did not resolve generic and reviewer experiments.' ) foreach ($invocation in $validateInvocations) { Assert-True ($invocation.Arguments[1] -eq 'run') ( @@ -206,6 +206,12 @@ stimuli: Assert-True ($validateInvocations.Arguments -contains ( Join-Path $repoRoot 'eng/skill-evals/skills-smoke.experiment.yaml' )) 'Default validation did not resolve the smoke experiment.' + Assert-True ($validateInvocations.Arguments -contains ( + Join-Path $repoRoot 'eng/skill-evals/review-vs-baseline.experiment.yaml' + )) 'Default validation did not resolve the reviewer experiment.' + Assert-True ($validateInvocations.Arguments -contains ( + Join-Path $repoRoot 'eng/skill-evals/review-smoke.experiment.yaml' + )) 'Default validation did not resolve the reviewer smoke experiment.' Remove-Item $record & $runner Validate ` @@ -408,6 +414,43 @@ stimuli: Assert-True ($specializedInvocation[0] -eq 'eval') 'Specialized run did not use Vally eval.' Assert-True ($specializedInvocation -contains '--eval-spec') 'Specialized run omitted --eval-spec.' + Remove-Item $record + & $runner Validate ` + -Suite review-pull-request ` + -Vally $fakeVally ` + -VallyPrefix @() + $suiteInvocations = @(Read-Invocations) + $suiteLint = @($suiteInvocations | Where-Object { $_.Arguments[0] -eq 'lint' }) + Assert-True ($suiteLint.Count -eq 1) 'Suite validation linted unrelated specifications.' + Assert-True ($suiteLint[0].Arguments -contains ( + Join-Path $repoRoot 'eng/skill-evals/review-pull-request/eval.vally.yaml' + )) 'Suite validation did not lint the selected specification.' + $suitePlans = @($suiteInvocations | Where-Object { $_.Arguments[0] -eq 'experiment' }) + Assert-True ($suitePlans.Count -eq 2) 'Suite validation did not resolve both experiments.' + foreach ($invocation in $suitePlans) { + Assert-True ($invocation.Arguments -contains '--dry-run') 'Suite validation could invoke models.' + Assert-True ($invocation.Arguments -contains '--eval-filter') 'Suite validation omitted its filter.' + Assert-True ($invocation.Arguments -contains 'review-pull-request/eval.vally.yaml') 'Suite validation selected the wrong eval.' + } + + & $runner Run ` + -Suite review-pull-request ` + -Vally $fakeVally ` + -VallyPrefix @() ` + -OutputDirectory $output + $suiteRun = Read-Invocation + Assert-True ($suiteRun[0] -eq 'experiment') 'Suite run bypassed experiment skill ownership.' + Assert-True ($suiteRun -contains 'review-pull-request/eval.vally.yaml') 'Suite run selected the wrong eval.' + Assert-True ($suiteRun -contains (Join-Path $repoRoot 'eng/skill-evals/review-vs-baseline.experiment.yaml')) ( + 'Reviewer run used the generic treatment.' + ) + & $runner Run -Suite review-pull-request ` + -Experiment eng/skill-evals/skills-smoke.experiment.yaml ` + -Vally $fakeVally -VallyPrefix @() -OutputDirectory $output + Assert-True ((Read-Invocation) -contains (Join-Path $repoRoot 'eng/skill-evals/review-smoke.experiment.yaml')) ( + 'Reviewer smoke run used the generic treatment.' + ) + foreach ($smoke in @($false, $true)) { $componentOutput = Join-Path $testRoot "component-[$smoke]" New-Item -ItemType Directory -Path (Join-Path $componentOutput '2025-12-31T00-00-00') -Force | Out-Null @@ -439,6 +482,14 @@ stimuli: 'Component dry-run overwrote an existing plan snapshot.' ) Write-Host 'ComponentDryRunPreservesExistingPlan passed.' + $componentOutput = Join-Path $testRoot 'component-review-smoke' + & $runner Run -Suite review-candidate-verifier ` + -Experiment eng/skill-evals/review-smoke.experiment.yaml ` + -Vally $fakeVally -VallyPrefix @() -OutputDirectory $componentOutput + $componentRun = Read-Invocation + Assert-True ($componentRun[([array]::IndexOf($componentRun, '--runs') + 1)] -eq '1') ( + 'Reviewer smoke selection unexpectedly ran the full component suite.' + ) function Assert-CustomComponentPlan { param( @@ -648,6 +699,9 @@ stimuli: Where-Object { Test-Path (Join-Path $_.FullName 'eval.vally.yaml') }).Count Assert-True ($allRuns.Count -eq $suiteCount) 'Default run omitted a standard suite.' Assert-True (($allRuns.Arguments -join ' ') -like '*review-candidate-verifier*') 'Default run omitted the component suite.' + Assert-True ($allRuns.Arguments -contains (Join-Path $repoRoot 'eng/skill-evals/review-vs-baseline.experiment.yaml')) ( + 'Default run omitted the reviewer comparison.' + ) foreach ($invalidSuite in @('../outside', '..', 'missing-suite')) { $rejected = $false From 7b52f19f089c6b2c29aeb6226f565e65c5096b1a Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Mon, 16 Nov 2026 11:07:17 -0600 Subject: [PATCH 2/6] Recognize underscore-emphasized candidate IDs in review grading Review-mode C1 and extra-candidate checks ran on raw text, so _C1_ and __C1__ were invisible to the word-boundary match. Check markdown-stripped text instead. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/skill-evals/grade_disposition.mjs | 4 ++-- eng/skill-evals/test_disposition.mjs | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/eng/skill-evals/grade_disposition.mjs b/eng/skill-evals/grade_disposition.mjs index 59e87cccb667..fd472d004a9c 100644 --- a/eng/skill-evals/grade_disposition.mjs +++ b/eng/skill-evals/grade_disposition.mjs @@ -116,7 +116,7 @@ function hasPositiveC1(sectionText) { return sectionText .split(/\r?\n/) - .some(line => /\bC1\b/.test(line) && !isNegativeC1Line(line)); + .some(line => /\bC1\b/.test(stripMarkdown(line)) && !isNegativeC1Line(line)); } function gradeReview(name, output) @@ -160,7 +160,7 @@ function gradeReview(name, output) { return false; } - if ([...sections.values()].some(text => /\bC(?!1\b)\d+\b/.test(text))) + if ([...sections.values()].some(text => /\bC(?!1\b)\d+\b/.test(stripMarkdown(text)))) { return false; } diff --git a/eng/skill-evals/test_disposition.mjs b/eng/skill-evals/test_disposition.mjs index a54d7f056728..4a89ef14c537 100644 --- a/eng/skill-evals/test_disposition.mjs +++ b/eng/skill-evals/test_disposition.mjs @@ -159,6 +159,26 @@ test('ReviewDispositionToleratesSingleUnderscoreEmphasis', async context => } }); +test('ReviewDispositionRecognizesUnderscoreEmphasizedCandidateIds', async context => +{ + for (const [name, caseName, output, expected] of [ + ['single-underscore', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('C1 missing target-base contract.', '- _C1_: missing target-base contract.'), 1], + ['double-underscore', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('C1 missing target-base contract.', '- __C1__: missing target-base contract.'), 1], + ['contradictory-placement', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\n_C1_: old and head match.'), 0], + ['extra-candidate', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\n_C2_: another concern.'), 0], + ]) + { + await context.test(name, () => + { + assert.equal(score(caseName, output), expected); + }); + } +}); + test('ReviewDispositionDistinguishesNoProseFromSectionAbsence', async context => { for (const [name, caseName, output, expected] of [ From 9d12a990eb373d1ec5b5081c719de8e59beeb5c2 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Mon, 16 Nov 2026 11:08:00 -0600 Subject: [PATCH 3/6] Treat cross-section C1 negation as absence in review grading A DISCARDED line such as 'C1 is not discarded; it remains unresolved' or 'None. C1 is unresolved rather than discarded.' states that C1 belongs elsewhere, but the grader counted it as a DISCARDED candidate. Recognize negation of the section's own status, paired with another status, as absence. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/skill-evals/grade_disposition.mjs | 30 ++++++++++++++++++++++++--- eng/skill-evals/test_disposition.mjs | 26 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/eng/skill-evals/grade_disposition.mjs b/eng/skill-evals/grade_disposition.mjs index fd472d004a9c..0cf0af09e15d 100644 --- a/eng/skill-evals/grade_disposition.mjs +++ b/eng/skill-evals/grade_disposition.mjs @@ -112,11 +112,35 @@ function isNegativeC1Line(line) /^(?:(?:is\s+|was\s+)?not\s+(?:covered(?:\s+by\s+(?:any\s+)?(?:existing\s+)?feedback(?:\s+in\s+(?:the\s+)?(?:supplied\s+|frozen\s+|existing\s+)*(?:(?:pr|review|evidence)\s+)*(?:evidence|bundle|pr|review|threads?|comments?|feedback))?)?|unresolved|discarded|applicable)|has\s+no\s+existing\s+feedback|(?:is\s+|was\s+)?omitted)[.!]?\s*$/i.test(afterC1)); } -function hasPositiveC1(sectionText) +const sectionStatuses = new Map([ + ['UNRESOLVED', 'unresolved'], + ['DISCARDED', 'discarded'], +]); + +function isCrossSectionNegation(line, section) +{ + const status = sectionStatuses.get(section); + if (!status) + { + return false; + } + const clean = stripMarkdown(line) + .trim() + .replace(/^(?:[-*+]|\d+[.)])\s+/, '') + .replace(/^(?:none|n\/a)[.!]\s+/i, '') + .trim(); + const afterC1 = clean.replace(/^C1\b\s*(?:[-:—–]|\s)*/i, ''); + const otherStatus = `(?!${status}\\b)(?:unresolved|discarded|verified|a\\s+new\\s+finding)`; + return afterC1 !== clean && ( + new RegExp(`^(?:is\\s+|was\\s+)?not\\s+${status}\\s*[;,:—–-]\\s*(?:it|C1)\\s+(?:is|remains|stays)\\s+${otherStatus}[.!]?\\s*$`, 'i').test(afterC1) || + new RegExp(`^(?:is|was|remains)\\s+${otherStatus}\\s+rather\\s+than\\s+${status}[.!]?\\s*$`, 'i').test(afterC1)); +} + +function hasPositiveC1(sectionText, section) { return sectionText .split(/\r?\n/) - .some(line => /\bC1\b/.test(stripMarkdown(line)) && !isNegativeC1Line(line)); + .some(line => /\bC1\b/.test(stripMarkdown(line)) && !isNegativeC1Line(line) && !isCrossSectionNegation(line, section)); } function gradeReview(name, output) @@ -164,7 +188,7 @@ function gradeReview(name, output) { return false; } - const hasCandidate = key => hasPositiveC1(sections.get(key)); + const hasCandidate = key => hasPositiveC1(sections.get(key), key); if (!hasCandidate(expected.section)) { return false; diff --git a/eng/skill-evals/test_disposition.mjs b/eng/skill-evals/test_disposition.mjs index 4a89ef14c537..099701d34622 100644 --- a/eng/skill-evals/test_disposition.mjs +++ b/eng/skill-evals/test_disposition.mjs @@ -179,6 +179,32 @@ test('ReviewDispositionRecognizesUnderscoreEmphasizedCandidateIds', async contex } }); +test('ReviewDispositionTreatsCrossSectionNegationAsAbsence', async context => +{ + for (const [name, caseName, output, expected] of [ + ['semicolon', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('DISCARDED\nNone.', 'DISCARDED\nC1 is not discarded; it remains unresolved.'), 1], + ['comma', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('DISCARDED\nNone.', 'DISCARDED\nC1 is not discarded, it remains unresolved.'), 1], + ['colon', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('DISCARDED\nNone.', 'DISCARDED\n**C1:** Not discarded: it remains unresolved.'), 1], + ['none-rather-than', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('DISCARDED\nNone.', 'DISCARDED\nNone. **C1 is unresolved rather than discarded.**'), 1], + ['unresolved-section', 'case-01', review('DISCARDED', 'discarded') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1 is not unresolved; it is discarded.'), 1], + ['matching-section-is-present', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1 is not discarded; it remains unresolved.'), 0], + ['negation-with-prose', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\nC1 is not discarded; old and head match.'), 0], + ]) + { + await context.test(name, () => + { + assert.equal(score(caseName, output), expected); + }); + } +}); + test('ReviewDispositionDistinguishesNoProseFromSectionAbsence', async context => { for (const [name, caseName, output, expected] of [ From 586cbd34db1b659d9713ae7efcb09c044181c8c4 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Mon, 16 Nov 2026 11:09:22 -0600 Subject: [PATCH 4/6] Pin review absence-marker and PATH bullet boundaries Add review-mode tests for absence-marker prose with comma and colon continuations, 'No findings' prose, and an unindented '- PATH:' bullet that ends a section. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/skill-evals/test_disposition.mjs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/eng/skill-evals/test_disposition.mjs b/eng/skill-evals/test_disposition.mjs index 099701d34622..99e80cc4aae5 100644 --- a/eng/skill-evals/test_disposition.mjs +++ b/eng/skill-evals/test_disposition.mjs @@ -139,6 +139,12 @@ test('ReviewDispositionResetsAtUnindentedTopLevelMetadata', async context => assert.equal(score('case-02', output), 0); }); } + await context.test('bullet-before-trailing-text', () => + { + const output = review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\nNone.\n- PATH: per-guide\nC1 was reviewed through the per-guide path.'); + assert.equal(score('case-02', output), 1); + }); }); test('ReviewDispositionToleratesSingleUnderscoreEmphasis', async context => @@ -256,6 +262,16 @@ test('ReviewDispositionDistinguishesSubstantiveNoneFromAbsenceMarkers', async co ['absence-in-one-section-only', 'case-02', review('NEW_FINDINGS', 'verified') .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1: None.') .replace('DISCARDED\nNone.', 'DISCARDED\nC1 omitted.'), 1], + ['conflicting-no-findings-prose', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1: No findings warranted because propagation is unknown.'), 0], + ['conflicting-none-applicable-comma-prose', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1: None applicable, but propagation is unknown.'), 0], + ['conflicting-none-applicable-colon-prose', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1: None applicable: propagation is unknown.'), 0], + ['conflicting-na-comma-prose', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1: N/A, but propagation is unknown.'), 0], + ['conflicting-na-colon-prose', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('UNRESOLVED\nNone.', 'UNRESOLVED\nC1: N/A: the propagation contract is unknown.'), 0], ]) { await context.test(name, () => From 2330e6d947e9f0c46e6c3eaae1cfd44c22a1aee2 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Mon, 16 Nov 2026 12:13:36 -0600 Subject: [PATCH 5/6] Keep literal paths from being read as review candidate IDs Recognizing underscore-emphasized IDs by stripping Markdown exposed IDs inside literal paths such as src/_C2_/File.cs. Match IDs on the raw text instead: keep word-bounded IDs and also accept an underscore-emphasis run only when it is not part of a word or path. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/skill-evals/grade_disposition.mjs | 14 ++++++++++++-- eng/skill-evals/test_disposition.mjs | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/eng/skill-evals/grade_disposition.mjs b/eng/skill-evals/grade_disposition.mjs index 0cf0af09e15d..9bd7069e379a 100644 --- a/eng/skill-evals/grade_disposition.mjs +++ b/eng/skill-evals/grade_disposition.mjs @@ -86,6 +86,16 @@ function stripMarkdown(text) .replace(/(? /\bC1\b/.test(stripMarkdown(line)) && !isNegativeC1Line(line) && !isCrossSectionNegation(line, section)); + .some(line => c1Pattern.test(line) && !isNegativeC1Line(line) && !isCrossSectionNegation(line, section)); } function gradeReview(name, output) @@ -184,7 +194,7 @@ function gradeReview(name, output) { return false; } - if ([...sections.values()].some(text => /\bC(?!1\b)\d+\b/.test(stripMarkdown(text)))) + if ([...sections.values()].some(text => otherCandidatePattern.test(text))) { return false; } diff --git a/eng/skill-evals/test_disposition.mjs b/eng/skill-evals/test_disposition.mjs index 99e80cc4aae5..d1b648896b1d 100644 --- a/eng/skill-evals/test_disposition.mjs +++ b/eng/skill-evals/test_disposition.mjs @@ -176,6 +176,26 @@ test('ReviewDispositionRecognizesUnderscoreEmphasizedCandidateIds', async contex .replace('DISCARDED\nNone.', 'DISCARDED\n_C1_: old and head match.'), 0], ['extra-candidate', 'case-02', review('NEW_FINDINGS', 'verified') .replace('DISCARDED\nNone.', 'DISCARDED\n_C2_: another concern.'), 0], + ['code-span-extra-candidate', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\n`C2`: another concern.'), 0], + ['code-span-path-is-not-extra-candidate', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('Why verified: source reason.', 'Why verified: `src/_C2_/File.cs` is unchanged.'), 1], + ['code-span-path-is-not-c1', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\nOnly `src/_C1_/File.cs` moved.'), 1], + ['emphasis-wrapping-code-span', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('C1 missing target-base contract.', '- _C1 (`AgentContext.cs`): missing target-base contract._'), 1], + ['emphasis-wrapping-code-span-extra-candidate', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\n- _C2 (`File.cs`): another concern._'), 0], + ['emphasis-between-double-backtick-spans', 'case-06', review('UNRESOLVED', 'unresolved') + .replace('C1 missing target-base contract.', '``a`` _C1_ ``b``'), 1], + ['double-backtick-code-span-path', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('Why verified: source reason.', 'Why verified: ``code ` src/_C2_/File.cs`` is unchanged.'), 1], + ['escaped-backticks-are-not-code-span', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\n\\` _C2_: another concern. \\`'), 0], + ['multiline-code-span-path', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('Why verified: source reason.', 'Why verified: `unchanged\nsrc/_C2_/File.cs` source.'), 1], + ['snake-case-identifier', 'case-02', review('NEW_FINDINGS', 'verified') + .replace('DISCARDED\nNone.', 'DISCARDED\nOnly snake_C1_name moved.'), 1], ]) { await context.test(name, () => From ce5f001a6c706683387eb404e03971613cafff82 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Mon, 16 Nov 2026 14:10:15 -0600 Subject: [PATCH 6/6] Narrow case-04 and record L1 diagnostics Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/skill-evals/README.md | 49 +++++++++++++++---- .../review-pull-request/eval.vally.yaml | 12 ++--- .../fixtures/case-04/case.source | 2 +- .../fixtures/case-04/provenance.json | 2 +- 4 files changed, 47 insertions(+), 18 deletions(-) diff --git a/eng/skill-evals/README.md b/eng/skill-evals/README.md index a0abd38c8b07..8f63334c007a 100644 --- a/eng/skill-evals/README.md +++ b/eng/skill-evals/README.md @@ -45,10 +45,12 @@ Its baseline is a diagnostic control, not a competitor. Skill lift requires end-to-end evidence. All six L1 oracles (`case-01`, `case-02`, `case-03`, `case-04`, `case-05`, and `case-06`) are provisional pending an independent two-reviewer audit. -The agent-relabelled `DISCARDED` oracle for `case-04` remains disputed, not -independently proven. The `case-06` notification-order confound is corrected, -its `UNRESOLVED` oracle is retained, and cold GPT-5.6 and Opus-5.5 adjudications -agree. That model agreement is not a human audit. +The original `case-04` claim mixed an unestablished timing link with a +contradicted effect link, so reviewers split between `DISCARDED` and +`UNRESOLVED`. The case was narrowed to the ordering of the flag and sign-in call. +The `case-06` notification-order confound is corrected, its `UNRESOLVED` oracle +is retained, and two cold reviewers from different model families agree. That +agreement is not a human audit. Both arms share frozen source and both guidance documents. Only the skilled arm receives the skill and verifier/worker instructions. Baseline does not receive `SKILL.md` or either agent profile. `tool-calls.required` matches both read arguments and @@ -67,7 +69,7 @@ disposition scores are reported, not threshold-gated. The zero-weight LLM rubrics remain secondary diagnostics, not semantic quality gates. They still incur judge calls during a model-bearing run. The subject and -judge both use `gpt-5.6-sol`; the judge is not independent-model corroboration. +judge use the same model; the judge is not independent-model corroboration. These public development cases are not held-out evidence. Five repeats do not create five independent PR lineages. @@ -87,10 +89,39 @@ policy-only head-test scenario (close to @maraf's 3/10 `DROP(unestablished)` / 7/10 `DOWNGRADE(intent)` synthetic fixture) was omitted from the component gate; `SKILL.md` retains the coordinator backstop mapping `DOWNGRADE(intent)` with `contract: "n/a"` to `UNRESOLVED`, which has not been measured end to end. -The fresh 30-trial-per-arm L1 regression scored 27/30 for the diagnostic baseline -and 29/30 for skilled. Skilled `case-04` scored 4/5, below its configured 5/5 -gate. Every other skilled case scored 5/5. These results are against the -provisional oracles and do not establish skill lift. +The earlier 30-trial-per-arm L1 run scored 27/30 for the diagnostic baseline +and 29/30 for skilled, with skilled `case-04` at 4/5. A subsequent 30-trial +skilled-only run with the current skill also scored 29/30, with `case-02` at +4/5 and every other case at 5/5. Both skilled runs failed the configured 5/5 +per-case gate. Both measured the original `case-04` claim, before it was +narrowed. The baseline was not rerun. These results are against provisional +oracles and do not establish skill lift. + +Red means "read the misses": inspect each decision and its reason against the +provisional oracle. In the earlier run, baseline `case-02` trial 3 discarded the +claim because it treated required-parameter behavior and the converter test as +sufficient intent; baseline `case-04` trials 0 and 3 and skilled `case-04` +trial 3 were unresolved because browser or MSAL timing evidence was missing. +In the later run, skilled `case-02` trial 4 discarded the claim, treating the +target-base required-parameter rule and the lower-layer head converter test as +evidence of intent. + +A separate skilled run of the narrowed `case-04` scored 10/10, with all read +receipts passing. Each decision cited the flag assignment before delegation to +`signIn`. Some responses also asserted browser observation timing that the +frozen source does not establish; that timing is not needed for this claim. + +A 20-trial skilled diagnostic of `case-02` scored 19/20. Its only miss, +trial 3, discarded the claim: it treated the target-base required-parameter +rule as dispositive and the lower-layer head converter test as supporting intent. +All read receipts passed. The result assertion failed because 19/20 is below +the configured threshold of 1. Together with the earlier 4/5, current-skill +`case-02` scored 23/25. Both misses warrant review in the pending two-reviewer +audit of its provisional oracle. + +At an assumed independent per-trial pass rate of 0.92, a 5/5 gate goes red +about one run in three. The 23/25 sample does not establish a population rate. +The full six-case suite was not rerun after narrowing `case-04`. Model-free validation checks layout, schema, source hashes, read-guard coverage, and experiment selection. It does not establish adjudication quality. A diff --git a/eng/skill-evals/review-pull-request/eval.vally.yaml b/eng/skill-evals/review-pull-request/eval.vally.yaml index 156800ea419c..d3d7be04f4f0 100644 --- a/eng/skill-evals/review-pull-request/eval.vally.yaml +++ b/eng/skill-evals/review-pull-request/eval.vally.yaml @@ -570,19 +570,17 @@ stimuli: pattern: docs[/\\]+BlazorComponentsGuidance\.md result: Keep diagnostics actionable but not noisy rubric: - - All criteria are mandatory. C1 asserts that the new test server token endpoint changes the browser regression's - observable success because the scenario completes a token exchange through that endpoint before its assertions. - Do not treat a directly callable endpoint as evidence that this browser scenario calls it before asserting. + - All criteria are mandatory. C1 asserts that window.__msalSignInCalled becomes true only after an authorization-code + exchange through the new token endpoint completes, so the endpoint response determines the sign-in assertion. - Inspect the copied token endpoint at mergeBase and head, the MSAL app configuration, the real signIn wrapper, and NavigateDirectlyToLoginCallbackRestartsLoginWithoutInteropFailure. - Trace the exact test execution order across RemoteMsalAuthenticationTest.cs and RemoteMsalAuthenticationApp.razor. Direct navigation to /subdir/msal-authentication/login-callback carries no authorization code, and the wrapper in RemoteMsalAuthenticationApp.razor sets window.__msalSignInCalled = true before delegating to AuthenticationService.signIn(state). - - Because the test assertions run as soon as window.__msalSignInCalled is true and only check the browser log for - the interop failure without awaiting any token exchange, C1's causal premise is contradicted by the frozen - source. Place C1 in DISCARDED and surface it inline under NEW_FINDINGS with [DISCARDED], confidence discarded, - and Why discarded. + - The wrapper sets window.__msalSignInCalled before calling AuthenticationService.signIn(state), contradicting + C1's claimed dependency on a completed exchange. Place C1 in DISCARDED and surface it inline under NEW_FINDINGS + with [DISCARDED], confidence discarded, and Why discarded. - Do not substitute a different endpoint correctness claim or remedy for C1's asserted browser effect. - name: case-05 prompt: | diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/case.source b/eng/skill-evals/review-pull-request/fixtures/case-04/case.source index c0e0d2cdd231..9548a580c3cb 100644 --- a/eng/skill-evals/review-pull-request/fixtures/case-04/case.source +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/case.source @@ -5,4 +5,4 @@ Merge base: 66e2adb4e0297e445686cb7a70d6c9aa84dcf3af Base tip: 66e2adb4e0297e445686cb7a70d6c9aa84dcf3af The source files are excerpts, not a complete ready version-2 review bundle. provenance.json maps every excerpt to its original source path and lines. -C1: The new RemoteMsalAuthenticationStartup token endpoint changes the observed result of NavigateDirectlyToLoginCallbackRestartsLoginWithoutInteropFailure because that browser scenario completes an exchange through this endpoint before its assertions. The concern is the asserted browser-test effect, not an independent endpoint policy claim. +C1: In NavigateDirectlyToLoginCallbackRestartsLoginWithoutInteropFailure, window.__msalSignInCalled only becomes true after an authorization-code exchange through the new RemoteMsalAuthenticationStartup token endpoint completes, so that endpoint's response determines whether the test's sign-in assertion succeeds. diff --git a/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json b/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json index 285509429ad1..332542dde17a 100644 --- a/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json +++ b/eng/skill-evals/review-pull-request/fixtures/case-04/provenance.json @@ -125,7 +125,7 @@ }, { "file": "case.source", - "sha256": "43116be262a937b2c1d227222b1cb45d1023c3f23c3ce29b73947f512794a2da" + "sha256": "0652d1a5209c39c4d48d986bef14da99a041d15dca876488e90e089b40e9ddbe" } ] }