diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 8d0a63ab293..36c683d2cb1 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 name: E2E -run-name: ${{ inputs.risk_correlation != '' && format('E2E risk {0}', inputs.risk_correlation) || format('E2E {0}', github.ref_name) }} +run-name: "${{ inputs.risk_pr && format('E2E PR #{0} risk {1}', inputs.pr_number, inputs.risk_correlation) || (inputs.risk_correlation != '' && format('E2E risk {0}', inputs.risk_correlation) || format('E2E {0}', github.ref_name)) }}" on: schedule: @@ -54,13 +54,18 @@ on: required: false default: false type: boolean + risk_pr: + description: Mark an exact-commit risk run as trusted PR validation. + required: false + default: false + type: boolean permissions: contents: read concurrency: - group: e2e-${{ github.ref }}-${{ inputs.risk_shadow && github.run_id || inputs.targets || 'supported' }}-${{ inputs.risk_shadow && 'risk-shadow' || inputs.jobs || 'all-jobs' }} - cancel-in-progress: false + group: ${{ inputs.risk_pr && format('e2e-required-live-pr-{0}', inputs.pr_number) || format('e2e-{0}-{1}-{2}', github.ref, inputs.risk_shadow && github.run_id || inputs.targets || 'supported', inputs.risk_shadow && 'risk-shadow' || inputs.jobs || 'all-jobs') }} + cancel-in-progress: ${{ inputs.risk_pr }} env: NEMOCLAW_E2E_EXPECTED_SHA: ${{ inputs.checkout_sha }} @@ -72,6 +77,9 @@ env: jobs: generate-matrix: runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read outputs: matrix: ${{ steps.matrix.outputs.matrix }} hermes_selected: ${{ steps.matrix.outputs.hermes_selected }} @@ -84,12 +92,15 @@ jobs: persist-credentials: false - name: Validate exact-commit dispatch - if: ${{ inputs.checkout_sha != '' || inputs.risk_plan_hash != '' || inputs.risk_correlation != '' || inputs.risk_shadow }} + if: ${{ inputs.checkout_sha != '' || inputs.risk_plan_hash != '' || inputs.risk_correlation != '' || inputs.risk_shadow || inputs.risk_pr }} env: CHECKOUT_SHA: ${{ inputs.checkout_sha }} + GITHUB_READ_TOKEN: ${{ github.token }} JOBS: ${{ inputs.jobs }} PLAN_HASH: ${{ inputs.risk_plan_hash }} + PR_NUMBER: ${{ inputs.pr_number }} RISK_CORRELATION: ${{ inputs.risk_correlation }} + RISK_PR: ${{ inputs.risk_pr }} RISK_SHADOW: ${{ inputs.risk_shadow }} TARGETS: ${{ inputs.targets }} WORKFLOW_EVENT: ${{ github.event_name }} @@ -100,9 +111,17 @@ jobs: [[ "$WORKFLOW_EVENT" == "workflow_dispatch" && "$WORKFLOW_REF" == "refs/heads/main" ]] || { echo "::error::exact-commit runs require a workflow_dispatch from main"; exit 1; } [[ "$RISK_SHADOW" == "true" ]] || { echo "::error::exact-commit inputs require risk_shadow=true"; exit 1; } [[ "$CHECKOUT_SHA" =~ ^[a-f0-9]{40}$ ]] || { echo "::error::checkout_sha must be a lowercase 40-character SHA"; exit 1; } - [[ "$CHECKOUT_SHA" == "$WORKFLOW_SHA" ]] || { echo "::error::checkout_sha must equal the current main workflow commit"; exit 1; } [[ "$(git rev-parse --verify HEAD)" == "$CHECKOUT_SHA" ]] || { echo "::error::checked-out HEAD does not match checkout_sha"; exit 1; } - git merge-base --is-ancestor "$CHECKOUT_SHA" origin/main || { echo "::error::checkout_sha must already be reachable from main"; exit 1; } + if [[ "$RISK_PR" == "true" ]]; then + [[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::risk PR requires a positive PR number"; exit 1; } + pr_json="$(curl -fsSL -H 'Accept: application/vnd.github+json' -H "Authorization: Bearer $GITHUB_READ_TOKEN" -H 'X-GitHub-Api-Version: 2022-11-28' "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")" + [[ "$(jq -r .state <<<"$pr_json")" == "open" ]] || { echo "::error::risk PR must still be open"; exit 1; } + [[ "$(jq -r .head.repo.full_name <<<"$pr_json")" == "$GITHUB_REPOSITORY" ]] || { echo "::error::automatic risk PR must be first-party"; exit 1; } + [[ "$(jq -r .head.sha <<<"$pr_json")" == "$CHECKOUT_SHA" ]] || { echo "::error::checkout_sha is stale for the PR"; exit 1; } + else + [[ "$CHECKOUT_SHA" == "$WORKFLOW_SHA" ]] || { echo "::error::checkout_sha must equal the current main workflow commit"; exit 1; } + git merge-base --is-ancestor "$CHECKOUT_SHA" origin/main || { echo "::error::checkout_sha must already be reachable from main"; exit 1; } + fi [[ "$PLAN_HASH" =~ ^[a-f0-9]{64}$ ]] || { echo "::error::risk_plan_hash must be a lowercase SHA-256"; exit 1; } [[ "$RISK_CORRELATION" =~ ^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$ ]] || { echo "::error::risk_correlation must be a lowercase UUIDv4"; exit 1; } [[ -n "$JOBS" && -z "$TARGETS" ]] || { echo "::error::shadow risk runs require selective jobs and forbid targets/fan-out"; exit 1; } @@ -3519,6 +3538,15 @@ jobs: - *dockerhub-auth + - name: Reclaim runner disk for dual-version upgrade images + shell: bash + run: | + set -euo pipefail + df -h / + sudo rm -rf -- /usr/local/lib/android /usr/share/dotnet /opt/ghc + docker system prune --all --force + df -h / + - name: Prepare E2E workspace uses: NVIDIA/NemoClaw/.github/actions/prepare-e2e@50281ee84c4a6fc759da95ea28fc0b7d9c378a28 diff --git a/.github/workflows/pr-e2e-risk-gate.yaml b/.github/workflows/pr-e2e-risk-gate.yaml new file mode 100644 index 00000000000..16076421699 --- /dev/null +++ b/.github/workflows/pr-e2e-risk-gate.yaml @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: E2E / Required Live Coordinator + +on: + pull_request_target: + types: [synchronize, reopened, closed] + workflow_run: + workflows: ["CI / Pull Request"] + types: [completed] + +permissions: {} + +concurrency: + group: required-live-${{ github.event.pull_request.head.repo.full_name || github.event.workflow_run.head_repository.full_name }}-${{ github.event.pull_request.head.ref || github.event.workflow_run.head_branch }} + cancel-in-progress: true + +jobs: + cancel-superseded: + if: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'pull_request_target' }} + runs-on: ubuntu-latest + permissions: + actions: write + contents: read + timeout-minutes: 5 + steps: + - name: Checkout trusted coordinator + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + repository: NVIDIA/NemoClaw + ref: ${{ github.sha }} + persist-credentials: false + + - name: Cancel superseded required-live runs + env: + GITHUB_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: >- + node --experimental-strip-types tools/e2e-advisor/pr-risk-gate.mts + --mode cancel --pr "$PR_NUMBER" + + coordinate: + if: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' }} + runs-on: ubuntu-latest + permissions: + actions: write + checks: write + contents: read + pull-requests: read + timeout-minutes: 150 + steps: + - name: Checkout trusted coordinator + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + repository: NVIDIA/NemoClaw + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Setup Node + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.0.0 + with: + node-version: "22" + cache: npm + + - name: Install trusted coordinator dependencies + run: npm ci --ignore-scripts + + - id: initialize + name: Create exact-head required-live check + env: + GITHUB_TOKEN: ${{ github.token }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: >- + node --experimental-strip-types tools/e2e-advisor/pr-risk-gate.mts + --mode initialize --head "$HEAD_SHA" + + - id: resolve + name: Resolve exact PR and CI result + env: + CI_CONCLUSION: ${{ github.event.workflow_run.conclusion }} + GITHUB_TOKEN: ${{ github.token }} + HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} + HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: >- + node --experimental-strip-types tools/e2e-advisor/pr-risk-gate.mts + --mode resolve + + - name: Fetch exact first-party PR objects + if: ${{ steps.resolve.outputs.first_party == 'true' && steps.resolve.outputs.ci_green == 'true' }} + env: + BASE_SHA: ${{ steps.resolve.outputs.base_sha }} + HEAD_SHA: ${{ steps.resolve.outputs.head_sha }} + run: | + git fetch --no-tags origin "$BASE_SHA" "$HEAD_SHA" + + - id: advisor + name: Wait for exact-head Advisor artifacts + if: ${{ steps.resolve.outputs.first_party == 'true' && steps.resolve.outputs.ci_green == 'true' }} + env: + GH_TOKEN: ${{ github.token }} + HEAD_SHA: ${{ steps.resolve.outputs.head_sha }} + run: | + set -euo pipefail + for attempt in $(seq 1 60); do + run_id="$(gh run list --repo "$GITHUB_REPOSITORY" --workflow e2e-advisor.yaml --commit "$HEAD_SHA" --event pull_request --status completed --limit 1 --json databaseId --jq '.[0].databaseId // empty')" + if [ -n "$run_id" ]; then + rm -rf "$RUNNER_TEMP/e2e-advisor" + if gh run download "$run_id" --repo "$GITHUB_REPOSITORY" --name e2e-advisor --dir "$RUNNER_TEMP/e2e-advisor"; then + echo "artifact_dir=$RUNNER_TEMP/e2e-advisor" >> "$GITHUB_OUTPUT" + exit 0 + fi + fi + sleep 15 + done + echo "::error::Exact-head E2E Advisor artifact did not become available" + exit 1 + + - id: start + name: Build exact-head plan and dispatch required live E2E + if: ${{ always() }} + env: + ADVISOR_DIR: ${{ steps.advisor.outputs.artifact_dir }} + BASE_SHA: ${{ steps.resolve.outputs.base_sha }} + CHECK_ID: ${{ steps.initialize.outputs.check_id }} + CI_GREEN: ${{ steps.resolve.outputs.ci_green }} + GITHUB_TOKEN: ${{ github.token }} + HEAD_REPO: ${{ steps.resolve.outputs.head_repo }} + HEAD_SHA: ${{ steps.resolve.outputs.head_sha }} + PR_NUMBER: ${{ steps.resolve.outputs.pr_number }} + run: >- + node --experimental-strip-types tools/e2e-advisor/pr-risk-gate.mts + --mode start + --check-id "$CHECK_ID" + --pr "$PR_NUMBER" + --base "$BASE_SHA" + --head "$HEAD_SHA" + --head-repo "$HEAD_REPO" + --ci-green "$CI_GREEN" + --advisor-dir "$ADVISOR_DIR" + + - name: Wait for correlated live E2E + if: ${{ steps.start.outputs.dispatched == 'true' }} + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ steps.start.outputs.run_id }} + run: timeout --signal=TERM --kill-after=30s 105m gh run watch "$RUN_ID" --repo "$GITHUB_REPOSITORY" --exit-status + + - name: Download correlated evidence + if: ${{ always() && steps.start.outputs.dispatched == 'true' }} + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ steps.start.outputs.run_id }} + run: gh run download "$RUN_ID" --repo "$GITHUB_REPOSITORY" --dir "$RUNNER_TEMP/required-live-evidence" + + - id: finish + name: Complete exact-head required-live check + if: ${{ always() && steps.start.outputs.dispatched == 'true' }} + env: + CHECK_ID: ${{ steps.initialize.outputs.check_id }} + GITHUB_TOKEN: ${{ github.token }} + RUN_ID: ${{ steps.start.outputs.run_id }} + STATE_HASH: ${{ steps.start.outputs.state_hash }} + run: >- + node --experimental-strip-types tools/e2e-advisor/pr-risk-gate.mts + --mode finish + --check-id "$CHECK_ID" + --run-id "$RUN_ID" + --state "$RUNNER_TEMP/required-live-state.json" + --state-hash "$STATE_HASH" + --evidence "$RUNNER_TEMP/required-live-evidence" + + - name: Close required-live check after coordinator failure + if: ${{ always() && steps.initialize.outputs.check_id != '' && steps.finish.outcome != 'success' && (failure() || cancelled()) }} + env: + CHECK_ID: ${{ steps.initialize.outputs.check_id }} + GITHUB_TOKEN: ${{ github.token }} + RUN_ID: ${{ steps.start.outputs.run_id }} + run: >- + node --experimental-strip-types tools/e2e-advisor/pr-risk-gate.mts + --mode abandon --check-id "$CHECK_ID" --run-id "$RUN_ID" diff --git a/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts b/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts index aba649976e9..54037dd5a96 100644 --- a/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts @@ -181,7 +181,7 @@ describe("MCP status wire-level credential-resolution probe", () => { ), ).toBe(true); expect(payload.exitCode).toBe(0); - }); + }, 15_000); it("skips status probe traffic until exact policy and provider readiness are verified (#6379)", () => { const home = createTempHome("nemoclaw-mcp-resolution-readiness-"); diff --git a/test/e2e/README.md b/test/e2e/README.md index 8709ec27630..6c2efe22939 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -92,6 +92,17 @@ scheduled/manual scorecard, including scorecard Slack reporting. Controller or evidence-verification errors close an already-created check as neutral so incomplete evidence cannot appear successful. +For pull requests, `.github/workflows/pr-e2e-risk-gate.yaml` waits for the +exact-head `CI / Pull Request` run to finish while the E2E Advisor runs in +parallel. A green CI result and matching Advisor artifact produce the union of +the deterministic risk floor and Advisor-required jobs. The coordinator +dispatches at most three jobs concurrently through `e2e.yaml` and reports one +`E2E / Required Live` check on the PR head. A new commit immediately cancels +older PR-correlated live runs; exact-head checks in both the coordinator and +child workflow reject stale results. Secret-bearing execution is automatic +only for branches in `NVIDIA/NemoClaw`. Fork PRs receive a non-green approval +boundary instead of exposing repository credentials to fork code. + ## Onboard performance budget The scheduled/manual scorecard evaluates the trusted `cloud-onboard` timing diff --git a/test/e2e/support/e2e-workflow-contract.test.ts b/test/e2e/support/e2e-workflow-contract.test.ts index f84a5511447..b9c2a74d30f 100644 --- a/test/e2e/support/e2e-workflow-contract.test.ts +++ b/test/e2e/support/e2e-workflow-contract.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; -import { removeJobNeed } from "../../helpers/e2e-workflow-contract"; +import { readYaml, removeJobNeed, type Workflow } from "../../helpers/e2e-workflow-contract"; describe("E2E workflow test helpers", () => { it("refuses to remove a dependency from a later job", () => { @@ -26,4 +26,21 @@ describe("E2E workflow test helpers", () => { "owner does not need misplaced", ); }); + + it("binds every checkout to the validated exact revision", () => { + const workflow = readYaml(".github/workflows/e2e.yaml"); + const checkouts = Object.entries(workflow.jobs).flatMap(([jobId, job]) => + (job.steps ?? []) + .filter((step) => step.uses?.startsWith("actions/checkout@")) + .map((step) => ({ jobId, step })), + ); + + expect(checkouts.length).toBeGreaterThan(0); + for (const { jobId, step } of checkouts) { + expect(step.with?.ref, `${jobId} checkout revision`).toBe( + "${{ inputs.checkout_sha || github.sha }}", + ); + expect(step.with?.["persist-credentials"], `${jobId} checkout credentials`).toBe(false); + } + }); }); diff --git a/test/e2e/support/openshell-gateway-upgrade-workflow-boundary.test.ts b/test/e2e/support/openshell-gateway-upgrade-workflow-boundary.test.ts index c64856238fa..cee2a8ef563 100644 --- a/test/e2e/support/openshell-gateway-upgrade-workflow-boundary.test.ts +++ b/test/e2e/support/openshell-gateway-upgrade-workflow-boundary.test.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; +import { readYaml, type Workflow } from "../../helpers/e2e-workflow-contract.ts"; import { evaluateE2eWorkflowDispatchSelectors, readFreeStandingJobsInventory, @@ -52,6 +53,24 @@ describe("OpenShell gateway upgrade workflow boundary", () => { ); }); + it("reclaims deterministic hosted-runner space before building both upgrade images", () => { + const workflow = readYaml(".github/workflows/e2e.yaml"); + const steps = workflow.jobs["openshell-gateway-upgrade"]?.steps ?? []; + const reclaimIndex = steps.findIndex( + (step) => step.name === "Reclaim runner disk for dual-version upgrade images", + ); + const testIndex = steps.findIndex( + (step) => step.name === "Run OpenShell gateway upgrade live Vitest test", + ); + + expect(reclaimIndex).toBeGreaterThan(0); + expect(reclaimIndex).toBeLessThan(testIndex); + expect(steps[reclaimIndex]?.run).toContain( + "sudo rm -rf -- /usr/local/lib/android /usr/share/dotnet /opt/ghc", + ); + expect(steps[reclaimIndex]?.run).toContain("docker system prune --all --force"); + }); + it("freshens only the retryable old fixture install", () => { expect(oldGatewayUpgradeInstallerArgs("old-install.sh")).toEqual([ "old-install.sh", diff --git a/test/post-merge-e2e-risk-gate.test.ts b/test/post-merge-e2e-risk-gate.test.ts index 900d42cc429..488018a11e8 100644 --- a/test/post-merge-e2e-risk-gate.test.ts +++ b/test/post-merge-e2e-risk-gate.test.ts @@ -396,7 +396,53 @@ describe("post-merge E2E risk gate", () => { } }); - it("rejects changed controller state before classifying downloaded evidence", async () => { + it.each([ + { + label: "shadow", + requireSuccess: false, + conclusion: "neutral", + }, + { + label: "required PR", + requireSuccess: true, + conclusion: "failure", + }, + ])("rejects changed controller state as $label", async ({ requireSuccess, conclusion }) => { + const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-risk-state-")); + const statePath = path.join(workDir, "e2e-risk-gate-state.json"); + const originalState = `${JSON.stringify(state())}\n`; + const changedState = `${JSON.stringify({ ...state(), requiresManualExpansion: true })}\n`; + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + fs.writeFileSync(statePath, changedState, { mode: 0o600 }); + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue({ ok: true, text: async () => "{}" } as Response); + + try { + const operation = finishRiskGate({ + statePath, + stateHash: sha256(originalState), + evidencePath: path.join(workDir, "evidence"), + checkRunId: 17, + childRunId: 23, + requireSuccess, + }); + await expect(operation).rejects.toThrow(/controller state changed after E2E dispatch/u); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(String(fetchMock.mock.calls[0]?.[0])).toContain("check-runs/17"); + expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ + status: "completed", + conclusion, + output: { title: "Risk-selected E2E evidence could not be verified" }, + }); + } finally { + fs.rmSync(workDir, { recursive: true, force: true }); + } + }); + + it("returns after a required PR evidence failure is recorded", async () => { const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-risk-state-")); const statePath = path.join(workDir, "e2e-risk-gate-state.json"); const outputPath = path.join(workDir, "github-output"); @@ -419,14 +465,15 @@ describe("post-merge E2E risk gate", () => { evidencePath: path.join(workDir, "evidence"), checkRunId: 17, childRunId: 23, + requireSuccess: true, + returnAfterRecordedFailure: true, }), - ).rejects.toThrow(/controller state changed after E2E dispatch/u); + ).resolves.toBeUndefined(); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("check-runs/17"); expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ status: "completed", - conclusion: "neutral", + conclusion: "failure", output: { title: "Risk-selected E2E evidence could not be verified" }, }); expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)).output.summary).toContain( diff --git a/test/pr-e2e-risk-gate-workflow.test.ts b/test/pr-e2e-risk-gate-workflow.test.ts new file mode 100644 index 00000000000..011b70003a8 --- /dev/null +++ b/test/pr-e2e-risk-gate-workflow.test.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { readYaml, type Workflow, type WorkflowStep } from "./helpers/e2e-workflow-contract"; + +const PATH = ".github/workflows/pr-e2e-risk-gate.yaml"; + +type CoordinatorWorkflow = Workflow & { + permissions: Record; + concurrency: { group: string; "cancel-in-progress": boolean }; +}; + +function namedStep(steps: WorkflowStep[] | undefined, name: string): WorkflowStep { + const result = steps?.find((step) => step.name === name); + expect(result, `missing ${name}`).toBeDefined(); + return result!; +} + +describe("required-live PR coordinator workflow", () => { + it("cancels superseded live runs as soon as a PR head changes", () => { + const workflow = readYaml(PATH); + const job = workflow.jobs["cancel-superseded"]; + const cancel = namedStep(job.steps, "Cancel superseded required-live runs"); + + expect(job.if).toContain("github.event_name == 'pull_request_target'"); + expect(cancel.run).toContain("--mode cancel"); + expect(cancel.run).toContain('--pr "$PR_NUMBER"'); + expect(cancel.run).not.toContain("--head"); + }); + + it("dispatches only after exact-head CI and Advisor planning and always closes its check", () => { + const workflow = readYaml(PATH); + const job = workflow.jobs.coordinate; + const initialize = namedStep(job.steps, "Create exact-head required-live check"); + const resolve = namedStep(job.steps, "Resolve exact PR and CI result"); + const advisor = namedStep(job.steps, "Wait for exact-head Advisor artifacts"); + const start = namedStep(job.steps, "Build exact-head plan and dispatch required live E2E"); + const finish = namedStep(job.steps, "Complete exact-head required-live check"); + const abandon = namedStep(job.steps, "Close required-live check after coordinator failure"); + + expect(workflow.permissions).toEqual({}); + expect(job.permissions).toEqual({ + actions: "write", + checks: "write", + contents: "read", + "pull-requests": "read", + }); + expect(workflow.concurrency?.["cancel-in-progress"]).toBe(true); + expect(initialize.env?.HEAD_SHA).toBe("${{ github.event.workflow_run.head_sha }}"); + expect(initialize.run).toContain("--mode initialize"); + expect(resolve.env?.HEAD_SHA).toBe("${{ github.event.workflow_run.head_sha }}"); + expect(resolve.env?.HEAD_BRANCH).toBe("${{ github.event.workflow_run.head_branch }}"); + expect(advisor.if).toContain("steps.resolve.outputs.ci_green == 'true'"); + expect(advisor.run).toContain('--commit "$HEAD_SHA"'); + expect(start.if).toContain("always()"); + expect(start.env?.CI_GREEN).toBe("${{ steps.resolve.outputs.ci_green }}"); + expect(start.env?.CHECK_ID).toBe("${{ steps.initialize.outputs.check_id }}"); + expect(start.run).toContain('--ci-green "$CI_GREEN"'); + expect(finish.id).toBe("finish"); + expect(finish.if).toContain("always()"); + expect(finish.run).toContain("--mode finish"); + expect(abandon.if).toContain("failure() || cancelled()"); + expect(abandon.if).toContain("steps.finish.outcome != 'success'"); + expect(abandon.env?.RUN_ID).toBe("${{ steps.start.outputs.run_id }}"); + expect(abandon.run).toContain("--mode abandon"); + expect(abandon.run).toContain('--run-id "$RUN_ID"'); + }); + + it("revalidates the exact first-party PR before any live job can receive secrets", () => { + const child = readYaml }>( + ".github/workflows/e2e.yaml", + ); + const generate = child.jobs["generate-matrix"]; + const validation = namedStep(generate.steps, "Validate exact-commit dispatch"); + + expect(child.permissions).toEqual({ contents: "read" }); + expect(generate.permissions).toEqual({ contents: "read", "pull-requests": "read" }); + expect(validation.run).toContain("automatic risk PR must be first-party"); + expect(validation.run).toContain('[[ "$(jq -r .head.sha <<<"$pr_json")" == "$CHECKOUT_SHA" ]]'); + expect(JSON.stringify(generate)).not.toContain("${{ secrets."); + }); +}); diff --git a/test/pr-e2e-risk-gate.test.ts b/test/pr-e2e-risk-gate.test.ts new file mode 100644 index 00000000000..c441db124ba --- /dev/null +++ b/test/pr-e2e-risk-gate.test.ts @@ -0,0 +1,354 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { dispatchRiskWorkflow } from "../tools/e2e-advisor/post-merge-risk-gate.mts"; +import { + abandon, + advisorJobs, + cancel, + initialize, + pullChangedFiles, + resolve, + start, +} from "../tools/e2e-advisor/pr-risk-gate.mts"; + +const temporaryDirectories: string[] = []; + +function artifact(result: unknown): string { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "required-live-advisor-")); + temporaryDirectories.push(directory); + fs.writeFileSync( + path.join(directory, "e2e-target-advisor-result.json"), + `${JSON.stringify(result)}\n`, + { mode: 0o600 }, + ); + const changedFiles = (result as { changedFiles?: string[] }).changedFiles ?? []; + fs.writeFileSync( + path.join(directory, "risk-plan.json"), + `${JSON.stringify({ headSha: "a".repeat(40), changedFiles })}\n`, + { mode: 0o600 }, + ); + return directory; +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + for (const directory of temporaryDirectories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +describe("required-live PR plan", () => { + it("rejects oversized coordinator IDs before any GitHub API request", async () => { + const fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + + await expect(abandon({ checkId: "9007199254740992" })).rejects.toThrow( + "--check-id must be a safe positive integer", + ); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("uses exact-head required jobs and reports selectors that need expansion", () => { + const changedFiles = ["src/lib/onboard.ts"]; + const directory = artifact({ + version: 1, + changedFiles, + required: [ + { id: "onboard-resume", selectorType: "job", required: true }, + { id: "ubuntu-repo-cloud-openclaw", selectorType: "target", required: true }, + { id: "optional-by-contract", selectorType: "job", required: false }, + ], + }); + + expect(advisorJobs(directory, "a".repeat(40), changedFiles)).toEqual({ + jobs: ["onboard-resume"], + unsupported: ["ubuntu-repo-cloud-openclaw"], + }); + }); + + it("rejects an Advisor artifact with a different changed-file set", () => { + const directory = artifact({ + version: 1, + changedFiles: ["src/lib/other.ts"], + required: [], + }); + + expect(() => advisorJobs(directory, "a".repeat(40), ["src/lib/onboard.ts"])).toThrow( + "Advisor result does not match the exact-head risk plan", + ); + }); + + it("rejects an Advisor artifact from another head revision", () => { + const changedFiles = ["src/lib/onboard.ts"]; + const directory = artifact({ version: 1, changedFiles, required: [] }); + + expect(() => advisorJobs(directory, "b".repeat(40), changedFiles)).toThrow( + "Advisor result does not match the exact-head risk plan", + ); + }); + + it("uses GitHub's canonical PR changed-file set instead of a direct commit range", async () => { + const fetchMock = vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify([{ filename: "src/a.ts" }, { filename: "src/b.ts" }])), + ); + vi.stubGlobal("fetch", fetchMock); + + await expect(pullChangedFiles("NVIDIA/NemoClaw", 42, "token")).resolves.toEqual([ + "src/a.ts", + "src/b.ts", + ]); + expect(String(fetchMock.mock.calls[0]?.[0])).toContain("pulls/42/files?per_page=100&page=1"); + }); + + it("binds a PR dispatch to its exact revision and cancellation group", async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + workflow_run_id: 91, + run_url: "https://api.github.com/repos/NVIDIA/NemoClaw/actions/runs/91", + html_url: "https://github.com/NVIDIA/NemoClaw/actions/runs/91", + }), + { status: 200 }, + ), + ); + vi.stubGlobal("fetch", fetchMock); + + await expect( + dispatchRiskWorkflow({ + repository: "NVIDIA/NemoClaw", + token: "token", + jobs: ["onboard-resume"], + commitSha: "a".repeat(40), + planHash: "b".repeat(64), + correlationId: "12345678-1234-4123-8123-123456789abc", + prNumber: 42, + }), + ).resolves.toBe(91); + + const request = fetchMock.mock.calls[0]?.[1] as RequestInit; + expect(JSON.parse(String(request.body))).toMatchObject({ + ref: "main", + inputs: { + checkout_sha: "a".repeat(40), + jobs: "onboard-resume", + pr_number: "42", + risk_pr: "true", + risk_shadow: "true", + }, + }); + }); + + it("creates the stable check before fallible PR resolution", async () => { + const outputFile = path.join(artifact({ changedFiles: [] }), "outputs"); + fs.writeFileSync(outputFile, "", { mode: 0o600 }); + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ id: 17 }))); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + vi.stubEnv("GITHUB_OUTPUT", outputFile); + + await initialize({ head: "a".repeat(40) }); + + expect(fs.readFileSync(outputFile, "utf8")).toBe("check_id=17\n"); + expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ + name: "E2E / Required Live", + head_sha: "a".repeat(40), + status: "in_progress", + }); + }); + + it("resolves the exact workflow head and carries only a successful CI conclusion", async () => { + const outputFile = path.join(artifact({ changedFiles: [] }), "outputs"); + fs.writeFileSync(outputFile, "", { mode: 0o600 }); + const pull = { + number: 42, + state: "open", + head: { sha: "a".repeat(40), repo: { full_name: "NVIDIA/NemoClaw" } }, + base: { sha: "b".repeat(40), repo: { full_name: "NVIDIA/NemoClaw" } }, + }; + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify([pull]))); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + vi.stubEnv("GITHUB_OUTPUT", outputFile); + vi.stubEnv("HEAD_SHA", "a".repeat(40)); + vi.stubEnv("HEAD_REPO", "NVIDIA/NemoClaw"); + vi.stubEnv("HEAD_BRANCH", "feature"); + vi.stubEnv("CI_CONCLUSION", "success"); + + await resolve(); + + expect(String(fetchMock.mock.calls[0]?.[0])).toContain("head=NVIDIA%3Afeature"); + expect(new Set(fs.readFileSync(outputFile, "utf8").trim().split("\n"))).toEqual( + new Set([ + "pr_number=42", + `base_sha=${"b".repeat(40)}`, + `head_sha=${"a".repeat(40)}`, + "head_repo=NVIDIA/NemoClaw", + "first_party=true", + "ci_green=true", + ]), + ); + }); + + it("blocks secret-bearing live execution for fork heads", async () => { + const outputFile = path.join(artifact({ changedFiles: [] }), "outputs"); + fs.writeFileSync(outputFile, "", { mode: 0o600 }); + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + number: 42, + state: "open", + head: { sha: "a".repeat(40), repo: { full_name: "contributor/NemoClaw" } }, + base: { sha: "b".repeat(40), repo: { full_name: "NVIDIA/NemoClaw" } }, + }), + ), + ) + .mockResolvedValueOnce(new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + vi.stubEnv("GITHUB_OUTPUT", outputFile); + + await start({ + checkId: "17", + pr: "42", + base: "b".repeat(40), + head: "a".repeat(40), + headRepo: "contributor/NemoClaw", + ciGreen: "true", + }); + + expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({ + status: "completed", + conclusion: "failure", + output: { title: "Fork live E2E requires a trusted upstream branch" }, + }); + expect(fs.readFileSync(outputFile, "utf8")).toBe("dispatched=false\n"); + }); + + it("blocks dispatch when the PR head changes after exact-head planning", async () => { + const changedFiles = ["src/lib/onboard.ts"]; + const directory = artifact({ version: 1, changedFiles, required: [] }); + const outputFile = path.join(directory, "outputs"); + fs.writeFileSync(outputFile, "", { mode: 0o600 }); + const matchingPull = { + number: 42, + state: "open", + head: { sha: "a".repeat(40), repo: { full_name: "NVIDIA/NemoClaw" } }, + base: { sha: "b".repeat(40), repo: { full_name: "NVIDIA/NemoClaw" } }, + }; + const fetchMock = vi + .fn() + .mockResolvedValueOnce(new Response(JSON.stringify(matchingPull))) + .mockResolvedValueOnce( + new Response(JSON.stringify(changedFiles.map((filename) => ({ filename })))), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + ...matchingPull, + head: { ...matchingPull.head, sha: "c".repeat(40) }, + }), + ), + ) + .mockResolvedValueOnce(new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + vi.stubEnv("GITHUB_OUTPUT", outputFile); + + await start({ + checkId: "17", + pr: "42", + base: "b".repeat(40), + head: "a".repeat(40), + headRepo: "NVIDIA/NemoClaw", + ciGreen: "true", + advisorDir: directory, + }); + + expect(fetchMock).toHaveBeenCalledTimes(4); + expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/dispatches"))).toBe(false); + expect(JSON.parse(String(fetchMock.mock.calls[3]?.[1]?.body))).toMatchObject({ + status: "completed", + conclusion: "failure", + output: { title: "PR head changed before live dispatch" }, + }); + }); + + it("cancels a transitioning child run only once", async () => { + const run = { id: 91, display_title: "E2E PR #42 risk correlation", status: "queued" }; + const fetchMock = vi + .fn() + .mockResolvedValueOnce(new Response(JSON.stringify([run]), { status: 200 })) + .mockResolvedValueOnce( + new Response(JSON.stringify([{ ...run, status: "in_progress" }]), { status: 200 }), + ) + .mockResolvedValueOnce(new Response("", { status: 202 })); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + + await cancel({ pr: "42" }); + + expect(fetchMock).toHaveBeenCalledTimes(3); + expect(String(fetchMock.mock.calls[2]?.[0])).toContain("actions/runs/91/cancel"); + }); + + it("abandons an incomplete gate and cancels its still-running child", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + new Response( + JSON.stringify({ id: 91, display_title: "E2E PR #42 risk id", status: "in_progress" }), + ), + ) + .mockResolvedValueOnce(new Response("", { status: 202 })) + .mockResolvedValueOnce(new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + + await abandon({ checkId: "17", runId: "91" }); + + expect(String(fetchMock.mock.calls[1]?.[0])).toContain("actions/runs/91/cancel"); + expect(String(fetchMock.mock.calls[2]?.[0])).toContain("check-runs/17"); + expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toMatchObject({ + status: "completed", + conclusion: "failure", + }); + }); + + it("closes an abandoned gate even when child cancellation fails", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(new Response(JSON.stringify({ id: 91, status: "in_progress" }))) + .mockResolvedValueOnce(new Response("cancel unavailable", { status: 503 })) + .mockResolvedValueOnce(new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("GITHUB_TOKEN", "token"); + vi.stubEnv("GITHUB_REPOSITORY", "NVIDIA/NemoClaw"); + + await expect(abandon({ checkId: "17", runId: "91" })).rejects.toThrow(); + + expect(String(fetchMock.mock.calls[2]?.[0])).toContain("check-runs/17"); + expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toMatchObject({ + status: "completed", + conclusion: "failure", + }); + }); +}); diff --git a/tools/e2e-advisor/README.md b/tools/e2e-advisor/README.md index 11b6991f91f..57050e7a388 100644 --- a/tools/e2e-advisor/README.md +++ b/tools/e2e-advisor/README.md @@ -75,6 +75,37 @@ requires manual expansion reports neutral. If no runtime risk family matches, it reports success without dispatching E2E. This is post-merge shadow evidence, not a required pre-merge check. +## Required-live PR coordinator + +`.github/workflows/pr-e2e-risk-gate.yaml` publishes one stable +`E2E / Required Live` check for every exact PR head. Normal PR CI and the E2E +Advisor run in parallel. After normal CI succeeds, the coordinator validates +the Advisor artifact against the same head SHA and changed-file set, unions its +supported job selectors with the deterministic risk-plan floor, and dispatches +at most three live jobs. No live job runs after failed normal CI. Unsupported +selectors, an expanded plan, missing or ambiguous evidence, stale revisions, +and controller failures fail closed as a non-green check. + +Every new PR commit immediately cancels older coordinator and child runs. The +child workflow checks out and revalidates the exact approved SHA, +and the controller accepts only the returned child run ID plus evidence bound to +the expected SHA, plan digest, correlation ID, job, and matrix shard. The model +can add coverage but cannot remove the deterministic floor. + +Fork Advisor planning remains automatic and secret-free. Secret-bearing live +execution of fork code is never dispatched: a protected-environment approval +cannot prevent fork code from reading repository-level E2E secrets. When a fork +needs live coverage, a maintainer must review the revision and promote it to a +trusted upstream branch; the normal exact-head CI and coordinator flow then +applies to that upstream revision. + +Rollout is intentionally two-step: observe the check in non-required mode, then +add the exact `E2E / Required Live` name to the `main` ruleset and enable strict +up-to-date required checks. Keep the +post-merge shadow check enabled as defense in depth and review its failures +before cutting a release tag. Repository settings are enforcement controls and +cannot be activated by this pull request alone. + ## Required secret Configure this repository secret for E2E recommendations: diff --git a/tools/e2e-advisor/post-merge-risk-gate.mts b/tools/e2e-advisor/post-merge-risk-gate.mts index cb75b049b3d..6c265917242 100755 --- a/tools/e2e-advisor/post-merge-risk-gate.mts +++ b/tools/e2e-advisor/post-merge-risk-gate.mts @@ -89,6 +89,7 @@ export type RiskGateState = { expectedJobs: string[]; expectedShards: Record; requiresManualExpansion: boolean; + prNumber?: number; }; export type RiskEvidenceVerdict = { @@ -233,6 +234,12 @@ export function validateRiskGateState(value: unknown): RiskGateState { if (typeof value.requiresManualExpansion !== "boolean") { throw new Error("risk-gate manual-expansion state is invalid"); } + if ( + value.prNumber !== undefined && + (!Number.isSafeInteger(value.prNumber) || (value.prNumber as number) < 1) + ) { + throw new Error("risk-gate PR number is invalid"); + } return value as RiskGateState; } @@ -431,17 +438,18 @@ function appendOutput(name: string, value: string): void { } } -async function createCheck( +export async function createCheck( repository: string, token: string, headSha: string, title: string, summary: string, + checkName = CHECK_NAME, ): Promise { const check = await githubApi(`repos/${repository}/check-runs`, token, { method: "POST", body: { - name: CHECK_NAME, + name: checkName, head_sha: headSha, status: "in_progress", output: { title, summary }, @@ -453,7 +461,7 @@ async function createCheck( return check.id; } -async function completeCheck( +export async function completeCheck( context: { repository: string; checkRunId: number }, token: string, verdict: RiskEvidenceVerdict, @@ -483,23 +491,26 @@ function controllerErrorMessage(error: unknown): string { : singleLine; } -async function completeNeutralAfterControllerError( +async function completeAfterControllerError( context: { repository: string; checkRunId: number }, token: string, title: string, - options: { error: unknown; detailsUrl?: string }, + options: { error: unknown; detailsUrl?: string; conclusion?: CheckConclusion }, ): Promise { + const conclusion = options.conclusion ?? "neutral"; const reason = controllerErrorMessage(options.error).replace(/`/gu, "'"); + const summaryPrefix = + conclusion === "failure" + ? "The required-live controller could not produce complete, trustworthy evidence." + : "The shadow controller could not produce complete, trustworthy evidence."; try { await completeCheck( context, token, { - conclusion: "neutral", + conclusion, title, - summary: - "The shadow controller could not produce complete, trustworthy evidence." + - `\n\nController error: \`${reason}\``, + summary: `${summaryPrefix}\n\nController error: \`${reason}\``, }, options.detailsUrl, ); @@ -516,6 +527,7 @@ export function changedFilesBetween( baseSha: string, commitSha: string, workspace = process.cwd(), + requireCheckedOutCommit = true, ): string[] { if (!SHA_PATTERN.test(baseSha) || !SHA_PATTERN.test(commitSha)) { throw new Error("base and tested commits must be lowercase 40-character SHAs"); @@ -525,7 +537,7 @@ export function changedFilesBetween( encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], }).trim(); - if (checkedOutSha !== commitSha) { + if (requireCheckedOutCommit && checkedOutSha !== commitSha) { throw new Error("trusted controller checkout does not match the tested commit"); } const output = execFileSync( @@ -655,6 +667,7 @@ export async function dispatchRiskWorkflow(options: { commitSha: string; planHash: string; correlationId: string; + prNumber?: number; }): Promise { if ( !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(options.repository) || @@ -665,7 +678,9 @@ export async function dispatchRiskWorkflow(options: { options.jobs.some((job) => !JOB_PATTERN.test(job)) || !SHA_PATTERN.test(options.commitSha) || !HASH_PATTERN.test(options.planHash) || - !CORRELATION_PATTERN.test(options.correlationId) + !CORRELATION_PATTERN.test(options.correlationId) || + (options.prNumber !== undefined && + (!Number.isSafeInteger(options.prNumber) || options.prNumber < 1)) ) { throw new Error("risk workflow dispatch inputs are invalid"); } @@ -682,6 +697,8 @@ export async function dispatchRiskWorkflow(options: { risk_plan_hash: options.planHash, risk_correlation: options.correlationId, risk_shadow: "true", + risk_pr: options.prNumber ? "true" : "false", + pr_number: options.prNumber ? String(options.prNumber) : "", }, // GitHub REST 2022-11-28 otherwise returns no run identity. return_run_details: true, @@ -777,7 +794,7 @@ async function start(options: { `Dispatched risk-selected E2E run ${childRunId}: plan=${plan.planHash.slice(0, 12)} selected_jobs=${plan.automaticJobs.join(",")} url=https://github.com/${repository}/actions/runs/${childRunId}`, ); } catch (error) { - const finalized = await completeNeutralAfterControllerError( + const finalized = await completeAfterControllerError( { repository, checkRunId }, token, "Risk-selected E2E could not be dispatched", @@ -849,6 +866,8 @@ export async function finishRiskGate(options: { evidencePath: string; checkRunId: number; childRunId: number; + requireSuccess?: boolean; + returnAfterRecordedFailure?: boolean; }): Promise { const token = process.env.GITHUB_TOKEN ?? ""; const repository = process.env.GITHUB_REPOSITORY ?? ""; @@ -893,17 +912,27 @@ export async function finishRiskGate(options: { signals, requiresManualExpansion: state.requiresManualExpansion, }); - await completeCheck(context, token, verdict, childRunUrl); - console.log(`Completed shadow check: conclusion=${verdict.conclusion} title=${verdict.title}`); + const enforcedVerdict: RiskEvidenceVerdict = + options.requireSuccess && verdict.conclusion !== "success" + ? { ...verdict, conclusion: "failure" } + : verdict; + await completeCheck(context, token, enforcedVerdict, childRunUrl); + console.log( + `Completed ${options.requireSuccess ? "required-live" : "shadow"} check: conclusion=${enforcedVerdict.conclusion} title=${enforcedVerdict.title}`, + ); } catch (error) { - const finalized = await completeNeutralAfterControllerError( + const finalized = await completeAfterControllerError( context, token, "Risk-selected E2E evidence could not be verified", - { error, detailsUrl: childRunUrl }, + { + error, + detailsUrl: childRunUrl, + conclusion: options.requireSuccess ? "failure" : "neutral", + }, ); if (finalized) appendOutput("finalized", "true"); - throw error; + if (!options.returnAfterRecordedFailure || !finalized) throw error; } } diff --git a/tools/e2e-advisor/pr-risk-gate.mts b/tools/e2e-advisor/pr-risk-gate.mts new file mode 100755 index 00000000000..61f43cffc54 --- /dev/null +++ b/tools/e2e-advisor/pr-risk-gate.mts @@ -0,0 +1,438 @@ +#!/usr/bin/env node + +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash, randomUUID } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { githubApi, githubRestPaginated } from "../advisors/github.mts"; +import { parseArgs } from "../advisors/io.mts"; +import { buildRiskPlan } from "../advisors/risk-plan.mts"; +import { readFreeStandingJobsInventory } from "../e2e/workflow-boundary.mts"; +import { + completeCheck, + createCheck, + dispatchRiskWorkflow, + expectedRiskSignalShards, + finishRiskGate, + type RiskGateState, + validateRiskPlan, +} from "./post-merge-risk-gate.mts"; +import { readPrivateRegularFile, writePrivateRegularFile } from "./private-file.ts"; + +const CHECK_NAME = "E2E / Required Live"; +const SHA = /^[a-f0-9]{40}$/u; +const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; +const JOB = /^[A-Za-z0-9][A-Za-z0-9_-]*$/u; + +type Pull = { + number: number; + state: string; + head: { sha: string; repo: { full_name: string } | null }; + base: { sha: string; repo: { full_name: string } }; +}; + +type PullFile = { filename: string }; + +type WorkflowRun = { + id: number; + display_title: string; + status: string; +}; + +type TargetResult = { + version: number; + changedFiles: string[]; + required: Array<{ id: string; selectorType: string; required: boolean }>; +}; + +/** Read and validate the trusted GitHub Actions identity. */ +function tokenAndRepository(): { token: string; repository: string } { + const token = process.env.GITHUB_TOKEN ?? ""; + const repository = process.env.GITHUB_REPOSITORY ?? ""; + if (!token || !REPOSITORY.test(repository)) throw new Error("trusted GitHub context is required"); + return { token, repository }; +} + +/** Require a non-empty command-line value. */ +function required(value: string | undefined, name: string): string { + if (!value) throw new Error(`--${name} is required`); + return value; +} + +/** Parse a positive integer command-line value. */ +function positive(value: string | undefined, name: string): number { + const raw = required(value, name); + if (!/^[1-9][0-9]*$/u.test(raw)) throw new Error(`--${name} must be a positive integer`); + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed)) throw new Error(`--${name} must be a safe positive integer`); + return parsed; +} + +/** Append a bounded, single-line GitHub Actions output. */ +function output(name: string, value: string): void { + if ( + !/^(?:base_sha|check_id|ci_green|dispatched|first_party|head_repo|head_sha|pr_number|run_id|state_hash)$/u.test( + name, + ) + ) { + throw new Error("invalid output name"); + } + const file = process.env.GITHUB_OUTPUT; + if (!file) throw new Error("safe GITHUB_OUTPUT is required"); + const validValue = + name === "base_sha" || name === "head_sha" + ? SHA.test(value) + : name === "state_hash" + ? /^[a-f0-9]{64}$/u.test(value) + : name === "head_repo" + ? REPOSITORY.test(value) + : name === "ci_green" || name === "dispatched" || name === "first_party" + ? /^(?:true|false)$/u.test(value) + : /^[1-9][0-9]*$/u.test(value); + if (!validValue) throw new Error(`invalid ${name} output value`); + const descriptor = fs.openSync( + file, + fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0), + ); + try { + if (!fs.fstatSync(descriptor).isFile()) throw new Error("GITHUB_OUTPUT must be a regular file"); + // GitHub supplies this output file. The name and value are restricted to + // typed controller outputs above, and O_NOFOLLOW rejects link substitution. + // codeql[js/http-to-file-access] + fs.writeFileSync(descriptor, `${name}=${value}\n`, "utf8"); + } finally { + fs.closeSync(descriptor); + } +} + +/** Resolve exactly one open pull request for a workflow-run head. */ +async function findExactPull(headSha: string, headRepo: string, headBranch: string): Promise { + const { token, repository } = tokenAndRepository(); + if (!SHA.test(headSha) || !REPOSITORY.test(headRepo) || !headBranch || /[\r\n]/u.test(headBranch)) + throw new Error("invalid workflow head identity"); + const owner = headRepo.split("/", 1)[0]!; + const pulls = await githubApi( + `repos/${repository}/pulls?state=open&head=${encodeURIComponent(`${owner}:${headBranch}`)}&per_page=100`, + token, + ); + const matches = pulls.filter( + (pull) => + pull.state === "open" && + pull.head.sha === headSha && + pull.head.repo?.full_name === headRepo && + pull.base.repo.full_name === repository, + ); + if (matches.length !== 1) throw new Error(`expected one open PR for ${headRepo}@${headSha}`); + return matches[0]!; +} + +/** Read the canonical changed-file set for the current exact PR revision. */ +export async function pullChangedFiles( + repository: string, + prNumber: number, + token: string, +): Promise { + const files = await githubRestPaginated( + `repos/${repository}/pulls/${prNumber}/files`, + token, + 5001, + ); + if (files.length > 5000) throw new Error("required-live PR exceeds 5000 changed files"); + const changedFiles = files.map((file) => file.filename); + if ( + new Set(changedFiles).size !== changedFiles.length || + changedFiles.some( + (file) => + !file || file.startsWith("/") || file.split("/").includes("..") || /[\r\n]/u.test(file), + ) + ) { + throw new Error("GitHub returned an unsafe required-live changed-file set"); + } + return changedFiles; +} + +/** Create the stable required-live check before fallible PR resolution. */ +export async function initialize(args: Record): Promise { + const { token, repository } = tokenAndRepository(); + const headSha = required(args.head, "head"); + if (!SHA.test(headSha)) throw new Error("invalid required-live head SHA"); + const checkRunId = await createCheck( + repository, + token, + headSha, + "Required live E2E is being planned", + `Exact PR head ${headSha.slice(0, 12)}.`, + CHECK_NAME, + ); + output("check_id", String(checkRunId)); +} + +/** Publish the exact PR identity and triggering CI result. */ +export async function resolve(): Promise { + const headSha = process.env.HEAD_SHA ?? ""; + const headRepo = process.env.HEAD_REPO ?? ""; + const headBranch = process.env.HEAD_BRANCH ?? ""; + const pull = await findExactPull(headSha, headRepo, headBranch); + const { repository } = tokenAndRepository(); + output("pr_number", String(pull.number)); + output("base_sha", pull.base.sha); + output("head_sha", pull.head.sha); + output("head_repo", headRepo); + output("first_party", String(headRepo === repository)); + output("ci_green", String(process.env.CI_CONCLUSION === "success")); +} + +/** Read a bounded private JSON artifact. */ +function readJson(file: string): unknown { + return JSON.parse(readPrivateRegularFile(file, { maxBytes: 1024 * 1024 })!); +} + +/** Validate exact-head Advisor output and return supported required jobs. */ +export function advisorJobs( + advisorDir: string, + headSha: string, + changedFiles: readonly string[], +): { + jobs: string[]; + unsupported: string[]; +} { + const result = readJson(path.join(advisorDir, "e2e-target-advisor-result.json")) as TargetResult; + const artifactPlan = readJson(path.join(advisorDir, "risk-plan.json")) as { + headSha?: unknown; + changedFiles?: unknown; + }; + if ( + artifactPlan.headSha !== headSha || + !Array.isArray(artifactPlan.changedFiles) || + JSON.stringify([...artifactPlan.changedFiles].sort()) !== + JSON.stringify([...changedFiles].sort()) || + result.version !== 1 || + !Array.isArray(result.changedFiles) || + JSON.stringify([...result.changedFiles].sort()) !== JSON.stringify([...changedFiles].sort()) || + !Array.isArray(result.required) + ) { + throw new Error("Advisor result does not match the exact-head risk plan"); + } + const jobs: string[] = []; + const unsupported: string[] = []; + for (const recommendation of result.required) { + if (!recommendation.required || typeof recommendation.id !== "string") continue; + if (recommendation.selectorType === "job" && JOB.test(recommendation.id)) + jobs.push(recommendation.id); + else unsupported.push(recommendation.id); + } + return { jobs: [...new Set(jobs)], unsupported: [...new Set(unsupported)] }; +} + +/** Create the stable check and dispatch an exact-head required-live plan. */ +export async function start(args: Record): Promise { + const { token, repository } = tokenAndRepository(); + const checkRunId = positive(args.checkId, "check-id"); + const prNumber = positive(args.pr, "pr"); + const baseSha = required(args.base, "base"); + const headSha = required(args.head, "head"); + const headRepo = required(args.headRepo, "head-repo"); + if (!SHA.test(baseSha) || !SHA.test(headSha) || !REPOSITORY.test(headRepo)) + throw new Error("invalid PR identity"); + + const pull = await githubApi(`repos/${repository}/pulls/${prNumber}`, token); + if ( + pull.state !== "open" || + pull.base.sha !== baseSha || + pull.head.sha !== headSha || + pull.head.repo?.full_name !== headRepo + ) { + await completeCheck({ repository, checkRunId }, token, { + conclusion: "failure", + title: "PR head was superseded", + summary: "No live E2E was dispatched for a stale PR revision.", + }); + output("dispatched", "false"); + return; + } + if (args.ciGreen !== "true") { + await completeCheck({ repository, checkRunId }, token, { + conclusion: "failure", + title: "Normal CI must pass before live E2E", + summary: + "The exact-head CI run did not complete successfully, so no live jobs were dispatched.", + }); + output("dispatched", "false"); + return; + } + if (headRepo !== repository) { + await completeCheck({ repository, checkRunId }, token, { + conclusion: "failure", + title: "Fork live E2E requires a trusted upstream branch", + summary: + "Advisor planning is automatic, but secret-bearing fork code is never dispatched. A maintainer must promote the reviewed revision to an upstream branch.", + }); + output("dispatched", "false"); + return; + } + + const allowedJobs = new Set(readFreeStandingJobsInventory().allowedJobs); + const changedFiles = await pullChangedFiles(repository, prNumber, token); + const plan = validateRiskPlan(buildRiskPlan({ headSha, changedFiles }), allowedJobs); + const advisorDir = required(args.advisorDir, "advisor-dir"); + const fromAdvisor = advisorJobs(advisorDir, headSha, plan.changedFiles); + const jobs = [...new Set([...plan.automaticJobs, ...fromAdvisor.jobs])]; + const invalidJobs = jobs.filter((job) => !allowedJobs.has(job)); + if ( + fromAdvisor.unsupported.length > 0 || + invalidJobs.length > 0 || + jobs.length > 3 || + plan.requiresManualExpansion + ) { + await completeCheck({ repository, checkRunId }, token, { + conclusion: "failure", + title: "Required live plan needs maintainer expansion", + summary: `Automatic jobs: ${jobs.join(", ") || "none"}. Unsupported selectors: ${fromAdvisor.unsupported.join(", ") || "none"}.`, + }); + output("dispatched", "false"); + return; + } + if (jobs.length === 0) { + await completeCheck({ repository, checkRunId }, token, { + conclusion: "success", + title: "No live E2E required", + summary: "The exact-head deterministic and Advisor plans selected no required live jobs.", + }); + output("dispatched", "false"); + return; + } + + const currentPull = await githubApi(`repos/${repository}/pulls/${prNumber}`, token); + if ( + currentPull.state !== "open" || + currentPull.base.sha !== baseSha || + currentPull.head.sha !== headSha || + currentPull.head.repo?.full_name !== headRepo + ) { + await completeCheck({ repository, checkRunId }, token, { + conclusion: "failure", + title: "PR head changed before live dispatch", + summary: "No live E2E was dispatched because the exact PR revision was superseded.", + }); + output("dispatched", "false"); + return; + } + + const correlationId = randomUUID(); + const executionPlanHash = createHash("sha256") + .update( + JSON.stringify({ + deterministicPlanHash: plan.planHash, + headRepo, + headSha, + jobs: [...jobs].sort(), + prNumber, + }), + ) + .digest("hex"); + const runId = await dispatchRiskWorkflow({ + repository, + token, + jobs, + commitSha: headSha, + planHash: executionPlanHash, + correlationId, + prNumber, + }); + // Publish the trusted API response immediately so the always-run cleanup can + // cancel the child even if local state persistence fails afterward. + output("run_id", String(runId)); + const state: RiskGateState = { + version: 1, + commitSha: headSha, + planHash: executionPlanHash, + correlationId, + expectedJobs: jobs, + expectedShards: expectedRiskSignalShards(jobs), + requiresManualExpansion: false, + prNumber, + }; + const serialized = `${JSON.stringify(state, null, 2)}\n`; + const statePath = path.join(process.env.RUNNER_TEMP ?? "", "required-live-state.json"); + writePrivateRegularFile(statePath, serialized); + output("state_hash", createHash("sha256").update(serialized).digest("hex")); + output("dispatched", "true"); +} + +/** Close an incomplete gate and stop its correlated child when still active. */ +export async function abandon(args: Record): Promise { + const { token, repository } = tokenAndRepository(); + const runId = args.runId ? positive(args.runId, "run-id") : undefined; + try { + if (runId) { + const child = await githubApi( + `repos/${repository}/actions/runs/${runId}`, + token, + ); + if (child.status === "queued" || child.status === "in_progress") { + await githubApi(`repos/${repository}/actions/runs/${runId}/cancel`, token, { + method: "POST", + }); + } + } + } finally { + await completeCheck({ repository, checkRunId: positive(args.checkId, "check-id") }, token, { + conclusion: "failure", + title: "Required live E2E coordinator stopped early", + summary: "The coordinator could not produce complete exact-head evidence.", + }); + } +} + +/** Cancel queued or running required-live children for a superseded PR head. */ +export async function cancel(args: Record): Promise { + const { token, repository } = tokenAndRepository(); + const prNumber = positive(args.pr, "pr"); + const prefix = `E2E PR #${prNumber} risk `; + const matchingRuns = new Map(); + for (const status of ["queued", "in_progress"]) { + const runs = await githubRestPaginated( + `repos/${repository}/actions/workflows/e2e.yaml/runs?event=workflow_dispatch&status=${status}`, + token, + 100, + ); + for (const run of runs.filter((candidate) => candidate.display_title.startsWith(prefix))) { + matchingRuns.set(run.id, run); + } + } + for (const run of matchingRuns.values()) { + await githubApi(`repos/${repository}/actions/runs/${run.id}/cancel`, token, { method: "POST" }); + } +} + +/** Route the requested coordinator mode. */ +async function main(): Promise { + const args = parseArgs(process.argv.slice(2)); + if (args.mode === "initialize") return initialize(args); + if (args.mode === "resolve") return resolve(); + if (args.mode === "cancel") return cancel(args); + if (args.mode === "start") return start(args); + if (args.mode === "abandon") return abandon(args); + if (args.mode === "finish") { + return finishRiskGate({ + statePath: required(args.state, "state"), + stateHash: required(args.stateHash, "state-hash"), + evidencePath: required(args.evidence, "evidence"), + checkRunId: positive(args.checkId, "check-id"), + childRunId: positive(args.runId, "run-id"), + requireSuccess: true, + returnAfterRecordedFailure: true, + }); + } + throw new Error("--mode must be initialize, resolve, cancel, start, finish, or abandon"); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + }); +}