diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index a9dd088ee8..d41133b90a 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -4,7 +4,7 @@ self-hosted-runner: # GitHub Actions added concurrency.queue in May 2026. The repository-pinned # actionlint release does not parse it, so suppress only that known parser lag -# in workflows that use the shared preview lifecycle queue. +# only in workflows explicitly using this documented queue option. paths: .github/workflows/preview.yml: ignore: @@ -15,6 +15,11 @@ paths: .github/workflows/hosted-identity-request.yml: ignore: - 'unexpected key "queue" for "concurrency" section' + .github/workflows/runtime-images.yml: + ignore: + - 'unexpected key "queue" for "concurrency" section' + # Provider-supported job cache permissions validated by the runtime image contract. + - 'unexpected key "cache-mode" for "job" section' .github/workflows/preview-cleanup-proof.yml: ignore: - 'unexpected key "queue" for "concurrency" section' diff --git a/.github/actions/preserve-required-gate/assess-required-gate.sh b/.github/actions/preserve-required-gate/assess-required-gate.sh index f76d200da7..0c6f8fec3d 100644 --- a/.github/actions/preserve-required-gate/assess-required-gate.sh +++ b/.github/actions/preserve-required-gate/assess-required-gate.sh @@ -344,12 +344,12 @@ while IFS=$'\t' read -r app_slug check_name details_url check_run_id check_statu --arg expected_pr "${PR_NUMBER}" \ --arg expected_display_title "${expected_display_title}" \ '. as $run - | ((try (.display_title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$")) catch null) // {}) as $title + | ((try (.display_title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})( merge-[0-9A-Fa-f]{40} mode-(required|metadata))?$")) catch null) // {}) as $title | if ($run.id | type) == "number" and ($run.workflow_id | type) == "number" and ($run.id == ($expected_id | tonumber)) and ($run.workflow_id == ($expected_workflow_id | tonumber)) and - ($run.name == $expected_name or $run.name == $expected_display_title) and + ($run.name == $expected_name or (($run.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == $expected_display_title) and ( $run.path == $expected_path or ( @@ -365,10 +365,10 @@ while IFS=$'\t' read -r app_slug check_name details_url check_run_id check_statu (($run.pull_requests | length) > 0 and any($run.pull_requests[]; ((.number // null) | tostring) == $expected_pr)) or (($run.pull_requests | length) == 0 and - ($run.display_title // null) == $expected_display_title) + (($run.display_title // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == $expected_display_title) ) then - if ($run.display_title // null) == $expected_display_title then + if (($run.display_title // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == $expected_display_title then "current" elif (($run.pull_requests | length) > 0) and $title.name == $expected_name and $title.pr == $expected_pr and @@ -439,7 +439,7 @@ while IFS=$'\t' read -r app_slug check_name details_url check_run_id check_statu .run_id == ($expected_run_id | tonumber) and .name == $expected_gate_name and (.workflow_name == $expected_workflow_name or - .workflow_name == $expected_display_title) and + ((.workflow_name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == $expected_display_title) and .head_sha == $expected_head and ((.check_run_url // "") | endswith("/check-runs/\($expected_check_run_id)")) then "true" else "false" end' \ diff --git a/.github/actions/preserve-required-gate/resolve-deferred-gate.sh b/.github/actions/preserve-required-gate/resolve-deferred-gate.sh index ddcedb01e3..6d32da1638 100644 --- a/.github/actions/preserve-required-gate/resolve-deferred-gate.sh +++ b/.github/actions/preserve-required-gate/resolve-deferred-gate.sh @@ -35,7 +35,7 @@ case "${workflow_file}" in .github/workflows/security.yml) workflow_name='Security Gate'; gate_name='Security Gate' ;; .github/workflows/codeql.yml) workflow_name='CodeQL Analysis'; gate_name='CodeQL Gate' ;; .github/workflows/license-scan.yml) workflow_name='License Gate'; gate_name='License Gate' ;; - .github/workflows/smoke.yml) workflow_name='PR Smoke Gate'; gate_name='Smoke Gate' ;; + .github/workflows/runtime-images.yml) workflow_name='Build Runtime Images'; gate_name='Smoke Gate' ;; *) fail_closed "Source does not own a supported required gate." ;; esac workflow_filename="${workflow_file##*/}" @@ -45,7 +45,7 @@ workflow_id="$(jq -er --arg name "${workflow_name}" --arg path "${workflow_file} | .id | select(type == "number" and . > 0 and . == floor)' <<<"${workflow_json}")" source_title="$(jq -er '.display_title' <<<"${source_json}")" title_identity="$(jq -ern --arg title "${source_title}" --arg name "${workflow_name}" ' - $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") + $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})( merge-[0-9A-Fa-f]{40} mode-(required|metadata))?$") | select(.name == $name) | [.pr, .base, .head] | @tsv')" IFS=$'\t' read -r pr_number base_sha head_sha <<<"${title_identity}" head_branch="$(jq -er '.head_branch | select(type == "string" and length > 0)' <<<"${source_json}")" @@ -53,7 +53,7 @@ jq -e --argjson id "${source_run_id}" --argjson workflow_id "${workflow_id}" \ --arg repository "${GITHUB_REPOSITORY}" --arg name "${workflow_name}" \ --arg title "${source_title}" --arg path "${workflow_file}" --arg head "${head_sha}" ' .id == $id and .workflow_id == $workflow_id and - (.name == $name or .name == $title) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and .repository.full_name == $repository and .event == "pull_request" and .status == "completed" and .head_sha == $head' <<<"${source_json}" >/dev/null || @@ -102,7 +102,7 @@ jq -e --argjson id "${GITHUB_RUN_ID}" --argjson workflow_id "${resolver_id}" \ .id == $id and .workflow_id == $workflow_id and .repository.full_name == $repository and .event == "workflow_run" and (.name == "Resolve Required Gates" or .name == $title) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .display_title == $title and .run_attempt == 1 and .status == "in_progress" and + (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and .run_attempt == 1 and .status == "in_progress" and (.head_sha | type) == "string" and (.head_sha | test("^[0-9A-Fa-f]{40}$")) and (try (.created_at | fromdateiso8601 | type == "number") catch false)' <<<"${current_resolver_json}" >/dev/null || fail_closed "Current resolver identity or first attempt is unproved; explicit recovery is required." @@ -151,7 +151,7 @@ if [[ "${resolution_phase}" == reconcile ]]; then target="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${bridge_run_id}/attempts/${bridge_attempt}")" || return 1 historical_title="$(jq -er --arg name "${workflow_name}" --arg pr "${pr_number}" --arg head "${head_sha}" ' .display_title as $value | $value - | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") + | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})( merge-[0-9A-Fa-f]{40} mode-(required|metadata))?$") | select(.name == $name and .pr == $pr and .head == $head) | $value' <<<"${target}")" || return 1 jq -e --argjson id "${bridge_run_id}" --argjson attempt "${bridge_attempt}" \ --argjson workflow "${workflow_id}" --arg repo "${GITHUB_REPOSITORY}" \ @@ -159,8 +159,8 @@ if [[ "${resolution_phase}" == reconcile ]]; then --arg title "${historical_title}" --arg name "${workflow_name}" --arg path "${workflow_file}" --argjson pr "${pr_number}" ' .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and .repository.full_name == $repo and .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - (.name == $name or .name == $title) and + .head_sha == $head and .head_branch == $branch and (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and .event == "pull_request" and ((.status == "completed" and (.conclusion | type == "string" and length > 0)) or @@ -241,8 +241,8 @@ if [[ "${resolution_phase}" == reconcile ]]; then --arg path "${workflow_file}" --argjson pr "${pr_number}" ' .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and .repository.full_name == $repo and .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - (.name == $name or .name == $title) and + .head_sha == $head and .head_branch == $branch and (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and .event == "pull_request" and .status == "completed" and (.pull_requests | type == "array") and ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr))' <<<"${run}" >/dev/null || return 1 @@ -527,10 +527,10 @@ deferred_job_identity() { --arg name "${workflow_name}" --arg path "${workflow_file}" --argjson pr "${pr_number}" \ --arg resolver_created "${current_resolver_created}" ' .id == $id and .workflow_id == $workflow_id and - (.name == $name or .name == $title) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and .repository.full_name == $repository and .head_repository.full_name == $head_repository and - .head_sha == $head and .head_branch == $branch and .display_title == $title and + .head_sha == $head and .head_branch == $branch and (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and .event == "pull_request" and .status == "completed" and .conclusion == "failure" and .run_attempt == 1 and (.created_at | type) == "string" and (try ((.created_at | fromdateiso8601) <= ($resolver_created | fromdateiso8601)) catch false) and diff --git a/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh b/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh index b68cd0889c..f308ab53d7 100644 --- a/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh +++ b/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh @@ -54,9 +54,9 @@ jq -e --argjson id "$run_id" --argjson attempt "$attempt" --argjson workflow "$w --arg path "$workflow_path" --arg title "$display_title" --arg branch "$head_branch" \ --arg head "$head_sha" --arg base "$base_sha" --argjson pr "$pr_number" ' .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and - (.name == $name or .name == $title) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .display_title == $title and .repository.full_name == $repo and + (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and .repository.full_name == $repo and .head_repository.full_name == $head_repo and .head_sha == $head and .head_branch == $branch and .event == "pull_request" and .status == "completed" and (.pull_requests | type) == "array" and @@ -83,7 +83,7 @@ attempt_job="$(jq -cer --argjson run "$run_id" --argjson attempt "$attempt" --ar any($jobs[]; type != "object" or (.id | type) != "number" or .id < 1 or .id != (.id | floor)) or ([$jobs[].id] | unique | length) != $total or any($jobs[]; .run_id != $run or .run_attempt != $attempt or .head_sha != $head or .head_branch != $branch or - (.workflow_name != $name and .workflow_name != $title) or + (.workflow_name != $name and ((.workflow_name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) != ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) or ((.check_run_url // "") | startswith("https://api.github.com/repos/" + $repo + "/check-runs/") | not) or (((.check_run_url // "") | ltrimstr("https://api.github.com/repos/" + $repo + "/check-runs/")) | test("^[1-9][0-9]*$") | not)) then @@ -98,7 +98,7 @@ attempt_job="$(jq -cer --argjson run "$run_id" --argjson attempt "$attempt" --ar | ($selected.html_url // "") as $html | ("https://github.com/" + $repo + "/actions/runs/" + ($run | tostring) + "/job/") as $prefix | if .name != $gate or .run_id != $run or .run_attempt != $attempt or .head_sha != $head or - (.workflow_name != $name and .workflow_name != $title) or + (.workflow_name != $name and ((.workflow_name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) != ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) or .check_run_url != ("https://api.github.com/repos/" + $repo + "/check-runs/" + ($check | tostring)) or (($html | startswith($prefix)) | not) or (($html | ltrimstr($prefix) | (try capture("^(?[1-9][0-9]*)([?#].*)?$").id catch "")) != ($job | tostring)) or diff --git a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh b/.github/actions/publish-required-gate-status/publish-required-gate-status.sh index ae09f293a3..91b64dbab5 100644 --- a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh +++ b/.github/actions/publish-required-gate-status/publish-required-gate-status.sh @@ -18,7 +18,7 @@ case "${EXPECTED_WORKFLOW_FILE}" in security.yml) workflow_name='Security Gate'; gate_name='Security Gate' ;; codeql.yml) workflow_name='CodeQL Analysis'; gate_name='CodeQL Gate' ;; license-scan.yml) workflow_name='License Gate'; gate_name='License Gate' ;; - smoke.yml) workflow_name='PR Smoke Gate'; gate_name='Smoke Gate' ;; + runtime-images.yml) workflow_name='Build Runtime Images'; gate_name='Smoke Gate' ;; *) fail_closed "Unsupported required gate workflow." ;; esac [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/${EXPECTED_WORKFLOW_FILE}" && @@ -82,7 +82,7 @@ native_identity() { fi title="$(jq -er '.display_title | select(type == "string")' <<<"${run}")" || return 1 title_base="$(jq -ern --arg title "${title}" --arg name "${workflow_name}" --arg pr "${PR_NUMBER}" --arg head "${HEAD_SHA}" ' - $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") + $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})( merge-[0-9A-Fa-f]{40} mode-(required|metadata))?$") | select(.name == $name and .pr == $pr and .head == $head) | .base')" || return 1 [[ "${current}" != true && "${require_current_base}" != true || "${title_base}" == "${BASE_SHA}" ]] || return 1 jq -e --argjson id "${run_id}" --argjson attempt "${attempt}" --argjson workflow "${workflow_id}" \ @@ -96,8 +96,8 @@ native_identity() { .run_number < $current_number or (.run_number == $current_number and .id == $current_run and .run_attempt <= $current_attempt) end) and .repository.full_name == $repo and .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - (.name == $name or .name == $title) and + .head_sha == $head and .head_branch == $branch and (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and (.pull_requests | type == "array") and ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr)) and @@ -162,9 +162,9 @@ jq -e --arg title "${current_title}" --argjson id "${GITHUB_RUN_ID}" --argjson a --arg path "${EXPECTED_WORKFLOW_PATH}" --argjson pr "${PR_NUMBER}" ' .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and .repository.full_name == $repo and (.run_number | type == "number" and . > 0 and . == floor) and - .event == "pull_request" and .display_title == $title and .head_sha == $head and + .event == "pull_request" and (.display_title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) and .head_sha == $head and .head_repository.full_name == $head_repo and .head_branch == $branch and - (.name == $name or .name == $title) and + (.name == $name or ((.name // "") | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; "")) == ($title | sub(" merge-[0-9A-Fa-f]{40} mode-(required|metadata)$"; ""))) and (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and (.pull_requests | type == "array") and ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr)) and diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7725d5a949..509949f93b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -519,6 +519,17 @@ jobs: if: ${{ needs.changes.outputs.lightweight_only != 'true' }} uses: ./.github/actions/setup-helm + - name: Set up Java for Gradle task-graph contracts + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: temurin + java-version: '25' + + - name: Set up Gradle for task-graph contracts + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + - name: ๐Ÿงช Validate dev tool contracts if: ${{ needs.changes.outputs.lightweight_only != 'true' }} run: | @@ -543,8 +554,6 @@ jobs: time bash ./dev-tools/tests/testcontainers-disabled-contract.sh TIMEFORMAT='bash ./dev-tools/tests/pr-retarget-workflow-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/pr-retarget-workflow-contract.sh - TIMEFORMAT='bash ./dev-tools/tests/static-analysis-summary-contract.sh: real=%3R user=%3U sys=%3S' - time bash ./dev-tools/tests/static-analysis-summary-contract.sh TIMEFORMAT='bash ./dev-tools/tests/ci-validation-summary-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/ci-validation-summary-contract.sh TIMEFORMAT='bash ./dev-tools/tests/security-summary-contract.sh: real=%3R user=%3U sys=%3S' @@ -573,6 +582,12 @@ jobs: time bash ./dev-tools/tests/postgres-runtime-upgrade-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-runner-isolation-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/preview-runner-isolation-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/privileged-workflow-policy-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/privileged-workflow-policy-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/required-gate-names-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/required-gate-names-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/play-waiver-guard-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/play-waiver-guard-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-standalone-transport-certificates-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/preview-standalone-transport-certificates-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-ca-recovery-contract.sh: real=%3R user=%3U sys=%3S' @@ -617,6 +632,8 @@ jobs: time bash ./dev-tools/tests/preview-image-tag-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-merge-image-tag-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/preview-merge-image-tag-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/wait-for-runtime-images-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/wait-for-runtime-images-contract.sh TIMEFORMAT='bash ./dev-tools/tests/overlay-preflight-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/overlay-preflight-contract.sh TIMEFORMAT='bash ./dev-tools/tests/validate-external-credentials-contract.sh: real=%3R user=%3U sys=%3S' diff --git a/.github/workflows/dev-demo.yml b/.github/workflows/dev-demo.yml index e2e6fb808b..5dd225fcd6 100644 --- a/.github/workflows/dev-demo.yml +++ b/.github/workflows/dev-demo.yml @@ -82,10 +82,13 @@ jobs: if [ -z "$IMAGE_TAG" ]; then IMAGE_TAG="${HEAD_SHA}" fi - if [[ -z "$IMAGE_TAG" || ! "$IMAGE_TAG" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then - echo "::error title=Invalid dev-demo image tag::Expected a non-empty tag of at most 128 safe characters." >&2 + # Mutable aliases can point at another commit's images, so a deploy + # accepts only the exact head's immutable SHA tag. Destroy ignores it. + if [[ "$ACTION" == "deploy" && "${IMAGE_TAG,,}" != "$HEAD_SHA" ]]; then + echo "::error title=Invalid dev-demo image tag::The image tag must be the deploy head SHA." >&2 exit 1 fi + IMAGE_TAG="$HEAD_SHA" if [[ "$HOSTNAME" != "dev.preview.firedevops.net" ]]; then echo "::error title=Invalid dev-demo hostname::Expected the canonical dev.preview.firedevops.net hostname." >&2 exit 1 @@ -222,6 +225,18 @@ jobs: echo "::error title=Missing Hosted identity requester credentials::Dev-demo deploy requires TRUSTED_HOSTED_IDENTITY_REQUESTER_KUBECONFIG when hosted-controller mode is enabled." >&2 exit 1 + # Wait for the exact image set before resetting, so a failed registry + # lookup leaves the working deployment in place. + - name: Wait for develop runtime images + if: ${{ steps.cluster-access.outputs.available == 'true' }} + env: + GH_TOKEN: ${{ github.token }} + PREVIEW_GHCR_USERNAME: ${{ secrets.TRUSTED_HOSTED_PREVIEW_GHCR_USERNAME }} + PREVIEW_GHCR_TOKEN: ${{ secrets.TRUSTED_HOSTED_PREVIEW_GHCR_TOKEN }} + run: | + echo "DEV_DEMO_STAGE=wait-for-images" >> "$GITHUB_ENV" + bash ./dev-tools/hosted/shared/wait-for-runtime-images.sh "${{ needs.dev-demo-plan.outputs.image_tag }}" + - name: Reset dev-demo namespace for clean deploy if: ${{ steps.cluster-access.outputs.available == 'true' && steps.v2-migration-mode.outputs.activation != 'true' }} env: @@ -325,14 +340,6 @@ jobs: run: | bash ./dev-tools/hosted/shared/ensure-ghcr-pull-secret.sh "${{ needs.dev-demo-plan.outputs.namespace }}" - - name: Wait for develop runtime images - if: ${{ steps.cluster-access.outputs.available == 'true' }} - env: - GH_TOKEN: ${{ github.token }} - run: | - echo "DEV_DEMO_STAGE=wait-for-images" >> "$GITHUB_ENV" - bash ./dev-tools/hosted/shared/wait-for-runtime-images.sh "${{ needs.dev-demo-plan.outputs.image_tag }}" - - name: Prepare dev-demo shared gRPC TLS secret if: ${{ steps.cluster-access.outputs.available == 'true' && steps.certificate-identity.outputs.mode == 'standalone' }} env: diff --git a/.github/workflows/erd.yml b/.github/workflows/erd.yml index 99db28e170..bcbabefe88 100644 --- a/.github/workflows/erd.yml +++ b/.github/workflows/erd.yml @@ -32,6 +32,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }} + persist-credentials: false - name: โš™๏ธ Set Up Java uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6 diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index 60139fc4bf..c6ca07d708 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -16,7 +16,8 @@ permissions: jobs: validate-target: name: Validate Trusted Preview Target - if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.name == 'PR Preview Environment' && (github.event.workflow_run.event == 'pull_request_target' || github.event.workflow_run.event == 'repository_dispatch')) || (github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository) }} + # GitHub-hosted runners need a separate cluster network path and credentials first. + if: ${{ vars.PREVIEW_GITHUB_HOSTED_CLUSTER_ACCESS == 'true' && ((github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.name == 'PR Preview Environment' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch')) || (github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository)) }} timeout-minutes: 10 runs-on: ubuntu-latest permissions: @@ -131,14 +132,23 @@ jobs: } SOURCE_RUN_ID="$WORKFLOW_RUN_ID" workflow_run_json="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}")" - require_source_field path '.github/workflows/preview.yml' "$(jq -r '.path // empty' <<<"$workflow_run_json")" + SOURCE_EVENT="$(jq -r '.event // empty' <<<"$workflow_run_json")" + source_path="$(jq -r '.path // empty' <<<"$workflow_run_json")" + source_path_pr="" + if [[ "$SOURCE_EVENT" == pull_request && + "$source_path" =~ ^[.]github/workflows/preview[.]yml@refs/pull/([1-9][0-9]{0,50})/merge$ ]]; then + source_path_pr="${BASH_REMATCH[1]}" + elif [[ "$SOURCE_EVENT" != repository_dispatch || + ( "$source_path" != ".github/workflows/preview.yml@$DEFAULT_BRANCH" && + "$source_path" != ".github/workflows/preview.yml@refs/heads/$DEFAULT_BRANCH" ) ]]; then + require_source_field path '.github/workflows/preview.yml' "$source_path" + fi require_source_field conclusion success "$(jq -r '.conclusion // empty' <<<"$workflow_run_json")" require_source_field repository "$GITHUB_REPOSITORY" \ "$(jq -r '.repository.full_name // empty' <<<"$workflow_run_json")" require_source_field head "$WORKFLOW_RUN_HEAD_SHA" \ "$(jq -r '.head_sha // empty' <<<"$workflow_run_json")" - SOURCE_EVENT="$(jq -r '.event // empty' <<<"$workflow_run_json")" - [[ "$SOURCE_EVENT" == pull_request_target || "$SOURCE_EVENT" == repository_dispatch ]] || + [[ "$SOURCE_EVENT" == pull_request || "$SOURCE_EVENT" == repository_dispatch ]] || emit_no_action "Ignoring source run with unsupported event ${SOURCE_EVENT}." if [[ "$SOURCE_EVENT" == repository_dispatch ]]; then require_source_field head-branch "$DEFAULT_BRANCH" \ @@ -161,8 +171,8 @@ jobs: ARTIFACT_KIND=intent ACTION=destroy fi - if [[ "$SOURCE_EVENT" == pull_request_target && "$ARTIFACT_KIND" != render ]]; then - emit_no_action "Ignoring pull_request_target source without a render artifact." + if [[ "$SOURCE_EVENT" == pull_request && "$ARTIFACT_KIND" != render ]]; then + emit_no_action "Ignoring pull_request source without a render artifact." fi download_source_artifact "$ARTIFACT_NAME" if [[ "$ARTIFACT_KIND" == render ]]; then @@ -179,6 +189,19 @@ jobs: EXPECTED_HEAD_SHA="$(jq -er '.headSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" ARTIFACT_BASE_SHA="$(jq -er '.baseSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" ARTIFACT_MERGE_SHA="$(jq -er '.mergeSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" + if [[ "$SOURCE_EVENT" == pull_request ]]; then + # A pull_request run is PR-authored. Only GitHub's own association + # (or its refs/pull path when the association is empty) binds the + # artifact's PR number; the live checks below bind the tuple. + [[ -z "$source_path_pr" || "$source_path_pr" == "$PR_NUMBER" ]] || + emit_no_action "Ignoring artifact not bound to the source path pull request." + jq -e --argjson pr "$PR_NUMBER" --arg head "$EXPECTED_HEAD_SHA" --arg qualified "$source_path_pr" ' + if (.pull_requests | length) == 0 then $qualified == ($pr | tostring) and .head_sha == $head + else ([.pull_requests[] | select(.number == $pr and .head.sha == $head)] | length) == 1 + end + ' <<<"$workflow_run_json" >/dev/null || + emit_no_action "Ignoring artifact not bound to the source run pull request and head." + fi else require_exact_files "preview-intent.json" intent_output="$(python3 ./dev-tools/hosted/preview/validate-preview-intent.py \ @@ -404,11 +427,7 @@ jobs: prepare-runtime: name: Prepare Validated Preview Inputs timeout-minutes: 45 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest needs: validate-target if: ${{ needs.validate-target.outputs.action == 'deploy' }} environment: trusted-hosted-cluster @@ -473,6 +492,8 @@ jobs: if: ${{ needs.validate-target.outputs.image_tag != needs.validate-target.outputs.base_sha }} env: GH_TOKEN: ${{ github.token }} + PREVIEW_GHCR_USERNAME: ${{ secrets.TRUSTED_HOSTED_PREVIEW_GHCR_USERNAME }} + PREVIEW_GHCR_TOKEN: ${{ secrets.TRUSTED_HOSTED_PREVIEW_GHCR_TOKEN }} run: | bash ./dev-tools/hosted/shared/wait-for-runtime-images.sh \ "${{ needs.validate-target.outputs.merge_sha }}" \ @@ -532,11 +553,7 @@ jobs: # projection, and deployment; the pre-apply projection wait is bounded to # 15 minutes. timeout-minutes: 45 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest needs: [validate-target, prepare-runtime] if: ${{ needs.validate-target.outputs.action == 'deploy' && needs.prepare-runtime.result == 'success' }} outputs: @@ -1172,11 +1189,7 @@ jobs: verify-runtime: name: Verify Hosted Preview Runtime timeout-minutes: 60 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest needs: [validate-target, deploy-runtime] if: ${{ needs.validate-target.outputs.action == 'deploy' && needs.deploy-runtime.result == 'success' && needs.deploy-runtime.outputs.allocation_status == 'allocated' }} environment: trusted-hosted-cluster @@ -1467,11 +1480,7 @@ jobs: publish-preview-proof: name: Publish Verified Hosted Preview Proof timeout-minutes: 20 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest needs: [validate-target, deploy-runtime, verify-runtime] if: ${{ needs.validate-target.outputs.action == 'deploy' && needs.deploy-runtime.result == 'success' && needs.deploy-runtime.outputs.allocation_status == 'allocated' && needs.verify-runtime.result == 'success' }} environment: trusted-hosted-cluster @@ -1683,11 +1692,7 @@ jobs: destroy-runtime: name: Delete Preview Runtime timeout-minutes: 60 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest needs: validate-target # Close cleanup is mode-independent: a retained identity may have been created # before the default-branch certificate identity mode changed. @@ -1804,11 +1809,7 @@ jobs: retire-identity: name: Retire Hosted Identity After Runtime Deletion timeout-minutes: 60 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest needs: [validate-target, destroy-runtime] if: ${{ needs.validate-target.outputs.action == 'destroy' && needs.validate-target.outputs.retire_identity == 'true' && needs.destroy-runtime.result == 'success' }} environment: trusted-hosted-cluster diff --git a/.github/workflows/preview-cleanup-proof.yml b/.github/workflows/preview-cleanup-proof.yml index 29253cd4de..5f917fb29b 100644 --- a/.github/workflows/preview-cleanup-proof.yml +++ b/.github/workflows/preview-cleanup-proof.yml @@ -134,11 +134,12 @@ jobs: [[ "$observed_uid" == "$EXPECTED_NAMESPACE_UID" ]] || fail "namespace UID changed" } - # Recheck both external identities immediately before the existing UID-fenced delete helper. + # The delete helper also verifies the proof marker on its resourceVersion-fenced read. verify_closed_pr verify_fixture_namespace - bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh \ - --delete-runtime "$namespace" "$EXPECTED_NAMESPACE_UID" + PREVIEW_REQUIRE_CLEANUP_PROOF=true \ + bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh \ + --delete-runtime "$namespace" "$EXPECTED_NAMESPACE_UID" remaining="$(kubectl get namespace "$namespace" --ignore-not-found -o name)" || fail "could not verify namespace deletion" diff --git a/.github/workflows/preview-janitor.yml b/.github/workflows/preview-janitor.yml index d355fa51f8..5e07cd540a 100644 --- a/.github/workflows/preview-janitor.yml +++ b/.github/workflows/preview-janitor.yml @@ -52,9 +52,11 @@ jobs: path: ${{ runner.temp }}/preview-namespace-manager.kubeconfig export-to-github-env: 'false' + # Checked in every mode: an identity kept from hosted-controller mode must + # still retire after the switch to standalone or while hosted close cleanup + # is gated off with PREVIEW_GITHUB_HOSTED_CLUSTER_ACCESS. - name: Check hosted identity requester credentials id: requester-credentials - if: ${{ steps.certificate-identity.outputs.mode == 'hosted-controller' }} env: REQUESTER_KUBECONFIG: ${{ secrets.TRUSTED_HOSTED_IDENTITY_REQUESTER_KUBECONFIG }} run: | @@ -67,7 +69,7 @@ jobs: fi - name: Write hosted identity requester kubeconfig - if: ${{ steps.certificate-identity.outputs.mode == 'hosted-controller' && steps.requester-credentials.outputs.available == 'true' }} + if: ${{ steps.requester-credentials.outputs.available == 'true' }} uses: ./.github/actions/write-kubeconfig with: content: ${{ secrets.TRUSTED_HOSTED_IDENTITY_REQUESTER_KUBECONFIG }} @@ -92,22 +94,18 @@ jobs: run: | set -euo pipefail case "$HOSTED_IDENTITY_MODE" in - hosted-controller) - if [[ "$HOSTED_IDENTITY_REQUESTER_CREDENTIALS_AVAILABLE" == true ]]; then - bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh \ - --apply --retire-terminal-identities - else - bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply - fi - ;; - standalone) - bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply - ;; + hosted-controller | standalone) ;; *) echo "unsupported certificate identity mode: ${HOSTED_IDENTITY_MODE}" >&2 exit 1 ;; esac + if [[ "$HOSTED_IDENTITY_REQUESTER_CREDENTIALS_AVAILABLE" == true ]]; then + bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh \ + --apply --retire-terminal-identities + else + bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply + fi - name: Remove hosted identity requester kubeconfig if: ${{ always() }} diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 383d615af8..d1091ac967 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -18,12 +18,10 @@ concurrency: jobs: reconcile-previews: name: Reconcile Open PR Previews + # GitHub-hosted runners need a separate cluster network path and credentials first. + if: ${{ vars.PREVIEW_GITHUB_HOSTED_CLUSTER_ACCESS == 'true' }} timeout-minutes: 60 - runs-on: - - self-hosted - - preview - - linux - - x64 + runs-on: ubuntu-latest environment: trusted-hosted-cluster steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -523,6 +521,8 @@ jobs: --arg trusted_workflow_name "Trusted Hosted Identity Request" \ --arg default_branch "${DEFAULT_BRANCH}" \ --arg pr_title "PR preview ${pr_number}" \ + --arg head_sha "${head_sha}" \ + --argjson pr "${pr_number}" \ --arg run_name "Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" ' if type != "array" then error("workflow runs are not an array") @@ -546,6 +546,15 @@ jobs: or (.firemud_reconciler_branch_filtered == true and .head_branch == $default_branch) ) and (.display_title == $run_name or .display_title == $pr_title) + # Names and titles of pull_request runs come from PR-authored + # YAML; only the GitHub association (or, when it is empty, the + # native refs/pull path) binds such a run to this PR, and only a + # run of the current head can render it. + # The run must also be the canonical preview workflow file. + and (.event != "pull_request" or (.head_sha == $head_sha + and ((.path // "") | startswith(".github/workflows/preview.yml")) and ( + ((.pull_requests // []) | any(.number == $pr)) + or ((.pull_requests // []) == [] and .path == ".github/workflows/preview.yml@refs/pull/\($pr)/merge")))) and ( .status == "requested" or .status == "queued" @@ -607,12 +616,12 @@ jobs: if [[ -n "$candidate_rows" ]]; then active_preview_run_sets=() for active_status in requested queued in_progress waiting pending; do - for active_run_scope in branch pull_request_target workflow_run; do + for active_run_scope in branch pull_request workflow_run; do if [[ "$active_run_scope" == branch ]]; then active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" active_run_branch_filtered=true - elif [[ "$active_run_scope" == pull_request_target ]]; then - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=pull_request_target&status=${active_status}&per_page=100" + elif [[ "$active_run_scope" == pull_request ]]; then + active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=pull_request&status=${active_status}&per_page=100" active_run_branch_filtered=false else active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=workflow_run&status=${active_status}&per_page=100" diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml new file mode 100644 index 0000000000..d74114d409 --- /dev/null +++ b/.github/workflows/preview-runtime-refresh.yml @@ -0,0 +1,42 @@ +name: Refresh Preview Runtime Base + +# Privileged observer for PR-authored preview runs. It uses nothing from the +# source run except GitHub's own PR association, reads the live PR, base ref and +# test merge, and dispatches a runtime refresh only for an eligible stale tuple. +# It never checks out PR code or downloads artifacts. +on: + workflow_run: + workflows: [PR Preview Environment] + types: [completed] + +permissions: {} + +jobs: + refresh: + if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write # Send the typed repository_dispatch. + pull-requests: read + steps: + - name: Check out trusted default branch image policy + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Set up canonical Python + uses: ./.github/actions/setup-python + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Dispatch a runtime refresh for the live tuple + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + GH_TOKEN: ${{ github.token }} + with: + script: | + const observe = require('./dev-tools/hosted/preview/preview-runtime-refresh.cjs'); + await observe({github, context, core}); diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 8e7c1824b3..f5ea891900 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -3,7 +3,7 @@ name: PR Preview Environment run-name: ${{ github.event_name == 'repository_dispatch' && format('Preview dispatch pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha || 'unknown', github.event.client_payload.head_sha, github.event.client_payload.merge_sha || 'unknown') || format('PR preview {0}', github.event.pull_request.number) }} on: - pull_request_target: + pull_request: paths-ignore: - '**/*.md' - 'mkdocs.yml' @@ -28,9 +28,9 @@ jobs: preview-plan: name: Preview Plan runs-on: ubuntu-latest - if: ${{ github.event_name != 'pull_request_target' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.base.repo.full_name == github.repository && (github.event.action != 'labeled' && github.event.action != 'unlabeled' || github.event.label.name == 'preview:priority') && (github.event.action != 'edited' || github.event.changes.base != null)) }} + if: ${{ github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.base.repo.full_name == github.repository && (github.event.action != 'labeled' && github.event.action != 'unlabeled' || github.event.label.name == 'preview:priority') && (github.event.action != 'edited' || github.event.changes.base != null)) }} concurrency: - group: preview-plan-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }} + group: preview-readonly-plan-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }} cancel-in-progress: true outputs: action: ${{ steps.derive.outputs.action }} @@ -92,7 +92,7 @@ jobs: exit 1 fi - if [[ "$EVENT_NAME" == pull_request_target ]]; then + if [[ "$EVENT_NAME" == pull_request ]]; then PR_NUMBER="$EVENT_PR_NUMBER" HEAD_SHA="$EVENT_HEAD_SHA" BASE_SHA="" @@ -206,13 +206,13 @@ jobs: echo "::error title=Stale preview head SHA::Supplied head SHA does not equal the current pull request head." >&2 exit 1 fi - if [[ "$ACTION" == deploy && "$EVENT_NAME" == pull_request_target && "${EVENT_BASE_SHA,,}" != "$CURRENT_BASE_SHA" ]]; then + if [[ "$ACTION" == deploy && "$EVENT_NAME" == pull_request && "${EVENT_BASE_SHA,,}" != "$CURRENT_BASE_SHA" ]]; then BASE_REFRESH_REQUIRED=true fi HEAD_SHA="$CURRENT_HEAD_SHA" BASE_SHA="$CURRENT_BASE_SHA" - if [[ "$EVENT_NAME" == pull_request_target && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] || + if [[ "$EVENT_NAME" == pull_request && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] || [[ "$EVENT_NAME" == repository_dispatch && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] || [[ "$EVENT_NAME" == repository_dispatch && -n "$PLANNED_BASE_SHA" && -n "$PLANNED_IMAGE_TAG" ]]; then BASE_REFRESH_REQUIRED=true @@ -336,7 +336,7 @@ jobs: DERIVED_PR_NUMBER: ${{ steps.derive.outputs.pr_number }} run: | set -euo pipefail - if [[ "$EVENT_NAME" == pull_request_target ]]; then + if [[ "$EVENT_NAME" == pull_request ]]; then PR_AUTHOR="$PR_USER_LOGIN" BASE_REF="$PR_BASE_REF" LABELS_JSON="$(jq -c 'if type == "array" then [.[] | {name: .name}] else . end' <<<"$PR_LABELS_JSON")" @@ -415,7 +415,9 @@ jobs: preview-runtime-base-refresh: name: Refresh PR Runtime Images For Current Base needs: preview-plan - if: ${{ needs.preview-plan.outputs.eligible == 'true' && needs.preview-plan.outputs.action == 'deploy' && needs.preview-plan.outputs.base_refresh_required == 'true' && needs.preview-plan.outputs.image_tag != needs.preview-plan.outputs.base_sha }} + # PR-authored pull_request runs never dispatch; the trusted Preview Runtime + # Refresh observer reads their live tuple and dispatches instead. + if: ${{ github.event_name == 'repository_dispatch' && needs.preview-plan.outputs.eligible == 'true' && needs.preview-plan.outputs.action == 'deploy' && needs.preview-plan.outputs.base_refresh_required == 'true' && needs.preview-plan.outputs.image_tag != needs.preview-plan.outputs.base_sha }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -514,7 +516,7 @@ jobs: permissions: contents: read concurrency: - group: preview-render-${{ needs.preview-plan.outputs.pr_number }} + group: preview-readonly-render-${{ needs.preview-plan.outputs.pr_number }} cancel-in-progress: true steps: - name: Harden runner @@ -522,10 +524,19 @@ jobs: with: egress-policy: audit + # A manual dispatch is a trusted event: never execute candidate scripts or + # local actions in that context. Candidate Helm templates are data only. + - name: Check out trusted default branch render tools + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Check out exact PR merge ref for untrusted render uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge + path: candidate fetch-depth: 2 persist-credentials: false @@ -551,11 +562,11 @@ jobs: run: | set -euo pipefail umask 077 - if ! MERGE_SHA="$(git rev-parse --verify 'HEAD^{commit}')"; then + if ! MERGE_SHA="$(git -C candidate rev-parse --verify 'HEAD^{commit}')"; then echo "::error title=Invalid preview merge ref::The checked-out pull request merge ref is not a commit." >&2 exit 1 fi - if ! merge_parents="$(git rev-list --parents -n 1 "$MERGE_SHA")"; then + if ! merge_parents="$(git -C candidate rev-list --parents -n 1 "$MERGE_SHA")"; then echo "::error title=Invalid preview merge ref::Unable to read the checked-out merge commit parents." >&2 exit 1 fi @@ -571,9 +582,9 @@ jobs: sanitized="$RUNNER_TEMP/preview-rendered-sanitized.yaml" metadata="$RUNNER_TEMP/preview-metadata.json" python3 ./dev-tools/hosted/preview/render-preview-values.py \ - k8s/helm/firemud/values-hosted-shared.example.yaml \ + candidate/k8s/helm/firemud/values-hosted-shared.example.yaml \ "$values" "$PR_NUMBER" "$NAMESPACE" "$RELEASE_NAME" "$HOSTNAME" "$IMAGE_TAG" 32000 - helm template "$RELEASE_NAME" k8s/helm/firemud \ + helm template "$RELEASE_NAME" candidate/k8s/helm/firemud \ -f "$values" --namespace "$NAMESPACE" > "$rendered" # Only these chart-owned objects are intentionally absent from the diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index cd218f3094..49f4bc0485 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -68,12 +68,17 @@ jobs: return ref.split("/").every(part => part && part !== "." && part !== ".." && !part.startsWith(".") && !part.endsWith(".lock")); } - const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; + const titlePattern = /^Build Runtime Images pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; const deadline = Date.now() + 120000; for (;;) { const { data: run } = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: sourceId, }); + // A metadata-only edit completes its own run with no images to publish. + if (callback && typeof run.display_title === "string" && run.display_title.endsWith(" mode-metadata")) { + core.notice("Metadata-only source run; no runtime images to publish."); + return; + } const title = typeof run.display_title === "string" && run.display_title.match(titlePattern); if (run.id !== sourceId || run.workflow_id !== workflow.id || !isTrustedWorkflowPath(run.path) || !title || @@ -107,9 +112,29 @@ jobs: core.notice("CI passed under the canonical PLAY transition exception; no runtime images are eligible for publication."); return; } + // Publish only the archive this run exported for its titled merge. + // Docs-only PRs, skipped refreshes and runs that built a recomputed + // merge export none; a failed lookup throws rather than skipping. + const artifactName = `pr-runtime-images-pr-merge-${title[4]}`; + const artifacts = await github.paginate(github.rest.actions.listWorkflowRunArtifacts, { + ...context.repo, run_id: sourceId, name: artifactName, per_page: 100, + }); + const exact = artifacts.filter(artifact => artifact.name === artifactName); + if (exact.length > 0 && exact.every(artifact => artifact.expired)) { + throw new Error(`${artifactName} has expired; publish from a fresh source run (or follow the partial-set manual hold if tags exist).`); + } + if (exact.length === 0) { + // An upload that succeeded but left no archive means it was deleted. + if (jobs.some(job => (job.steps ?? []).some(step => step.name === "Upload preview image artifact" && + step.conclusion === "success"))) { + throw new Error(`${artifactName} was uploaded but is gone; publish from a fresh source run (or follow the partial-set manual hold if tags exist).`); + } + core.notice(`Source run exported no ${artifactName} archive; nothing to publish.`); + return; + } core.setOutput("source", JSON.stringify(run)); core.setOutput("title", run.display_title); - core.setOutput("artifact_name", `pr-runtime-images-pr-merge-${title[4]}`); + core.setOutput("artifact_name", artifactName); break; } if (callback || !["queued", "in_progress", "waiting", "pending", "requested"].includes(run.status) || @@ -215,7 +240,7 @@ jobs: SHA_PATTERN = r"[0-9a-f]{40}" SOURCE_WORKFLOW_PATH = ".github/workflows/runtime-images.yml" TITLE_PATTERN = re.compile( - rf"^Build Runtime Images secure-pr-artifact " + rf"^Build Runtime Images " rf"pr-([1-9][0-9]*) base-({SHA_PATTERN}) head-({SHA_PATTERN}) " rf"merge-({SHA_PATTERN}) mode-required$" ) @@ -621,6 +646,12 @@ jobs: missing_services+=("$service") fi done + # Tags are write-once and provenance is tag-level: a set another build of + # this merge already completed is final, even with different image IDs. + if ((${#missing_services[@]} == 0)); then + echo "Every ${IMAGE_TAG} tag is already published; nothing to do." + exit 0 + fi for service in "${existing_services[@]}"; do verify_existing_target "$service" done @@ -675,6 +706,8 @@ jobs: # shellcheck disable=SC2016 # Backticks are literal Markdown delimiters. printf -- '- `%s`\n' "${unpublished_services[@]}" fi + echo + echo "Manual hold: re-run this publisher while the source artifact exists, or delete the partial pr-merge tags or push a new PR head. A rebuild cannot match the published image IDs." } >> "$GITHUB_STEP_SUMMARY" exit 1 fi diff --git a/.github/workflows/resolve-required-gates.yml b/.github/workflows/resolve-required-gates.yml index d49edd99ef..45f473420e 100644 --- a/.github/workflows/resolve-required-gates.yml +++ b/.github/workflows/resolve-required-gates.yml @@ -2,7 +2,7 @@ name: Resolve Required Gates on: workflow_run: - workflows: ['CI โ€” Validation', Security Gate, CodeQL Analysis, License Gate, PR Smoke Gate] + workflows: ['CI โ€” Validation', Security Gate, CodeQL Analysis, License Gate, Build Runtime Images] types: [completed] run-name: Resolve Required Gates workflow-${{ github.event.workflow_run.workflow_id }} head-${{ github.event.workflow_run.head_sha }} source-${{ github.event.workflow_run.id }} @@ -49,7 +49,7 @@ jobs: ['.github/workflows/security.yml', 'Security Gate'], ['.github/workflows/codeql.yml', 'CodeQL Analysis'], ['.github/workflows/license-scan.yml', 'License Gate'], - ['.github/workflows/smoke.yml', 'PR Smoke Gate'], + ['.github/workflows/runtime-images.yml', 'Build Runtime Images'], ]); const terminalConclusions = new Set([ 'action_required', 'cancelled', 'failure', 'neutral', 'skipped', 'stale', @@ -68,7 +68,8 @@ jobs: const [association] = source.pull_requests; const [workflowPath] = source.path.split('@', 1); const workflowName = workflowNames.get(workflowPath); - const title = /^(.*) pr-([1-9][0-9]*) base-([0-9a-fA-F]{40}) head-([0-9a-fA-F]{40})$/.exec(source.display_title); + // Build Runtime Images titles also carry the merge and mode they built. + const title = /^(.*) pr-([1-9][0-9]*) base-([0-9a-fA-F]{40}) head-([0-9a-fA-F]{40})(?: merge-[0-9a-fA-F]{40} mode-(?:required|metadata))?$/.exec(source.display_title); if (!workflowName || source.path === `${workflowPath}@` || (source.name !== workflowName && source.name !== source.display_title) || title?.[1] !== workflowName || title[4] !== source.head_sha || diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 959cbe3153..2ac33e1bdb 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -3,45 +3,6 @@ name: Build Runtime Images on: pull_request: types: [opened, synchronize, reopened, edited] - paths: - - 'build.gradle.kts' - - 'settings.gradle.kts' - - 'gradle.properties' - - 'gradlew' - - 'gradlew.bat' - - 'buildSrc/**' - - 'gradle/**' - - 'protos/**' - - 'docker/**' - - '.dockerignore' - - '.github/workflows/runtime-images.yml' - - '.github/workflows/publish-pr-runtime-images.yml' - - '.github/workflows/smoke.yml' - - '.github/workflows/smoke-full.yml' - - 'services/**' - - '.github/actions/load-workflow-tool-versions/**' - - '.github/actions/setup-python/**' - - '.python-version' - - 'config/workflow-tool-versions.env' - - 'config/python/smoke-requirements.txt' - - 'config/python/smoke-requirements.in' - - 'dev-tools/build-compose-service-jars.sh' - - 'dev-tools/validation/run-gradle-with-dependency-recovery.sh' - - 'dev-tools/validation/run-locked-gradle.sh' - - 'dev-tools/validation/gradle-run-supervisor.py' - - 'dev-tools/build-local-smoke-images.sh' - - 'dev-tools/backups/verify-backups.sh' - - 'dev-tools/backups/pg-dump-s3-selection.shlib' - - 'dev-tools/backups/smoke-backup-verifier-image.sh' - - 'docker/backup-verifier.Dockerfile' - - 'dev-tools/certs/generate-dev-certs.sh' - - 'dev-tools/minio/**' - - 'dev-tools/hosted/controller/smoke-paused-controller-image.sh' - - 'dev-tools/smoke/**' - - 'dev-tools/verify-compose-health.sh' - - 'dev-tools/verify-fresh-bootstrap.sh' - - 'dev-tools/verify-restart-state.sh' - - 'dev-tools/verify-smoke-images.sh' workflow_run: workflows: ["CI โ€” Validation"] types: [completed] @@ -49,19 +10,170 @@ on: types: [pr-runtime-base-refresh] workflow_dispatch: -run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('secure-pr-artifact pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} +run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} permissions: contents: read +# GitHub rejects queue: max together with a cancelling run, so the workflow +# group never cancels. Typed refresh tuples and protected commits queue every +# pending request, so a main request cannot replace a pending develop +# publication of the same commit. Each PR run has its own group here; the PR +# build jobs below cancel the PR's older build at job level instead. concurrency: - group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} - cancel-in-progress: true + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-run-{1}', github.event.pull_request.number, github.run_id)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') && format('protected-sha-{0}', github.event.workflow_run.head_sha)) || (github.event_name == 'workflow_dispatch' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop') && format('protected-sha-{0}', github.sha)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('ci-push-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && format('metadata-{0}', github.run_id) || 'required' }} + cancel-in-progress: false + queue: max jobs: + changes: + name: Detect Smoke-Relevant Changes + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + # Runs for every event except a metadata-only PR edit: a skipped ancestor + # would also skip later jobs whose conditions lack a status function. + if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} + outputs: + run_smoke_full: ${{ steps.compute.outputs.run_smoke_full }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Compute smoke scope + id: compute + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + // Non-PR events classify nothing here; their own jobs decide scope. + if (context.eventName !== "pull_request") { + core.setOutput("run_smoke_full", "true"); + return; + } + // Classify the exact test merge this run builds. The live PR file list + // can already describe a later head. + const base = context.payload.pull_request.base.sha; + const merge = context.sha; + let fileEntries = []; + let fileListComplete = false; + try { + const {data: comparison} = await github.request("GET /repos/{owner}/{repo}/compare/{basehead}", { + ...context.repo, basehead: `${base}...${merge}`, page: 1, per_page: 1, + }); + fileEntries = Array.isArray(comparison?.files) ? comparison.files : []; + // Only a merge whose ordered parents are the event base and head may skip + // smoke; otherwise image-meta resolves the exact merge and smoke runs. + const {data: commit} = await github.request("GET /repos/{owner}/{repo}/commits/{ref}", { + ...context.repo, ref: merge, + }); + const parents = (commit?.parents ?? []).map((parent) => parent?.sha); + fileListComplete = parents.length === 2 && parents[0] === base && + parents[1] === context.payload.pull_request.head.sha && + comparison?.base_commit?.sha === base && comparison.merge_base_commit?.sha === base && + comparison.status === "ahead" && Array.isArray(comparison.files) && comparison.files.length < 300; + } catch (error) { + core.warning(`Test-merge comparison unavailable: ${error.message}`); + } + const fileEntriesValid = fileEntries.every((file) => + file && + typeof file === "object" && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + const files = fileEntriesValid + ? fileEntries.flatMap((file) => + [file.filename, file.previous_filename].filter(Boolean) + ) + : []; + + if (!fileListComplete || !fileEntriesValid) { + core.warning("PR file-list detection was incomplete; requiring full-stack smoke."); + core.setOutput("run_smoke_full", "true"); + return; + } + + const docsOnlyPredicate = (file) => + file === "AGENTS.md" || + file === "mkdocs.yml" || + file.startsWith("design/") || + file.startsWith("dev-tools/docs/") || + // Markdown under src/main/ is a packaged resource, so it is runtime input. + (file.endsWith(".md") && !file.includes("/src/main/")); + + const frontendOnlyPredicate = (file) => + file.startsWith("web-client/") || + file.startsWith("config/openapi/"); + + const fullRelevantPrefixes = [ + "buildSrc/", + "gradle/", + "protos/", + "docker/", + "services/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ".github/actions/setup-gh/", + ".env.sample", + "dev-tools/certs/ensure-dev-certs.sh", + "dev-tools/smoke/", + "dev-tools/minio/", + ]; + const fullRelevantFiles = new Set([ + "build.gradle.kts", + "settings.gradle.kts", + "gradle.properties", + "gradlew", + "gradlew.bat", + ".dockerignore", + ".python-version", + ".github/actions/load-workflow-tool-versions/action.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/publish-pr-runtime-images.yml", + "config/workflow-tool-versions.env", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + ]); + + const nonDocFiles = files.filter((file) => !docsOnlyPredicate(file)); + const nonDocsAreFrontendOnly = + nonDocFiles.length > 0 && nonDocFiles.every((file) => frontendOnlyPredicate(file)); + + if (nonDocFiles.length === 0 || nonDocsAreFrontendOnly) { + core.setOutput("run_smoke_full", "false"); + return; + } + + const runSmokeFull = nonDocFiles.some( + (file) => + fullRelevantFiles.has(file) || + fullRelevantPrefixes.some((prefix) => file.startsWith(prefix)) + ); + core.setOutput("run_smoke_full", runSmokeFull ? "true" : "false"); + image-meta: name: Derive Runtime Image Metadata - if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop')) }} + needs: [changes] + if: ${{ !cancelled() && ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.run_smoke_full == 'true') || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) }} runs-on: ubuntu-latest outputs: pr_number: ${{ steps.meta.outputs.pr_number }} @@ -71,15 +183,17 @@ jobs: merge_sha: ${{ steps.meta.outputs.merge_sha }} head_branch: ${{ steps.meta.outputs.head_branch }} checkout_ref: ${{ steps.meta.outputs.checkout_ref }} + head_current: ${{ steps.meta.outputs.head_current }} image_tag: ${{ steps.meta.outputs.image_tag }} candidate_tag: ${{ steps.meta.outputs.candidate_tag }} base_image: ${{ steps.meta.outputs.base_image }} - canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} + skip_build: ${{ steps.published.outputs.skip_build }} permissions: actions: read contents: read + packages: read # Check existing pr-merge tags before a typed refresh rebuilds. pull-requests: read steps: - name: Harden runner @@ -118,7 +232,6 @@ jobs: BASE_REF="" BASE_SHA="" MERGE_SHA="" - CANONICAL_PLAY_TRANSITION=false if [ "$EVENT_NAME" = "pull_request" ]; then PR_NUMBER="$EVENT_PR_NUMBER" BASE_REF="$EVENT_BASE_REF" @@ -135,16 +248,33 @@ jobs: echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 exit 1 } - merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" - jq -e \ - --arg base_sha "$BASE_SHA" \ - --arg head_sha "$HEAD_SHA" \ - --arg merge_sha "$MERGE_SHA" \ - '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ - <<<"$merge_commit_json" >/dev/null || { - echo "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." >&2 + exact_merge() { + gh api "repos/${GITHUB_REPOSITORY}/commits/$1" | jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$1" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + >/dev/null + } + if ! exact_merge "$MERGE_SHA"; then + # A retarget edit can carry the previous test merge. Build GitHub's + # recomputed merge instead when its parents are exactly the event's. + MERGE_SHA="" + for attempt in 1 2 3 4 5 6; do + live_merge="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '.merge_commit_sha // ""')" || live_merge="" + if [[ "$live_merge" =~ ^[0-9a-f]{40}$ ]] && exact_merge "$live_merge"; then + MERGE_SHA="$live_merge" + break + fi + (( attempt < 6 )) && sleep 10 + done + [[ -n "$MERGE_SHA" ]] || { + echo "No PR test merge has the event's exact base/head parents; refusing a stale PR artifact." >&2 exit 1 } + CHECKOUT_REF="$MERGE_SHA" + echo "Event merge was stale; building recomputed test merge ${MERGE_SHA}." + fi elif [ "$EVENT_NAME" = "repository_dispatch" ]; then [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 @@ -161,6 +291,8 @@ jobs: HEAD_SHA="$EVENT_HEAD_SHA" HEAD_BRANCH="" CHECKOUT_REF="$MERGE_SHA" + # The payload is untrusted: any writer can send this dispatch. + # Everything below is rechecked against the live API. [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { echo "Runtime PR refresh payload has an invalid pull request number." >&2 exit 1 @@ -220,12 +352,6 @@ jobs: echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 exit 1 } - # Only the verified live same-repository PR can authorize this - # diagnostic marker; dispatch payload labels carry no authority. - if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ - <<<"$pull_request_json" >/dev/null; then - CANONICAL_PLAY_TRANSITION=true - fi elif [ "${{ github.event_name }}" = "workflow_run" ]; then [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { echo "Runtime branch publication requires a CI push workflow run." >&2 @@ -253,6 +379,29 @@ jobs: echo "Runtime branch publication is restricted to main or develop." >&2 exit 1 } + current_head="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" --jq '.object.sha')" + [[ "$current_head" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication could not prove the live ${HEAD_BRANCH} head." >&2 + exit 1 + } + if [[ "$current_head" != "$HEAD_SHA" ]]; then + echo "Skipping runtime builds for obsolete ${HEAD_BRANCH}@${HEAD_SHA}; current head is ${current_head}." + exit 0 + fi + fi + + # A delayed run of a superseded comparison (older head, or base before a + # retarget) must not enter the per-PR smoke groups, where it would cancel + # the current comparison's smoke. An unreadable PR counts as current so + # the gate still gets proof. + HEAD_CURRENT=true + if [ "$EVENT_NAME" = "pull_request" ]; then + live_pr="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '"\(.head.sha // "") \(.base.ref // "")"')" || live_pr="" + read -r live_head live_base_ref <<<"$live_pr" || true + if [[ -n "${live_head:-}" && ( "$live_head" != "$HEAD_SHA" || "${live_base_ref:-}" != "$BASE_REF" ) ]]; then + HEAD_CURRENT=false + echo "::notice::PR now compares ${live_head} against ${live_base_ref}; skipping smoke for superseded ${HEAD_SHA} against ${BASE_REF}." + fi fi if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then @@ -275,14 +424,45 @@ jobs: echo "merge_sha=${MERGE_SHA}" echo "head_branch=${HEAD_BRANCH}" echo "checkout_ref=${CHECKOUT_REF}" + echo "head_current=${HEAD_CURRENT}" echo "image_tag=${IMAGE_TAG}" echo "candidate_tag=${CANDIDATE_TAG}" echo "base_image=${BASE_IMAGE}" - echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" } >> "$GITHUB_OUTPUT" + - name: Log in to GHCR for the publication check + if: ${{ github.event_name == 'repository_dispatch' }} + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + # One rule: build only when no pr-merge tag exists. Tags are write-once and + # the publisher serializes per merge and leaves a complete set alone, so a + # duplicate build only costs CI time. Any existing tag means a publisher has + # already started; a rebuild cannot complete a partial set. + - name: Skip a refresh whose PR merge images are already being published + id: published + if: ${{ github.event_name == 'repository_dispatch' }} + env: + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MERGE_SHA: ${{ steps.meta.outputs.merge_sha }} + run: | + set -euo pipefail + source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh + pr_merge_publication_state "$MERGE_SHA" state + case "$state" in + none) echo "skip_build=false" >> "$GITHUB_OUTPUT" ;; + complete) echo "skip_build=true" >> "$GITHUB_OUTPUT" + echo "All pr-merge-${MERGE_SHA} runtime images already exist; skipping the rebuild." ;; + *) echo "skip_build=true" >> "$GITHUB_OUTPUT" + echo "::warning title=Partial PR runtime publication::Some pr-merge-${MERGE_SHA} tags exist. A running publisher will finish them; otherwise this is a manual hold: re-run the original publisher while its source archive exists, or delete the partial tags or push a new PR head." ;; + esac + - name: Verify successful CI push for manual publication - if: ${{ github.event_name == 'workflow_dispatch' }} + if: ${{ github.event_name == 'workflow_dispatch' && steps.meta.outputs.head_sha != '' }} env: GH_TOKEN: ${{ github.token }} EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} @@ -303,30 +483,36 @@ jobs: - name: Detect PR smoke scopes id: smoke_scope uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + VERIFIED_BASE_SHA: ${{ steps.meta.outputs.base_sha }} + VERIFIED_MERGE_SHA: ${{ steps.meta.outputs.merge_sha }} with: script: | let runtimeSmokeRequired = true; let controllerSmokeRequired = true; if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { try { - const pullNumber = context.eventName === "pull_request" - ? context.payload.pull_request.number - : context.payload.client_payload.pr_number; - const changedFiles = await github.paginate( - github.rest.pulls.listFiles, - { - ...context.repo, - pull_number: pullNumber, - per_page: 100, - }, - (response) => response.data - ); - const expectedFileCount = context.eventName === "pull_request" - ? context.payload.pull_request.changed_files - : (await github.rest.pulls.get({ + let changedFiles; + { + // Classify the verified test merge this run builds; a live PR + // file list can already describe a later head. + const {VERIFIED_BASE_SHA: base, VERIFIED_MERGE_SHA: merge} = process.env; + if (![base, merge].every(sha => typeof sha === "string" && /^[0-9a-f]{40}$/.test(sha))) { + throw new Error("missing immutable test-merge comparison"); + } + const {data: comparison} = await github.request("GET /repos/{owner}/{repo}/compare/{basehead}", { ...context.repo, - pull_number: pullNumber, - })).data.changed_files; + basehead: `${base}...${merge}`, + page: 1, per_page: 1, + request: {signal: AbortSignal.timeout(10000)}, + }); + if (comparison?.base_commit?.sha !== base || comparison.merge_base_commit?.sha !== base || + comparison.status !== "ahead" || !Array.isArray(comparison.files) || + comparison.files.length >= 300) { + throw new Error("incomplete immutable test-merge file comparison"); + } + changedFiles = comparison.files; + } const validFileEntries = changedFiles.every((file) => file && typeof file.filename === "string" && @@ -334,7 +520,7 @@ jobs: (file.previous_filename === undefined || (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) ); - if (!Number.isInteger(expectedFileCount) || changedFiles.length !== expectedFileCount || !validFileEntries) { + if (!validFileEntries) { core.warning("PR smoke scope detection was incomplete; running both local smokes."); } else { const paths = changedFiles.flatMap((file) => @@ -349,6 +535,9 @@ jobs: "protos/", ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", + ".github/actions/setup-gh/", + ".env.sample", + "dev-tools/certs/ensure-dev-certs.sh", ]; const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; const runtimeFiles = new Set([ @@ -356,7 +545,6 @@ jobs: ".github/workflows/publish-pr-runtime-images.yml", ".github/workflows/runtime-images.yml", ".github/workflows/smoke-full.yml", - ".github/workflows/smoke.yml", ".github/actions/load-workflow-tool-versions/action.yml", ".python-version", "build.gradle.kts", @@ -458,13 +646,15 @@ jobs: "protos/", ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", + ".github/actions/setup-gh/", + ".env.sample", + "dev-tools/certs/ensure-dev-certs.sh", ]; const runtimeFiles = new Set([ ".dockerignore", ".github/workflows/publish-pr-runtime-images.yml", ".github/workflows/runtime-images.yml", ".github/workflows/smoke-full.yml", - ".github/workflows/smoke.yml", ".github/actions/load-workflow-tool-versions/action.yml", ".python-version", "build.gradle.kts", @@ -490,10 +680,6 @@ jobs: "gradlew.bat", "settings.gradle.kts", ]); - const runtimeRunEvents = ["pull_request", "repository_dispatch"]; - const runtimeRunPageSize = 100; - const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; - const waitForMergeRefresh = async () => { await new Promise((resolve) => setTimeout(resolve, 2000)); }; @@ -522,10 +708,15 @@ jobs: core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); return true; } + // A main/develop PR deploys base images for unpackaged Markdown, as the + // preview resolver decides; stacked PRs always need their merge images. + const protectedBase = ["main", "develop"].includes(pullRequest.base?.ref); return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => - runtimeFiles.has(path) || - runtimePrefixes.some((prefix) => path.startsWith(prefix)) || - path.startsWith("services/") + !(protectedBase && path.endsWith(".md") && !path.includes("/src/main/")) && ( + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + path.startsWith("services/") + ) ); }; @@ -639,162 +830,6 @@ jobs: return null; }; - const loadExistingRuntimeRuns = async () => { - const readInventory = async (createdSince) => { - const inventory = []; - let complete = true; - let incompleteReason = null; - for (const event of runtimeRunEvents) { - const response = await github.rest.actions.listWorkflowRuns({ - ...context.repo, - workflow_id: "runtime-images.yml", - event, - created: `${createdSince}..*`, - per_page: runtimeRunPageSize, - page: 1, - }); - const payload = response?.data; - if (!payload || !Number.isInteger(payload.total_count) || - payload.total_count < 0 || !Array.isArray(payload.workflow_runs)) { - throw new Error(`runtime-images ${event} recent run inventory is malformed`); - } - if (payload.total_count > runtimeRunPageSize) { - complete = false; - incompleteReason ??= `runtime-images ${event} has more than ${runtimeRunPageSize} runs since ${createdSince}`; - } - const expectedPageLength = Math.min(payload.total_count, runtimeRunPageSize); - if (payload.workflow_runs.length !== expectedPageLength) { - throw new Error(`runtime-images ${event} recent run inventory is incomplete`); - } - inventory.push(...payload.workflow_runs); - } - return {complete, runs: inventory, reason: incompleteReason}; - }; - - const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); - const initial = await readInventory(createdSince); - if (initial.complete) { - return initial; - } - - const inFlightStatuses = ["queued", "waiting", "requested", "pending", "in_progress"]; - const inFlightRuns = initial.runs.filter((run) => inFlightStatuses.includes(run?.status)); - if (inFlightRuns.length === 0) { - return initial; - } - - const validTimestamp = (value) => typeof value === "string" && - /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && - Number.isFinite(Date.parse(value)); - if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || - !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { - return { - ...initial, - reason: "truncated recent inventory contains an in-flight run without a valid event, id, or creation timestamp", - }; - } - - const refinementSince = inFlightRuns - .map((run) => run.created_at) - .sort()[0]; - // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. - const refined = await readInventory(refinementSince); - if (!refined.complete) { - return { - ...refined, - reason: refined.reason || "refined runtime run inventory is incomplete", - }; - } - const refinedIds = new Set(refined.runs.map((run) => `${run?.event}:${run?.id}`)); - if (inFlightRuns.some((run) => !refinedIds.has(`${run.event}:${run.id}`))) { - return { - ...refined, - complete: false, - reason: "refined inventory did not retain every initially observed in-flight run", - }; - } - return refined; - }; - - const findExactExistingProducer = (tuple, inventory) => { - const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; - const workflowPathMatches = (path) => { - if (path === expectedWorkflowPath) { - return true; - } - const prefix = `${expectedWorkflowPath}@`; - if (typeof path !== "string" || !path.startsWith(prefix)) { - return false; - } - const ref = path.slice(prefix.length); - if (ref.length === 0 || ref === "@" || ref.endsWith(".") || - /[\u0000-\u0020\u007f]/.test(ref) || - ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || - ref.includes("..") || ref.includes("@{")) { - return false; - } - return ref.split("/").every((part) => - part.length > 0 && part !== "." && part !== ".." && - !part.startsWith(".") && - !part.endsWith(".lock") - ); - }; - const expectedTitle = - `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + - `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; - const matching = inventory.runs.filter((run) => - run?.display_title === expectedTitle - ); - const ordered = []; - const matchingIds = new Set(); - for (const run of matching) { - if (!runtimeRunEvents.includes(run.event) || - !Number.isSafeInteger(run.id) || run.id <= 0 || matchingIds.has(run.id) || - typeof run.created_at !== "string" || - !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || - !Number.isFinite(Date.parse(run.created_at)) || - !workflowPathMatches(run.path) || - !["Build Runtime Images", expectedTitle].includes(run.name) || - run.repository?.full_name !== context.payload.repository.full_name || - run.head_repository?.full_name !== context.payload.repository.full_name) { - throw new Error(`run ${run.id} has the exact tuple title but invalid workflow or repository identity`); - } - matchingIds.add(run.id); - ordered.push(run); - if (run.event === "pull_request") { - if (run.head_sha !== tuple.headSha) { - throw new Error(`run ${run.id} has the exact tuple title but a different PR head SHA`); - } - const pullRequests = run.pull_requests; - if (!Array.isArray(pullRequests) || (pullRequests.length > 0 && !pullRequests.some((pullRequest) => - String(pullRequest?.number) === tuple.prNumber && - pullRequest?.head?.sha === tuple.headSha - ))) { - throw new Error(`run ${run.id} has incomplete or conflicting PR association evidence`); - } - } - } - ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); - if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { - throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); - } - const newest = ordered[0]; - if (!newest) { - return []; - } - if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { - if (newest.conclusion !== null && newest.conclusion !== undefined) { - throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); - } - return [newest]; - } - if (newest.status === "completed") { - // Completed source success does not prove publication remains usable; preserve recovery dispatch. - return []; - } - throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); - }; - if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || refreshBranch.length === 0) { core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); @@ -947,61 +982,31 @@ jobs: } } } - let runtimeInventoryPromise; - let runtimeInventoryError = null; - for (const resolved of refreshTargets) { - const {tuple, pullRequest} = resolved; + const dispatchFailures = []; + const dispatch = async (eventType, payload) => { + try { + await github.rest.repos.createDispatchEvent({ + ...context.repo, event_type: eventType, client_payload: payload, + }); + } catch (error) { + const failure = `${eventType} for PR #${payload.pr_number}: ${error.message}`; + dispatchFailures.push(failure); + core.warning(failure); + } + }; + for (const {tuple, pullRequest} of refreshTargets) { + const target = { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }; if (await hasRuntimeChange(pullRequest)) { - let existingProducers = []; - let fallbackReason = null; - let inventory; - if (runtimeInventoryError) { - fallbackReason = runtimeInventoryError; - } else { - try { - runtimeInventoryPromise ??= loadExistingRuntimeRuns(); - inventory = await runtimeInventoryPromise; - } catch (error) { - fallbackReason = error.message || String(error); - runtimeInventoryError = fallbackReason; - } - } - if (!fallbackReason) { - try { - existingProducers = findExactExistingProducer(tuple, inventory); - if (!inventory.complete) { - // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. - existingProducers = []; - fallbackReason = inventory.reason || "recent run inventory is incomplete"; - } - } catch (error) { - fallbackReason = error.message || String(error); - } - } - if (fallbackReason) { - core.warning( - `Cannot verify recent runtime producer evidence for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}); falling back to the required refresh dispatch: ${fallbackReason}` - ); - } - if (existingProducers.length > 0) { - const producer = existingProducers[0]; - core.info( - `Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${producer.id} remains ${producer.status}.` - ); - } else { - core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); - await github.rest.repos.createDispatchEvent({ - ...context.repo, - event_type: "pr-runtime-base-refresh", - client_payload: { - pr_number: tuple.prNumber, - base_ref: tuple.baseRef, - base_sha: tuple.baseSha, - head_sha: tuple.headSha, - merge_sha: tuple.mergeSha, - }, - }); - } + // The receiver's concurrency group collapses duplicates and it + // skips the build when the pr-merge tags already exist. + core.info(`Dispatching PR runtime refresh for #${tuple.prNumber} (${tuple.baseRef} / ${tuple.mergeSha}).`); + await dispatch("pr-runtime-base-refresh", target); } else { core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); } @@ -1010,20 +1015,11 @@ jobs: continue; } core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); - await github.rest.repos.createDispatchEvent({ - ...context.repo, - event_type: "preview-deploy", - client_payload: { - action: "deploy", - pr_number: tuple.prNumber, - base_ref: tuple.baseRef, - base_sha: tuple.baseSha, - head_sha: tuple.headSha, - merge_sha: tuple.mergeSha, - preview_domain: "preview.firedevops.net", - }, + await dispatch("preview-deploy", { + ...target, action: "deploy", preview_domain: "preview.firedevops.net", }); } + if (dispatchFailures.length) core.setFailed(dispatchFailures.join("\n")); build-base-image: name: Build Runtime Base Image @@ -1122,8 +1118,8 @@ jobs: build-runtime-images: name: Build Runtime Images (${{ matrix.service }}) - needs: [image-meta, build-base-image] - if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + needs: [image-meta, build-base-image, select-protected-runtime-digests] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.select-protected-runtime-digests.result == 'success' && needs.select-protected-runtime-digests.outputs.missing_services != '' && needs.select-protected-runtime-digests.outputs.missing_services != '[]' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} runs-on: ubuntu-latest permissions: # This job publishes only unique staging service tags. Canonical aliases @@ -1133,18 +1129,7 @@ jobs: strategy: fail-fast: false matrix: - service: - - account-service - - automation-scripting-service - - entity-management-service - - game-design-service - - game-logic-service - - game-session-service - - logging-admin-service - - social-groups-service - - spring-cloud-gateway - - tcp-proxy-service - - world-management-service + service: ${{ fromJSON(needs.select-protected-runtime-digests.outputs.missing_services) }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 @@ -1545,12 +1530,18 @@ jobs: publishable: ${{ steps.runtime-artifact.outcome == 'success' }} name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) needs: [image-meta] - if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.image-meta.outputs.head_current == 'true') || (github.event_name == 'repository_dispatch' && needs.image-meta.outputs.skip_build == 'false') }} runs-on: ubuntu-latest timeout-minutes: 45 + # No cancelling group: GitHub orders cancellation by arrival, so a delayed + # older run could cancel the current one. image-meta skips superseded + # comparisons before smoke instead. + # A repository dispatch runs on the default branch but builds candidate code. + cache-mode: read permissions: # PR-controlled source receives no registry or repository write credential. contents: read + pull-requests: read # Read live PR labels for the PLAY waiver. env: COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} SMOKE_TIMEOUT_SECONDS: 20 @@ -1584,6 +1575,10 @@ jobs: with: requirements: smoke + - name: Set up canonical GitHub CLI + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + uses: ./.github/actions/setup-gh + - name: Set up Java uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: @@ -1665,8 +1660,10 @@ jobs: ${{ steps.minio-source.outputs.client_image_id }} run: bash ./dev-tools/verify-smoke-images.sh --keep-running + # A recomputed retarget merge differs from the run title's merge, so the + # publisher could never select its archive; the typed refresh publishes it. - name: Export fixed-tag preview image artifact - if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') && (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }} run: | service_manifest=/tmp/pr-runtime-services.txt provenance=/tmp/pr-runtime-provenance.json @@ -1733,7 +1730,7 @@ jobs: - name: Upload preview image artifact id: runtime-artifact - if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') && (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} @@ -1745,7 +1742,7 @@ jobs: retention-days: 1 - name: Summarize secure PR runtime artifact - if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') && (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }} env: PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} @@ -1809,17 +1806,13 @@ jobs: fi # Canonical-transition diagnostic evidence, not runtime qualification. The - # native smoke outcome remains failed; only the bounded CI exception may pass. + # native smoke outcome remains failed; only the terminal guard, after a live + # read of the PR's canonical-play-transition label, may let the job pass. - name: Known canonical transition PLAY failure with successful authenticated cleanup id: canonical-play-transition if: >- ${{ always() && github.repository == 'benhook1013/FireMUD' && - ((github.event_name == 'pull_request' && - contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || - (github.event_name == 'repository_dispatch' && - github.event.action == 'pr-runtime-base-refresh' && - needs.image-meta.outputs.canonical_play_transition == 'true')) && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.runtime-smoke.outcome == 'failure' && steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && @@ -1836,29 +1829,49 @@ jobs: RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} + PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} with: script: | - const required = process.env.RUNTIME_SMOKE_REQUIRED; + const env = process.env; + const required = env.RUNTIME_SMOKE_REQUIRED; if (required !== "true" && required !== "false") { core.setFailed("Runtime smoke scope is unavailable or invalid."); - } else if (required === "true" && ( - process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || - (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( - process.env.RUNTIME_SMOKE_OUTCOME === "failure" && - process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" - )) - )) { - core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); - } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { - core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); + return; + } + if (required === "false") return; + if (env.RUNTIME_CLEANUP_OUTCOME !== "success") { + core.setFailed("Required runtime smoke needs successful authenticated cleanup."); + return; + } + if (env.RUNTIME_SMOKE_OUTCOME === "success") return; + if (env.RUNTIME_SMOKE_OUTCOME !== "failure" || env.KNOWN_PLAY_EXCEPTION_OUTCOME !== "success") { + core.setFailed("Required runtime smoke did not pass and is not the exact canonical PLAY transition failure."); + return; + } + // The waiver needs the label now, not when the event was sent. + let labels; + try { + ({data: {labels}} = await github.rest.pulls.get({...context.repo, pull_number: Number(env.PR_NUMBER)})); + } catch (error) { + core.setFailed(`Unable to read the live PR labels for the canonical PLAY transition waiver: ${error.message}`); + return; + } + if (!Array.isArray(labels) || !labels.some(label => label?.name === "canonical-play-transition")) { + core.setFailed("The canonical PLAY transition failure is waived only while the PR carries the canonical-play-transition label."); + return; } + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); pr-controller-smoke: name: PR Hosted Identity Controller Smoke needs: [image-meta] - if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch') && needs.image-meta.outputs.controller_smoke_required == 'true' }} + if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.image-meta.outputs.head_current == 'true') || (github.event_name == 'repository_dispatch' && needs.image-meta.outputs.skip_build == 'false')) && needs.image-meta.outputs.controller_smoke_required == 'true' }} runs-on: ubuntu-latest timeout-minutes: 15 + # No cancelling group: GitHub orders cancellation by arrival, so a delayed + # older run could cancel the current one. image-meta skips superseded + # comparisons before smoke instead. + cache-mode: read permissions: # PR-controlled source receives no registry or repository write credential. contents: read @@ -1903,7 +1916,6 @@ jobs: load: true tags: ${{ env.BASE_IMAGE }} cache-from: type=gha,scope=pr-controller-smoke - cache-to: type=gha,mode=max,scope=pr-controller-smoke - name: Set up Python for Gradle recovery uses: ./.github/actions/setup-python @@ -1926,6 +1938,163 @@ jobs: set -euo pipefail bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null + smoke-gate: + name: Smoke Gate + runs-on: ubuntu-latest + permissions: + checks: read # Preserve a prior successful required context on metadata-only edits. + contents: read # Check out the shared required-gate composite action. + actions: read # Bind preserved proof to its exact workflow run. + statuses: write # Publish acknowledged supplementary metadata gate barriers. + pull-requests: read # Re-read the current PR during metadata preservation. + needs: [changes, image-meta, pr-local-smoke, pr-controller-smoke] + if: ${{ always() && github.event_name == 'pull_request' }} + timeout-minutes: 15 + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Classify smoke gate execution + id: smoke_gate_context + env: + SMOKE_GATE_REQUIRED: ${{ github.event.action != 'edited' || github.event.changes.base.ref != null }} + CHANGES_RESULT: ${{ needs.changes.result }} + run: | + echo "required=$SMOKE_GATE_REQUIRED" >> "$GITHUB_OUTPUT" + if [ "$SMOKE_GATE_REQUIRED" = "true" ] && [ "$CHANGES_RESULT" = "success" ]; then + echo "execute=true" >> "$GITHUB_OUTPUT" + else + echo "execute=false" >> "$GITHUB_OUTPUT" + fi + + - name: Check out required-gate action + if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + + - name: Preserve successful required gate on metadata-only edit + id: preserved_gate + if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} + uses: ./.github/actions/preserve-required-gate + with: + gate-name: Smoke Gate + workflow-name: Build Runtime Images + workflow-file: runtime-images.yml + workflow-path: .github/workflows/runtime-images.yml + + - name: Publish pending required gate status + id: publish-pending-status + if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} + uses: ./.github/actions/publish-required-gate-status + with: + assessment: ${{ steps.preserved_gate.outputs.assessment }} + gate-name: Smoke Gate + workflow-name: Build Runtime Images + workflow-file: runtime-images.yml + workflow-path: .github/workflows/runtime-images.yml + + - name: Report dependency-deferred required gate + if: ${{ !cancelled() && steps.smoke_gate_context.outputs.required != 'true' }} + env: + PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} + ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} + PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} + run: | + case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in + success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) + ;; + *) + echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 + exit 1 + ;; + esac + + - name: Fail when smoke dependencies did not succeed + if: ${{ steps.smoke_gate_context.outputs.required == 'true' && steps.smoke_gate_context.outputs.execute != 'true' }} + env: + CHANGES_RESULT: ${{ needs.changes.result }} + run: | + echo "Smoke change detection did not succeed: changes=$CHANGES_RESULT" >&2 + exit 1 + + - name: Record skipped runtime smoke + if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full != 'true' }} + run: echo "No runtime-stack smoke proof is required for this change." + + - name: Require this run's runtime smoke + if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full == 'true' }} + env: + IMAGE_META_RESULT: ${{ needs.image-meta.result }} + LOCAL_SMOKE_RESULT: ${{ needs.pr-local-smoke.result }} + CONTROLLER_SMOKE_RESULT: ${{ needs.pr-controller-smoke.result }} + CONTROLLER_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.controller_smoke_required }} + run: | + # The terminal guard in PR Full-Stack Smoke already decided the PLAY waiver. + if [[ "$IMAGE_META_RESULT" == success && "$LOCAL_SMOKE_RESULT" == success && + ( "$CONTROLLER_SMOKE_RESULT" == success || + ( "$CONTROLLER_SMOKE_REQUIRED" == false && "$CONTROLLER_SMOKE_RESULT" == skipped ) ) ]]; then + exit 0 + fi + echo "Runtime smoke did not pass: image-meta=$IMAGE_META_RESULT local=$LOCAL_SMOKE_RESULT controller=$CONTROLLER_SMOKE_RESULT" >&2 + exit 1 + + select-protected-runtime-digests: + name: Select Existing Complete Runtime Digest Set + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + packages: read + outputs: + fixed_digests: ${{ steps.select.outputs.fixed_digests }} + missing_services: ${{ steps.select.outputs.missing_services }} + env: + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted runtime selection source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c581273ba90b1 # v7 + with: + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Verify trusted runtime selection revision + run: test "$(git rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR with read access + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Read the fixed digest inventory + id: select + env: + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh + select_existing_fixed_digests + dispatch-pr-runtime-publication: name: Dispatch Trusted PR Runtime Publication needs: [image-meta, pr-local-smoke, pr-controller-smoke] @@ -1951,12 +2120,61 @@ jobs: client_payload: { source_run_id: String(context.runId) }, }); + pin-protected-runtime-digests: + name: Pin Runtime Digest Set for Smoke + needs: [image-meta, build-runtime-images, select-protected-runtime-digests] + if: ${{ always() && !cancelled() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.select-protected-runtime-digests.result == 'success' && ((needs.select-protected-runtime-digests.outputs.missing_services != '' && needs.select-protected-runtime-digests.outputs.missing_services != '[]' && needs.build-runtime-images.result == 'success') || (needs.select-protected-runtime-digests.outputs.missing_services == '[]' && needs.build-runtime-images.result == 'skipped')) }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + packages: read + outputs: + runtime_digests: ${{ steps.pin.outputs.runtime_digests }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted digest inventory source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Verify trusted digest inventory revision + run: test "$(git rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR with read access + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Bind the complete smoke digest set + id: pin + env: + CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + FIXED_RUNTIME_DIGESTS: ${{ needs.select-protected-runtime-digests.outputs.fixed_digests }} + run: | + set -euo pipefail + source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh + pin_runtime_digests + smoke-full: name: Published Runtime Full-Stack Smoke - needs: [image-meta, build-runtime-images] - if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' }} + needs: [image-meta, pin-protected-runtime-digests] + if: ${{ always() && !cancelled() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.pin-protected-runtime-digests.result == 'success' && needs.pin-protected-runtime-digests.outputs.runtime_digests != '' }} permissions: - # The trusted branch smoke workflow only pulls the staged candidate images. + # The trusted smoke workflow pulls the complete fixed and staged set by digest. contents: read packages: read uses: ./.github/workflows/smoke-full.yml @@ -1965,21 +2183,28 @@ jobs: head_sha: ${{ needs.image-meta.outputs.head_sha }} checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} image_tag: ${{ needs.image-meta.outputs.candidate_tag }} + runtime_digests: ${{ needs.pin-protected-runtime-digests.outputs.runtime_digests }} secrets: inherit publish-runtime-images: name: Promote Smoke-Tested Runtime Images - needs: [image-meta, build-runtime-images, smoke-full] - if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + needs: [image-meta, select-protected-runtime-digests, pin-protected-runtime-digests, smoke-full] + if: ${{ always() && !cancelled() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.select-protected-runtime-digests.result == 'success' && needs.pin-protected-runtime-digests.result == 'success' && needs.pin-protected-runtime-digests.outputs.runtime_digests != '' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} runs-on: ubuntu-latest timeout-minutes: 20 + concurrency: + # Fixed SHA tags are shared across branches; branch alias checks remain required. + group: runtime-image-promotion-protected-branches + cancel-in-progress: false + queue: max permissions: contents: read packages: write env: HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} - CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + RUNTIME_DIGESTS: ${{ needs.pin-protected-runtime-digests.outputs.runtime_digests }} + FIXED_RUNTIME_DIGESTS: ${{ needs.select-protected-runtime-digests.outputs.fixed_digests }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 @@ -1989,9 +2214,12 @@ jobs: - name: Checkout trusted publication source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: ${{ needs.image-meta.outputs.checkout_ref }} + ref: ${{ github.workflow_sha }} persist-credentials: false + - name: Verify trusted publication revision + run: test "$(git rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" + - name: Set up canonical GitHub CLI uses: ./.github/actions/setup-gh @@ -2013,109 +2241,25 @@ jobs: run: | set -euo pipefail - services=( - account-service - automation-scripting-service - entity-management-service - game-design-service - game-logic-service - game-session-service - logging-admin-service - social-groups-service - spring-cloud-gateway - tcp-proxy-service - world-management-service - ) - - declare -A registry_tokens=() - registry_manifest_state() { - local image="$1" - local image_path="${image#ghcr.io/}" - local repository_path="${image_path%:*}" - local tag="${image_path##*:}" - local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" - local registry_token="${registry_tokens[$repository_path]:-}" - local status - - [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { - echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 - return 1 - } - if [[ -z "$registry_token" ]]; then - if ! registry_token="$(curl --silent --show-error --location --fail \ - --connect-timeout 10 --max-time 30 \ - --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ - --get \ - --data-urlencode 'service=ghcr.io' \ - --data-urlencode "scope=repository:${repository_path}:pull" \ - --header 'Accept: application/json' \ - 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then - echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 - return 1 - fi - registry_tokens["$repository_path"]="$registry_token" - fi - # `docker manifest inspect "$image"` conflates a 404 with auth, - # registry, and network failures, so it is never an absence check. - if ! status="$(curl --silent --show-error --location --head \ - --connect-timeout 10 --max-time 30 \ - --header "Authorization: Bearer ${registry_token}" \ - --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ - --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then - echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 - return 1 - fi - case "$status" in - 200) printf 'existing\n' ;; - 404) printf 'missing\n' ;; - *) - echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 - return 1 - ;; - esac - } - - registry_digest() { - local image="$1" - local inspect_output inspect_status - local digest - if inspect_output="$(docker buildx imagetools inspect "$image")"; then - : - else - inspect_status=$? - echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 - return "$inspect_status" - fi - digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" - [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { - echo "Registry manifest for $image has no exact digest." >&2 - return 1 - } - printf '%s\n' "$digest" - } - - assert_current_branch_head() { - local current_sha - current_sha="$(gh api \ - "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ - --jq '.object.sha')" - [[ "$current_sha" == "$HEAD_SHA" ]] || { - echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 - exit 1 - } - } + source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh promote_alias() { - local source="$1" target="$2" fixed="$3" - local source_digest existing_digest target_digest - source_digest="$(registry_digest "$source")" + local source="$1" target="$2" fixed="$3" retained_digest="${4:-}" + local source_digest="${source##*@}" existing_digest target_digest local target_state - if ! target_state="$(registry_manifest_state "$target")"; then + if ! registry_manifest_state "$target" target_state; then echo "Immutable target preflight failed for $target; refusing to publish." >&2 exit 1 fi if [[ "$target_state" == missing ]]; then - docker buildx imagetools create --tag "$target" "$source" + if [[ "$fixed" == true && -n "$retained_digest" ]]; then + echo "Fixed runtime tag $target disappeared after smoke qualification." >&2 + exit 1 + fi + if [[ "$fixed" != true ]]; then + assert_current_branch_head + fi + docker buildx imagetools create --prefer-index=false --tag "$target" "$source" else existing_digest="$(registry_digest "$target")" if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then @@ -2123,7 +2267,8 @@ jobs: exit 1 fi if [[ "$existing_digest" != "$source_digest" ]]; then - docker buildx imagetools create --tag "$target" "$source" + assert_current_branch_head + docker buildx imagetools create --prefer-index=false --tag "$target" "$source" fi fi target_digest="$(registry_digest "$target")" @@ -2133,17 +2278,20 @@ jobs: } } + preflight_fixed_digest_set || { + preflight_status=$? + echo 'If another run published a fixed SHA tag after selection, use Re-run all jobs to reselect and smoke-test the entire set before promotion.' >&2 + exit "$preflight_status" + } for service in "${services[@]}"; do - candidate="ghcr.io/benhook1013/${service}:${CANDIDATE_TAG}" + candidate="${smoke_sources[$service]}" sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" assert_current_branch_head - promote_alias "$candidate" "$sha_tag" true - assert_current_branch_head + promote_alias "$candidate" "$sha_tag" true "${retained_fixed[$service]}" promote_alias "$candidate" "$branch_tag" false if [[ "$HEAD_BRANCH" == develop ]]; then - assert_current_branch_head promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false fi done diff --git a/.github/workflows/smoke-full.yml b/.github/workflows/smoke-full.yml index 2314df4900..b973c2c8fa 100644 --- a/.github/workflows/smoke-full.yml +++ b/.github/workflows/smoke-full.yml @@ -16,6 +16,11 @@ on: image_tag: required: true type: string + runtime_digests: + description: Exact registry digest for each runtime service + required: false + default: "" + type: string workflow_dispatch: inputs: action: @@ -75,8 +80,85 @@ jobs: with: requirements: smoke + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Checkout trusted smoke entrypoint and override + if: ${{ inputs.runtime_digests != '' }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.workflow_sha }} + path: .trusted-runtime-workflow + persist-credentials: false + + - name: Install the trusted digest-aware smoke override + if: ${{ inputs.runtime_digests != '' }} + run: | + set -euo pipefail + test "$(git -C .trusted-runtime-workflow rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" + install -T .trusted-runtime-workflow/docker/docker-compose.smoke-images.override.yml \ + docker/docker-compose.smoke-images.override.yml + + - name: Export exact runtime image references + if: ${{ inputs.runtime_digests != '' }} + env: + RUNTIME_DIGESTS: ${{ inputs.runtime_digests }} + run: | + python3 - <<'PY' + import json + import os + import re + + runtime_services = { + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", + } + + def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate key in runtime_digests") + result[key] = value + return result + + try: + digests = json.loads(os.environ["RUNTIME_DIGESTS"], object_pairs_hook=unique_object) + except ValueError: + raise SystemExit("runtime_digests must be valid JSON without duplicate keys") + if not isinstance(digests, dict) or digests.keys() != runtime_services: + raise SystemExit("runtime_digests must contain exactly the 11 runtime service names") + for service, digest in digests.items(): + if not isinstance(digest, str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", digest): + raise SystemExit(f"runtime_digests has an invalid digest for {service}") + + refs = { + "SMOKE_IMAGE_REF_" + service.upper().replace("-", "_"): f"ghcr.io/benhook1013/{service}@{digest}" + for service, digest in digests.items() + } + with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as environment: + for variable, image in refs.items(): + environment.write(f"{variable}={image}\n") + PY + - name: Generate Dev Certificates - run: ./dev-tools/certs/generate-dev-certs.sh + env: + FIREMUD_SMOKE_RUNTIME_DIGESTS: ${{ inputs.runtime_digests }} + run: | + if [[ -n "$FIREMUD_SMOKE_RUNTIME_DIGESTS" ]]; then + ./.trusted-runtime-workflow/dev-tools/certs/generate-dev-certs.sh ./dev-tools/certs + else + ./dev-tools/certs/generate-dev-certs.sh + fi - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 @@ -86,7 +168,16 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: ๐Ÿงช Run Canonical Image Smoke Proof - run: SMOKE_IMAGE_TAG="${{ inputs.image_tag }}" bash ./dev-tools/verify-smoke-images.sh --keep-running + env: + FIREMUD_SMOKE_RUNTIME_DIGESTS: ${{ inputs.runtime_digests }} + run: | + set -euo pipefail + if [[ -n "$FIREMUD_SMOKE_RUNTIME_DIGESTS" ]]; then + FIREMUD_SMOKE_SOURCE_ROOT="$GITHUB_WORKSPACE" \ + bash .trusted-runtime-workflow/dev-tools/verify-smoke-images.sh --keep-running + else + bash ./dev-tools/verify-smoke-images.sh --keep-running + fi - name: ๐Ÿ“œ Dump Docker Compose Logs on Failure if: failure() @@ -101,12 +192,34 @@ jobs: - name: ๐Ÿงน Stop Smoke Stack if: always() + env: + FIREMUD_SMOKE_RUNTIME_DIGESTS: ${{ inputs.runtime_digests }} run: | - source ./dev-tools/smoke/run-owned-compose.sh - if ! stop_run_owned_compose_project \ + set -euo pipefail + tools_root=. + if [[ -n "$FIREMUD_SMOKE_RUNTIME_DIGESTS" ]]; then + tools_root=.trusted-runtime-workflow + test "$(git -C "$tools_root" rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" + fi + source "$tools_root/dev-tools/smoke/run-owned-compose.sh" + # Restore the run-owned mount paths required to parse the startup Compose files. + _firemud_smoke_prepare + _firemud_smoke_initial_admission_context + export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" + compose_files=( -f docker/docker-compose.yml \ -f docker/docker-compose.override.yml \ - -f docker/docker-compose.smoke-images.override.yml; then + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.grpc-mtls.override.yml + ) + if [[ -n "$FIREMUD_SMOKE_RUNTIME_DIGESTS" ]]; then + protected_config="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.compose.json" + compose_files=(--project-directory "$PWD/docker" -f "$protected_config") + fi + if ! stop_run_owned_compose_project "${compose_files[@]}"; then echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 exit 1 fi + if [[ -n "$FIREMUD_SMOKE_RUNTIME_DIGESTS" ]]; then + rm -f -- "$protected_config" + fi diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml deleted file mode 100644 index c919aac6b6..0000000000 --- a/.github/workflows/smoke.yml +++ /dev/null @@ -1,1478 +0,0 @@ -name: PR Smoke Gate - -on: - pull_request: - types: [opened, synchronize, reopened, edited] - -run-name: PR Smoke Gate ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }} - -permissions: - contents: read - -concurrency: - group: smoke-${{ github.workflow }}-${{ format('pr-{0}-controller', github.event.pull_request.number) }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && format('metadata-{0}', github.run_id) || 'required' }} - cancel-in-progress: true - -jobs: - changes: - name: Detect Smoke-Relevant Changes - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read - if: ${{ github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} - outputs: - run_smoke_full: ${{ steps.compute.outputs.run_smoke_full }} - steps: - - name: Harden runner - uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 - with: - egress-policy: audit - - - name: Compute smoke scope - id: compute - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - with: - script: | - const fileEntries = await github.paginate( - github.rest.pulls.listFiles, - { - ...context.repo, - pull_number: context.payload.pull_request.number, - per_page: 100, - }, - (response) => response.data - ); - - const expectedFileCount = context.payload.pull_request.changed_files; - const fileListComplete = - Number.isInteger(expectedFileCount) && expectedFileCount === fileEntries.length; - const fileEntriesValid = fileEntries.every((file) => - file && - typeof file === "object" && - typeof file.filename === "string" && - file.filename.length > 0 && - (file.previous_filename === undefined || - (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) - ); - const files = fileEntriesValid - ? fileEntries.flatMap((file) => - [file.filename, file.previous_filename].filter(Boolean) - ) - : []; - - if (!fileListComplete || !fileEntriesValid) { - core.warning("PR file-list detection was incomplete; requiring full-stack smoke."); - core.setOutput("run_smoke_full", "true"); - return; - } - - const docsOnlyPredicate = (file) => - file === "AGENTS.md" || - file === "mkdocs.yml" || - file.startsWith("design/") || - file.startsWith("dev-tools/docs/") || - file.endsWith(".md"); - - const frontendOnlyPredicate = (file) => - file.startsWith("web-client/") || - file.startsWith("config/openapi/"); - - const fullRelevantPrefixes = [ - "buildSrc/", - "gradle/", - "protos/", - "docker/", - "services/", - ".github/actions/load-workflow-tool-versions/", - ".github/actions/setup-python/", - "dev-tools/smoke/", - "dev-tools/minio/", - ]; - const fullRelevantFiles = new Set([ - "build.gradle.kts", - "settings.gradle.kts", - "gradle.properties", - "gradlew", - "gradlew.bat", - ".dockerignore", - ".python-version", - ".github/actions/load-workflow-tool-versions/action.yml", - ".github/workflows/smoke.yml", - ".github/workflows/smoke-full.yml", - ".github/workflows/runtime-images.yml", - ".github/workflows/publish-pr-runtime-images.yml", - "config/workflow-tool-versions.env", - "config/python/smoke-requirements.txt", - "config/python/smoke-requirements.in", - "dev-tools/build-compose-service-jars.sh", - "dev-tools/validation/run-gradle-with-dependency-recovery.sh", - "dev-tools/validation/run-locked-gradle.sh", - "dev-tools/validation/gradle-run-supervisor.py", - "dev-tools/build-local-smoke-images.sh", - "dev-tools/backups/verify-backups.sh", - "dev-tools/backups/pg-dump-s3-selection.shlib", - "dev-tools/backups/smoke-backup-verifier-image.sh", - "dev-tools/certs/generate-dev-certs.sh", - "dev-tools/verify-compose-health.sh", - "dev-tools/verify-fresh-bootstrap.sh", - "dev-tools/verify-restart-state.sh", - "dev-tools/verify-smoke-images.sh", - ]); - - const nonDocFiles = files.filter((file) => !docsOnlyPredicate(file)); - const nonDocsAreFrontendOnly = - nonDocFiles.length > 0 && nonDocFiles.every((file) => frontendOnlyPredicate(file)); - - if (nonDocFiles.length === 0 || nonDocsAreFrontendOnly) { - core.setOutput("run_smoke_full", "false"); - return; - } - - const runSmokeFull = nonDocFiles.some( - (file) => - fullRelevantFiles.has(file) || - fullRelevantPrefixes.some( - (prefix) => - file.startsWith(prefix) && - !file.startsWith("services/hosted-environment-identity-controller/") - ) - ); - core.setOutput("run_smoke_full", runSmokeFull ? "true" : "false"); - - smoke-summary-pending: - name: Smoke Summary (Pending) - runs-on: ubuntu-latest - permissions: - # This job publishes the initial pending state; Smoke Summary publishes the terminal state. - contents: read - pull-requests: write - needs: [changes] - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} - steps: - - name: Harden runner - uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 - with: - egress-policy: audit - - - name: ๐Ÿ’ฌ Publish Pending Smoke Summary Comment - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - CHANGES_RESULT: ${{ needs.changes.result }} - RUN_SMOKE_FULL: ${{ needs.changes.outputs.run_smoke_full }} - with: - script: | - const rawChangesResult = process.env.CHANGES_RESULT || ""; - const changesStatus = ["success", "failure", "cancelled"].includes(rawChangesResult) - ? rawChangesResult - : "unavailable"; - const changesHealthy = changesStatus === "success"; - const fullEnabled = process.env.RUN_SMOKE_FULL === "true"; - const smokeGateStatus = fullEnabled ? "pending" : "not-required"; - const fullResult = !changesHealthy - ? `not-evaluated (${changesStatus} changes detection)` - : fullEnabled - ? "tracked-by-smoke-gate" - : "skipped (run_smoke_full=false)"; - const statusIcon = (value) => { - if (value === "success") return "โœ…"; - if (value === "failure" || value.startsWith("failure (")) return "โŒ"; - if (value === "cancelled") return "โšช"; - if (value === "pending") return "โณ"; - if (value === "unavailable") return "โš ๏ธ"; - if (value.startsWith("not-evaluated")) return "โš ๏ธ"; - return "โญ๏ธ"; - }; - - let headline = "โญ๏ธ Runtime smoke is not required"; - if (!changesHealthy) { - headline = `โš ๏ธ Smoke scope detection ${changesStatus}; Smoke Gate is still authoritative`; - } else if (fullEnabled) { - headline = "โณ Full-stack smoke runs in Build Runtime Images and is tracked by Smoke Gate"; - } - - const body = [ - "", - "### Smoke Summary", - headline, - "", - `- ${statusIcon(changesStatus)} Changes detection: \`${changesStatus}\``, - `- ${statusIcon(smokeGateStatus)} Smoke Gate: \`${smokeGateStatus}\``, - `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, - ].join("\n"); - - const expectedHeadSha = context.payload.pull_request.head.sha; - const expectedBaseRef = context.payload.pull_request.base.ref; - const expectedBaseSha = context.payload.pull_request.base.sha; - const { data: currentPullRequest } = await github.rest.pulls.get({ - ...context.repo, - pull_number: context.issue.number, - }); - if ( - currentPullRequest.state !== "open" || - currentPullRequest.head.sha !== expectedHeadSha || - currentPullRequest.base.ref !== expectedBaseRef || - currentPullRequest.base.sha !== expectedBaseSha - ) { - core.info( - `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + - `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` - ); - return; - } - - const comments = await github.paginate( - github.rest.issues.listComments, - { - ...context.repo, - issue_number: context.issue.number, - per_page: 100, - } - ); - - const isBotAuthored = (comment) => comment.user?.login === "github-actions[bot]"; - const isWorkflowComment = (comment) => { - const body = comment.body ?? ""; - return isBotAuthored(comment) && body.includes(""); - }; - const isLegacyWorkflowComment = (comment) => { - const body = comment.body ?? ""; - return isBotAuthored(comment) && body.startsWith("### Smoke Summary"); - }; - const summaryComments = []; - const seenCommentIds = new Set(); - for (const comment of comments) { - if ((!isWorkflowComment(comment) && !isLegacyWorkflowComment(comment)) || seenCommentIds.has(comment.id)) { - continue; - } - seenCommentIds.add(comment.id); - summaryComments.push(comment); - } - const commentTimestamp = (comment) => { - const parsed = Date.parse(comment.created_at || ""); - return Number.isNaN(parsed) ? Number.MAX_SAFE_INTEGER : parsed; - }; - const existing = summaryComments.reduce((oldest, comment) => { - if (!oldest) return comment; - const oldestTimestamp = commentTimestamp(oldest); - const candidateTimestamp = commentTimestamp(comment); - if (candidateTimestamp !== oldestTimestamp) { - return candidateTimestamp < oldestTimestamp ? comment : oldest; - } - return Number(comment.id) < Number(oldest.id) ? comment : oldest; - }, null); - - const deleteCommentIfPresent = async (comment) => { - try { - await github.rest.issues.deleteComment({ - ...context.repo, - comment_id: comment.id, - }); - } catch (error) { - if (error.status !== 404) throw error; - } - }; - - if (existing && existing.body !== body) { - await github.rest.issues.updateComment({ - ...context.repo, - comment_id: existing.id, - body - }); - } else if (!existing) { - await github.rest.issues.createComment({ - ...context.repo, - issue_number: context.issue.number, - body - }); - } - - for (const comment of summaryComments) { - if (String(comment.id) === String(existing?.id)) continue; - await deleteCommentIfPresent(comment); - } - - smoke-summary: - name: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Summary)' || 'Smoke Summary' }} - runs-on: ubuntu-latest - permissions: - # This job updates the canonical comment to the terminal Smoke Gate result. - contents: read - pull-requests: write - needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} - steps: - - name: Harden runner - uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 - with: - egress-policy: audit - - - name: ๐Ÿ’ฌ Publish Smoke Summary Comment - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - CHANGES_RESULT: ${{ needs.changes.result }} - RUN_SMOKE_FULL: ${{ needs.changes.outputs.run_smoke_full }} - SMOKE_GATE_RESULT: ${{ needs.smoke-gate.result }} - KNOWN_PLAY_EXCEPTION: ${{ needs.smoke-gate.outputs.known_play_exception }} - with: - script: | - const rawChangesResult = process.env.CHANGES_RESULT || ""; - const changesStatus = ["success", "failure", "cancelled"].includes(rawChangesResult) - ? rawChangesResult - : "unavailable"; - const changesHealthy = changesStatus === "success"; - const fullEnabled = process.env.RUN_SMOKE_FULL === "true"; - const rawSmokeGateResult = process.env.SMOKE_GATE_RESULT || ""; - const smokeGateStatus = ["success", "failure", "cancelled", "skipped"].includes(rawSmokeGateResult) - ? rawSmokeGateResult - : "unavailable"; - const knownPlayException = process.env.KNOWN_PLAY_EXCEPTION === "true" && smokeGateStatus === "success"; - const fullResult = knownPlayException - ? "failure (known PLAY exception accepted; no runtime qualification or publication)" - : !changesHealthy - ? `not-evaluated (${changesStatus} changes detection)` - : fullEnabled - ? smokeGateStatus - : "skipped (run_smoke_full=false)"; - const statusIcon = (value) => { - if (value === "success") return "โœ…"; - if (value === "failure" || value.startsWith("failure (")) return "โŒ"; - if (value === "cancelled") return "โšช"; - if (value === "skipped") return "โญ๏ธ"; - if (value === "unavailable") return "โš ๏ธ"; - if (value.startsWith("not-evaluated")) return "โš ๏ธ"; - return "โญ๏ธ"; - }; - - let headline = "โญ๏ธ Runtime smoke is not required"; - if (!changesHealthy) { - headline = `${statusIcon(smokeGateStatus)} Smoke Gate completed with ${smokeGateStatus}; scope detection was ${changesStatus}`; - } else if (knownPlayException) { - headline = "โš ๏ธ Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Canonical PLAY transition exception accepted; no runtime qualification or publication."; - } else if (fullEnabled) { - headline = `${statusIcon(smokeGateStatus)} Full-stack smoke completed with Smoke Gate: ${smokeGateStatus}`; - } - - const body = [ - "", - "### Smoke Summary", - headline, - "", - `- ${statusIcon(changesStatus)} Changes detection: \`${changesStatus}\``, - `- ${statusIcon(smokeGateStatus)} Smoke Gate: \`${smokeGateStatus}\``, - `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, - ].join("\n"); - - const expectedHeadSha = context.payload.pull_request.head.sha; - const expectedBaseRef = context.payload.pull_request.base.ref; - const expectedBaseSha = context.payload.pull_request.base.sha; - const { data: currentPullRequest } = await github.rest.pulls.get({ - ...context.repo, - pull_number: context.issue.number, - }); - if ( - currentPullRequest.state !== "open" || - currentPullRequest.head.sha !== expectedHeadSha || - currentPullRequest.base.ref !== expectedBaseRef || - currentPullRequest.base.sha !== expectedBaseSha - ) { - core.info( - `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + - `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` - ); - return; - } - - const comments = await github.paginate( - github.rest.issues.listComments, - { - ...context.repo, - issue_number: context.issue.number, - per_page: 100, - } - ); - - const isBotAuthored = (comment) => comment.user?.login === "github-actions[bot]"; - const isWorkflowComment = (comment) => { - const body = comment.body ?? ""; - return isBotAuthored(comment) && body.includes(""); - }; - const isLegacyWorkflowComment = (comment) => { - const body = comment.body ?? ""; - return isBotAuthored(comment) && body.startsWith("### Smoke Summary"); - }; - const summaryComments = []; - const seenCommentIds = new Set(); - for (const comment of comments) { - if ((!isWorkflowComment(comment) && !isLegacyWorkflowComment(comment)) || seenCommentIds.has(comment.id)) { - continue; - } - seenCommentIds.add(comment.id); - summaryComments.push(comment); - } - const commentTimestamp = (comment) => { - const parsed = Date.parse(comment.created_at || ""); - return Number.isNaN(parsed) ? Number.MAX_SAFE_INTEGER : parsed; - }; - const existing = summaryComments.reduce((oldest, comment) => { - if (!oldest) return comment; - const oldestTimestamp = commentTimestamp(oldest); - const candidateTimestamp = commentTimestamp(comment); - if (candidateTimestamp !== oldestTimestamp) { - return candidateTimestamp < oldestTimestamp ? comment : oldest; - } - return Number(comment.id) < Number(oldest.id) ? comment : oldest; - }, null); - - const deleteCommentIfPresent = async (comment) => { - try { - await github.rest.issues.deleteComment({ - ...context.repo, - comment_id: comment.id, - }); - } catch (error) { - if (error.status !== 404) throw error; - } - }; - - if (existing && existing.body !== body) { - await github.rest.issues.updateComment({ - ...context.repo, - comment_id: existing.id, - body - }); - } else if (!existing) { - await github.rest.issues.createComment({ - ...context.repo, - issue_number: context.issue.number, - body - }); - } - - for (const comment of summaryComments) { - if (String(comment.id) === String(existing?.id)) continue; - await deleteCommentIfPresent(comment); - } - - smoke-gate: - outputs: - known_play_exception: ${{ steps.track-runtime-smoke.outputs.known_play_exception }} - name: Smoke Gate - runs-on: ubuntu-latest - permissions: - checks: read # Preserve a prior successful required context on metadata-only edits. - contents: read # Check out the shared required-gate composite action. - actions: read # Inspect matching runtime-image workflow and job results. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR head and base before accepting smoke. - needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' }} - timeout-minutes: 95 - steps: - - name: Harden runner - uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 - with: - egress-policy: audit - - - name: Classify smoke gate execution - id: smoke_gate_context - env: - SMOKE_GATE_REQUIRED: ${{ github.event.action != 'edited' || github.event.changes.base.ref != null }} - CHANGES_RESULT: ${{ needs.changes.result }} - run: | - echo "required=$SMOKE_GATE_REQUIRED" >> "$GITHUB_OUTPUT" - if [ "$SMOKE_GATE_REQUIRED" = "true" ] && [ "$CHANGES_RESULT" = "success" ]; then - echo "execute=true" >> "$GITHUB_OUTPUT" - else - echo "execute=false" >> "$GITHUB_OUTPUT" - fi - - - name: Check out required-gate action - if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: Smoke Gate - workflow-name: PR Smoke Gate - workflow-file: smoke.yml - workflow-path: .github/workflows/smoke.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: Smoke Gate - workflow-name: PR Smoke Gate - workflow-file: smoke.yml - workflow-path: .github/workflows/smoke.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && steps.smoke_gate_context.outputs.required != 'true' }} - env: - PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} - ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} - PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} - run: | - case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in - success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) - ;; - *) - echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 - exit 1 - ;; - esac - - - name: Fail when smoke dependencies did not succeed - if: ${{ steps.smoke_gate_context.outputs.required == 'true' && steps.smoke_gate_context.outputs.execute != 'true' }} - env: - CHANGES_RESULT: ${{ needs.changes.result }} - run: | - echo "Smoke change detection did not succeed: changes=$CHANGES_RESULT" >&2 - exit 1 - - - name: Record skipped runtime smoke - if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full != 'true' }} - run: echo "No runtime-stack smoke proof is required for this change." - - - name: Track full-stack smoke result from Build Runtime Images - id: track-runtime-smoke - if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full == 'true' }} - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - with: - script: | - const owner = context.repo.owner; - const repo = context.repo.repo; - const headSha = context.payload.pull_request.head.sha; - const baseRef = context.payload.pull_request.base.ref; - const eventBaseSha = context.payload.pull_request.base.sha; - const eventMergeSha = context.sha; - const prNumber = String(context.payload.pull_request.number); - const started = Date.now(); - // Contract-checked against pr-local-smoke; bounded overhead covers metadata, - // runner scheduling and API convergence, not unbounded queue delays. - const producerTimeoutMinutes = 45; - const prerequisiteAndQueueAllowanceMinutes = 45; - const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; - const cancelledReplacementTimeoutMs = 5 * 60 * 1000; - const sleepMs = 30000; - const snapshotSleepMs = 15000; - const pullRequestCheckInterval = 2; - const retryableStatuses = new Set([408, 425, 429, 500, 502, 503, 504]); - let pollIteration = 0; - let identityDiagnostic = "current PR identity has not been resolved"; - - class TerminalGitHubRequestError extends Error {} - - async function withTransientGitHubRetry(label, operation) { - const maxAttempts = 4; - let retryDelayMs = 1000; - for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { - try { - return await operation(); - } catch (error) { - const status = error?.status ?? error?.response?.status; - const headers = error?.response?.headers ?? {}; - const reset = String(headers["x-ratelimit-reset"] ?? ""); - const resetSeconds = Number(reset); - const quotaExhausted = status === 403 && - String(headers["x-ratelimit-remaining"]) === "0" && - /^[0-9]+$/.test(reset) && Number.isSafeInteger(resetSeconds) && resetSeconds > 0; - const delayMs = quotaExhausted - ? Math.max(1000, resetSeconds * 1000 - Date.now() + 1000) - : retryDelayMs; - const remainingMs = timeoutMs - (Date.now() - started); - const retryable = quotaExhausted || status == null || retryableStatuses.has(status); - if (!retryable || attempt === maxAttempts || delayMs >= remainingMs) { - if (status === 403) { - throw new TerminalGitHubRequestError(`${label}: ${error.message ?? "GitHub refused the request"}`, { cause: error }); - } - throw error; - } - core.warning( - `${label} failed transiently (status=${status ?? "network"}); retrying in ${delayMs}ms` - ); - await new Promise((resolve) => setTimeout(resolve, delayMs)); - retryDelayMs *= 2; - } - } - throw new Error(`${label} retry loop exited unexpectedly`); - } - - // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "2a769961890119fc91a83b2987537122704f6624035d1572b446569d5f9d11a1"; - // Before this change merges, successful refreshes still run the current default-branch definition. - const canonicalPreMergeTrustedRefreshRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; - // Trusted refreshes can still execute the previous successful default-branch definition. - const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; - // Retain the exact fail-red producer still executed by trusted base refreshes. - const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; - // Include held-admission proof, authenticated cleanup, and their executed inputs. - const canonicalPlayClassifierSha256 = { - "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", - "dev-tools/smoke/smoke_common.py": "a1e36948b500ac796295560cb8c22321ebe47eab78be9e1f4d58837053547534", - "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b", - "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", - "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", - "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", - "dev-tools/smoke/run-owned-compose.sh": "c2a0590c98d39a8c8ec22c20e692948136a5ec53ca2dfc0b29db7323a3e1b6be", - "dev-tools/certs/ensure-dev-certs.sh": "30f4ab5c9cb7af7f9d4a477ce923cfad19a319a85b6e05957f7d24eae9baddd2", - ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", - "docker/docker-compose.yml": "5a59a4d3baa8b61b7b1ab2c982a482cd648a9d044be2562205c80cb05efe8b00", - "docker/docker-compose.override.yml": "acae1e8d947a5cab071a581873d2cc721f907a8d506bf59e875c5b069c38b126", - "docker/docker-compose.smoke-images.override.yml": "7717be8b49a1dc548a47fba852c181feeb4dbe9a21fc201a7f8e74b992801fd6", - "docker/docker-compose.pr-local-minio.override.yml": "d975ce211afcb73079a21c70fda358e3a8f3366b83fe0302907c9d7149ce965e", - "docker/docker-compose.grpc-mtls.override.yml": "dcee047f1492392035d57153ba8dfd6d38de33ca932d327f377440d5813577f0" - }; - const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; - const workflowPath = ".github/workflows/runtime-images.yml"; - const repositoryName = `${owner}/${repo}`; - const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; - const preExecutionCancelledJobNames = new Set([ - "Derive Runtime Image Metadata", - "Dispatch PR Base Refreshes", - "Build Runtime Base Image", - "Build Backup Verifier Image", - "PR Hosted Identity Controller Smoke", - "PR Full-Stack Smoke (runtime-required=$" + "{{ needs.image-meta.outputs.runtime_smoke_required }})", - "Publish Trusted Backup Verifier Image", - "Published Runtime Full-Stack Smoke", - "Dispatch Trusted PR Runtime Publication", - "Build Runtime Images ($" + "{{ matrix.service }})", - "Build Trusted Hosted Identity Controller", - "Publish Trusted Hosted Identity Controller", - "Promote Smoke-Tested Runtime Images", - ]); - - const preExecutionCancelledProofs = new Set(); - async function isPreExecutionCancelledAttempt(run, expectedDisplayTitle, identity) { - if (run.event !== "pull_request" || run.status !== "completed" || run.conclusion !== "cancelled" || - !positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; - const headRepository = context.payload.pull_request.head.repo?.full_name; - if (typeof headRepository !== "string" || headRepository.length === 0) return false; - const attemptPath = "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"; - const requestAttempt = () => withTransientGitHubRetry( - "exact cancelled runtime attempt lookup", - () => github.request(attemptPath, { - owner, repo, run_id: run.id, attempt_number: run.run_attempt, - }) - ); - const exactAttempt = (source) => source.id === run.id && - source.run_attempt === run.run_attempt && source.status === "completed" && - source.conclusion === "cancelled" && source.path === workflowPath && - source.repository?.full_name === repositoryName && - source.workflow_id === run.workflow_id && positiveInteger(source.workflow_id) && - source.event === "pull_request" && run.event === "pull_request" && - source.display_title === expectedDisplayTitle && - run.display_title === expectedDisplayTitle && - source.head_sha === identity.headSha && run.head_sha === identity.headSha && - source.head_repository?.full_name === headRepository; - const latestAttempt = async () => { - const { data } = await withTransientGitHubRetry( - "current cancelled runtime run lookup", - () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: run.id }) - ); - return data.id === run.id && data.run_attempt === run.run_attempt && - data.status === "completed" && data.conclusion === "cancelled"; - }; - const proofKey = JSON.stringify([ - repositoryName, workflowPath, run.id, run.run_attempt, run.workflow_id, - run.display_title, run.head_sha, expectedDisplayTitle, identity.headSha, headRepository, - ]); - try { - // Attempt/workflow/job proof is immutable; the latest attempt is always fresh. - if (preExecutionCancelledProofs.has(proofKey)) return await latestAttempt(); - const { data: before } = await requestAttempt(); - if (!exactAttempt(before) || !(await latestAttempt())) return false; - const { data: workflow } = await withTransientGitHubRetry( - "cancelled runtime workflow identity lookup", - () => github.rest.actions.getWorkflow({ owner, repo, workflow_id: before.workflow_id }) - ); - if (workflow.id !== before.workflow_id || workflow.path !== workflowPath || - workflow.name !== "Build Runtime Images") return false; - const jobs = await withTransientGitHubRetry( - "exact cancelled runtime attempt jobs lookup", - () => github.paginate( - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - { owner, repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100 } - ) - ); - if (!Array.isArray(jobs) || jobs.length !== preExecutionCancelledJobNames.size) return false; - const jobIds = new Set(); - const jobNames = new Set(); - for (const job of jobs) { - if (!positiveInteger(job.id) || jobIds.has(job.id) || job.run_id !== run.id || - jobNames.has(job.name) || - !preExecutionCancelledJobNames.has(job.name) || - job.status !== "completed" || !["cancelled", "skipped"].includes(job.conclusion) || - !Array.isArray(job.steps) || job.steps.length !== 0) return false; - jobIds.add(job.id); - jobNames.add(job.name); - } - if (jobNames.size !== preExecutionCancelledJobNames.size) return false; - const { data: after } = await requestAttempt(); - if (!exactAttempt(after) || !(await latestAttempt())) return false; - preExecutionCancelledProofs.add(proofKey); - return true; - } catch (error) { - core.warning(`Cancelled runtime attempt ${run.id}/${run.run_attempt} is not proven pre-execution: ${error.message}`); - return false; - } - } - - function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { - return definitionHash === canonicalRuntimeWorkflowSha256 || - (sourceEvent === "repository_dispatch" && - definitionHash === canonicalPreviousTrustedRefreshRuntimeWorkflowSha256); - } - - async function verifyCanonicalSmokeProducer(run, candidate, identity) { - if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; - const { data: source } = await withTransientGitHubRetry( - "exact runtime workflow attempt lookup", - () => github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}", { - owner, repo, run_id: run.id, attempt_number: run.run_attempt, - }) - ); - const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + - `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; - if ( - source.id !== run.id || source.run_attempt !== run.run_attempt || - source.status !== "completed" || source.conclusion !== "success" || - source.path !== workflowPath || source.repository?.full_name !== repositoryName || - !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || - source.event !== run.event || !["pull_request", "repository_dispatch"].includes(source.event) - ) return false; - const expectedHeadRepository = source.event === "pull_request" - ? context.payload.pull_request.head.repo?.full_name - : repositoryName; - if (typeof expectedHeadRepository !== "string" || - source.head_repository?.full_name !== expectedHeadRepository) return false; - if (source.event === "pull_request" && source.head_sha !== identity.headSha) return false; - if (source.event === "repository_dispatch" && ( - source.head_branch !== context.payload.repository.default_branch || - !/^[0-9a-f]{40}$/.test(source.head_sha ?? "") - )) return false; - const { data: workflow } = await withTransientGitHubRetry( - "runtime workflow identity lookup", - () => github.rest.actions.getWorkflow({ owner, repo, workflow_id: source.workflow_id }) - ); - if (workflow.id !== source.workflow_id || workflow.path !== workflowPath || - workflow.name !== "Build Runtime Images") return false; - const jobs = await withTransientGitHubRetry( - "exact runtime attempt jobs lookup", - () => github.paginate( - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - { owner, repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100 } - ) - ); - const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); - if (producers.length !== 1) return false; - const job = producers[0]; - if ( - !positiveInteger(job.id) || job.id !== candidate.id || - job.run_id !== source.id || job.run_attempt !== source.run_attempt || - job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== "success" || - job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` - ) return false; - const markers = (job.steps ?? []).filter((step) => - step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" - ); - // PR workflows execute their test merge definition; typed refreshes execute the - // immutable default-branch revision recorded by their native run attempt. - const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; - const { data: definition } = await withTransientGitHubRetry( - "immutable runtime workflow definition lookup", - () => github.rest.repos.getContent({ owner, repo, path: workflowPath, ref: workflowSha }) - ); - if (definition.type !== "file" || definition.path !== workflowPath || - definition.encoding !== "base64" || typeof definition.content !== "string") return false; - const bytes = Buffer.from(definition.content, "base64"); - if (definition.size !== bytes.length) return false; - const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); - const preMergeTrustedRefresh = source.event === "repository_dispatch" && - definitionHash === canonicalPreMergeTrustedRefreshRuntimeWorkflowSha256; - if (isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event) || preMergeTrustedRefresh) { - if (markers.length !== 1 || markers[0].status !== "completed" || - markers[0].conclusion !== "skipped") return false; - } else if (definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; - const { data: latest } = await withTransientGitHubRetry( - "current runtime attempt lookup", - () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) - ); - return latest.id === source.id && latest.run_attempt === source.run_attempt && - latest.status === "completed" && latest.conclusion === "success"; - } - - // Canonical-transition diagnostic acceptance never becomes passing producer proof. - async function verifyKnownPlayFailure(run, candidate, identity) { - if (repositoryName !== "benhook1013/FireMUD" || - !["pull_request", "repository_dispatch"].includes(run.event)) return false; - if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; - const { data: source } = await withTransientGitHubRetry( - "exact runtime workflow attempt lookup", - () => github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}", { - owner, repo, run_id: run.id, attempt_number: run.run_attempt, - }) - ); - const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + - `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; - if ( - source.id !== run.id || source.run_attempt !== run.run_attempt || - source.status !== "completed" || !["success", "failure"].includes(source.conclusion) || - source.path !== workflowPath || source.repository?.full_name !== repositoryName || - !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || - source.event !== run.event - ) return false; - const expectedHeadRepository = context.payload.pull_request.head.repo?.full_name; - if (typeof expectedHeadRepository !== "string" || - expectedHeadRepository !== repositoryName || - source.head_repository?.full_name !== expectedHeadRepository) return false; - if (source.event === "pull_request" && source.head_sha !== identity.headSha) return false; - if (source.event === "repository_dispatch" && ( - source.head_branch !== context.payload.repository.default_branch || - !/^[0-9a-f]{40}$/.test(source.head_sha ?? "") - )) return false; - const { data: workflow } = await withTransientGitHubRetry( - "runtime workflow identity lookup", - () => github.rest.actions.getWorkflow({ owner, repo, workflow_id: source.workflow_id }) - ); - if (workflow.id !== source.workflow_id || workflow.path !== workflowPath || - workflow.name !== "Build Runtime Images") return false; - const jobs = await withTransientGitHubRetry( - "exact runtime attempt jobs lookup", - () => github.paginate( - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - { owner, repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100 } - ) - ); - const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); - if (producers.length !== 1) return false; - const job = producers[0]; - if ( - !positiveInteger(job.id) || job.id !== candidate.id || - job.run_id !== source.id || job.run_attempt !== source.run_attempt || - job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== source.conclusion || - job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` - ) return false; - const expectedSuccessfulSteps = [ - "Run credential-free full-stack smoke", - "Require successful runtime smoke and authenticated cleanup", - ]; - const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; - const steps = job.steps ?? []; - const exactlyOne = (name, conclusion) => steps.filter((step) => - step.name === name && step.status === "completed" && step.conclusion === conclusion - ).length === 1; - if (!exactlyOne(markerName, "success") || !exactlyOne("Stop smoke stack", "success") || - !exactlyOne("Export fixed-tag preview image artifact", "skipped") || - !exactlyOne("Upload preview image artifact", "skipped") || - expectedSuccessfulSteps.some((name) => !exactlyOne(name, source.conclusion)) || - steps.some((step) => step.status !== "completed" || - !["success", "skipped", "failure"].includes(step.conclusion) || - (step.conclusion === "failure" && !(source.conclusion === "failure" && expectedSuccessfulSteps.includes(step.name)))) || - jobs.some((other) => other.id !== job.id && - (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; - // Typed refresh workflow authority is its native default-branch revision; - // the executed classifier source still belongs to the verified PR merge. - const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; - for (const path of [workflowPath, ...Object.keys(canonicalPlayClassifierSha256)]) { - const { data: definition } = await withTransientGitHubRetry( - `immutable PLAY classifier definition lookup: ${path}`, - () => github.rest.repos.getContent({ - owner, repo, path, ref: path === workflowPath ? workflowSha : identity.mergeSha, - }) - ); - if (definition.type !== "file" || definition.path !== path || - definition.encoding !== "base64" || typeof definition.content !== "string") return false; - const bytes = Buffer.from(definition.content, "base64"); - if (definition.size !== bytes.length) return false; - const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); - const expectedSha256 = path === workflowPath - ? canonicalLegacyRuntimeWorkflowSha256 : canonicalPlayClassifierSha256[path]; - const matches = path === workflowPath && source.conclusion === "success" - ? isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event) - : definitionHash === expectedSha256; - if (!matches) return false; - } - const { data: latest } = await withTransientGitHubRetry( - "current runtime attempt lookup", - () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) - ); - if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || - latest.status !== "completed" || latest.conclusion !== source.conclusion) return false; - // The fingerprinted marker attests the PR event label or the typed - // refresh's verified live PR label. Removal closes either exception. - const { data: currentPullRequest } = await withTransientGitHubRetry( - "current canonical transition label lookup", - () => github.rest.pulls.get({ owner, repo, pull_number: Number(prNumber) }) - ); - if (!(currentPullRequest.state === "open" && - currentPullRequest.head?.repo?.full_name === repositoryName && - currentPullRequest.base?.repo?.full_name === repositoryName && - currentPullRequest.head?.sha === identity.headSha && - currentPullRequest.base?.ref === identity.baseRef && - Array.isArray(currentPullRequest.labels) && - currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"))) return false; - if (source.event === "repository_dispatch") { - if (currentPullRequest.merge_commit_sha !== identity.mergeSha) return false; - const { data: currentBase } = await withTransientGitHubRetry( - "current canonical transition base ref lookup", - () => github.rest.git.getRef({ owner, repo, ref: `heads/${identity.baseRef}` }) - ); - if (currentBase.ref !== `refs/heads/${identity.baseRef}` || - currentBase.object?.sha !== identity.baseSha) return false; - } - return true; - } - - // Commit objects are immutable; mutable PR/base reads stay fresh. - const immutableCommits = new Map(); - async function immutableCommit(ref, label) { - if (!immutableCommits.has(ref)) { - const { data } = await withTransientGitHubRetry(label, () => - github.rest.repos.getCommit({ owner, repo, ref }) - ); - if (data.sha !== ref) throw new Error("GitHub returned a different commit OID"); - immutableCommits.set(ref, data); - } - return immutableCommits.get(ref); - } - - function isObsoletePullRequest(pullRequest) { - return ( - pullRequest.state !== "open" || - pullRequest.head.sha !== headSha || - pullRequest.base.ref !== baseRef - ); - } - - function logObsoletePullRequest(label, pullRequest) { - core.info( - `${label} ${baseRef}@${eventBaseSha}...${headSha}; current PR state/base/head is ${pullRequest.state}/${pullRequest.base.ref}/${pullRequest.head.sha}` - ); - } - - function identityKey(identity) { - return `${identity.sourceEvent}:${identity.baseRef}@${identity.baseSha}...${identity.headSha}#${identity.mergeSha}`; - } - - async function findMatchingRuntimeImagesRun(sourceEvent, expectedDisplayTitle, identity) { - const workflowRunQuery = { - owner, - repo, - workflow_id: "runtime-images.yml", - event: sourceEvent, - per_page: 100, - }; - if (sourceEvent === "pull_request") { - workflowRunQuery.head_sha = identity.headSha; - } else { - const pullRequestCreatedAt = context.payload.pull_request.created_at; - if ( - typeof pullRequestCreatedAt !== "string" || - Number.isNaN(Date.parse(pullRequestCreatedAt)) - ) { - throw new Error("current pull request creation timestamp is unavailable"); - } - workflowRunQuery.created = `${pullRequestCreatedAt}..*`; - } - const matchingRuns = []; - await withTransientGitHubRetry( - "runtime-images workflow lookup", - async () => { - matchingRuns.length = 0; - for await (const response of github.paginate.iterator( - github.rest.actions.listWorkflowRuns, - workflowRunQuery - )) { - const runs = response.data ?? []; - for (const run of runs) { - if ( - run.event !== sourceEvent || - (sourceEvent === "pull_request" && run.head_sha !== identity.headSha) || - run.display_title !== expectedDisplayTitle - ) { - continue; - } - if (sourceEvent === "pull_request") { - const pullRequests = run.pull_requests ?? []; - if ( - pullRequests.length > 0 && - !pullRequests.some((pullRequest) => - String(pullRequest.number) === prNumber && - pullRequest.head?.sha === identity.headSha - ) - ) { - continue; - } - } - const createdAt = Date.parse(run.created_at ?? ""); - if (!Number.isFinite(createdAt) || !positiveInteger(run.id)) { - throw new Error("matching runtime-images run has invalid native chronology"); - } - matchingRuns.push({ run, createdAt }); - } - } - } - ); - matchingRuns.sort((left, right) => right.createdAt - left.createdAt || right.run.id - left.run.id); - let newestPreExecutionCancellation = null; - for (const candidate of matchingRuns) { - const run = candidate.run; - if (run.status === "completed" && run.conclusion === "cancelled" && - await isPreExecutionCancelledAttempt(run, expectedDisplayTitle, identity)) { - newestPreExecutionCancellation ??= run; - continue; - } - return run; - } - return newestPreExecutionCancellation; - } - - async function resolveCurrentIdentity(label) { - let currentPullRequest; - try { - ({ data: currentPullRequest } = await withTransientGitHubRetry( - "current pull request lookup", - () => github.rest.pulls.get({ - owner, - repo, - pull_number: Number(prNumber), - }) - )); - } catch (error) { - if (error instanceof TerminalGitHubRequestError) throw error; - identityDiagnostic = `${label} could not resolve the current pull request: ${error.message}`; - core.warning(identityDiagnostic); - return null; - } - if (isObsoletePullRequest(currentPullRequest)) { - logObsoletePullRequest(label, currentPullRequest); - return { obsolete: true }; - } - - try { - // Edited events can omit a usable test-merge SHA. Only immutable - // ordered parents authorize event proof; otherwise require the - // independently verified current tuple's trusted refresh. - const validEventTuple = /^[0-9a-f]{40}$/.test(eventBaseSha ?? "") && - /^[0-9a-f]{40}$/.test(eventMergeSha ?? ""); - const mergeCommit = validEventTuple - ? await immutableCommit(eventMergeSha, "event test-merge lookup") - : null; - const parents = mergeCommit?.parents ?? []; - if ( - mergeCommit?.sha === eventMergeSha && - parents.length === 2 && - parents[0]?.sha === eventBaseSha && - parents[1]?.sha === headSha - ) { - identityDiagnostic = `resolved tested event identity ${baseRef}@${eventBaseSha}...${headSha}#${eventMergeSha}`; - return { - baseRef, - baseSha: eventBaseSha, - headSha, - mergeSha: eventMergeSha, - sourceEvent: "pull_request", - }; - } - - core.info( - `Event test merge parents are not [${eventBaseSha}, ${headSha}]; checking for an exact trusted current-base smoke refresh.` - ); - const { data: currentBaseRefData } = await withTransientGitHubRetry( - "current base ref lookup", - () => github.rest.git.getRef({ - owner, - repo, - ref: `heads/${baseRef}`, - }) - ); - const currentBaseSha = currentBaseRefData.object?.sha; - const currentMergeSha = currentPullRequest.merge_commit_sha; - if ( - !/^[0-9a-f]{40}$/.test(currentBaseSha ?? "") || - !/^[0-9a-f]{40}$/.test(currentMergeSha ?? "") - ) { - throw new Error("GitHub returned an invalid current base or test-merge SHA"); - } - const currentMergeCommit = await immutableCommit(currentMergeSha, "current test-merge lookup"); - const currentParents = currentMergeCommit.parents ?? []; - if ( - currentMergeCommit.sha !== currentMergeSha || - currentParents.length !== 2 || - currentParents[0]?.sha !== currentBaseSha || - currentParents[1]?.sha !== headSha - ) { - throw new Error( - `current test merge parents are not [${currentBaseSha}, ${headSha}]` - ); - } - - identityDiagnostic = `resolved trusted current-base identity ${baseRef}@${currentBaseSha}...${headSha}#${currentMergeSha}`; - return { - baseRef, - baseSha: currentBaseSha, - headSha, - mergeSha: currentMergeSha, - sourceEvent: "repository_dispatch", - }; - } catch (error) { - if (error instanceof TerminalGitHubRequestError) throw error; - identityDiagnostic = `${label} could not verify the event or trusted current-base test merge: ${error.message}`; - core.warning(identityDiagnostic); - return null; - } - } - - async function isCurrentPullRequestObsolete(label) { - const { data: currentPullRequest } = await withTransientGitHubRetry( - "current pull request lookup", - () => github.rest.pulls.get({ - owner, - repo, - pull_number: Number(prNumber), - }) - ); - if (!isObsoletePullRequest(currentPullRequest)) { - return false; - } - logObsoletePullRequest(label, currentPullRequest); - return true; - } - - let currentIdentity = null; - let cancelledRunId = null; - let cancelledRunObservedAt = null; - smokeGatePolling: while (Date.now() - started < timeoutMs) { - if (pollIteration % pullRequestCheckInterval === 0 || !currentIdentity) { - const resolvedIdentity = await resolveCurrentIdentity( - "Stopping obsolete smoke gate for" - ); - if (resolvedIdentity?.obsolete) { - return; - } - currentIdentity = resolvedIdentity; - } - if (!currentIdentity) { - core.info(`Waiting for a current PR identity before selecting runtime smoke: ${identityDiagnostic}`); - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue; - } - pollIteration += 1; - - const expectedDisplayTitle = - `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + - `base-${currentIdentity.baseSha} head-${currentIdentity.headSha} ` + - `merge-${currentIdentity.mergeSha} mode-required`; - let matching = await findMatchingRuntimeImagesRun( - currentIdentity.sourceEvent, - expectedDisplayTitle, - currentIdentity - ); - if ( - currentIdentity.sourceEvent === "pull_request" && - cancelledRunId !== null && - (matching?.id !== cancelledRunId || - matching.status !== "completed" || - matching.conclusion !== "cancelled") - ) { - cancelledRunId = null; - cancelledRunObservedAt = null; - } - if ( - currentIdentity.sourceEvent === "pull_request" && - matching?.status === "completed" && - matching.conclusion === "cancelled" - ) { - if (cancelledRunId !== matching.id) { - cancelledRunId = matching.id; - cancelledRunObservedAt = Date.now(); - } - const replacement = await findMatchingRuntimeImagesRun( - "repository_dispatch", - expectedDisplayTitle, - currentIdentity - ); - if (!replacement) { - if (Date.now() - cancelledRunObservedAt >= cancelledReplacementTimeoutMs) { - if (await isCurrentPullRequestObsolete("Stopping obsolete cancelled-run smoke gate for")) { - return; - } - core.setFailed( - `Cancelled runtime-images run ${cancelledRunId} has no exact repository_dispatch replacement ` + - `after ${cancelledReplacementTimeoutMs / 60000} minutes` - ); - return; - } - core.info( - `Exact pull_request runtime-images run ${matching.id} was cancelled; waiting for an exact repository_dispatch replacement.` - ); - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue; - } - core.info( - `Exact pull_request runtime-images run ${matching.id} was cancelled; checking exact repository_dispatch replacement ${replacement.id}.` - ); - matching = replacement; - } - if (matching) { - core.info(`Found runtime-images run ${matching.id} with status=${matching.status} conclusion=${matching.conclusion}`); - if (matching.status !== "completed") { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue; - } - if (matching.conclusion !== "success") { - if (await isCurrentPullRequestObsolete("Stopping obsolete failed smoke gate for")) { - return; - } - if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && - ["pull_request", "repository_dispatch"].includes(matching.event)) { - let knownPlayVerified = false; - try { - const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => - github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { - owner, repo, run_id: matching.id, attempt_number: matching.run_attempt, per_page: 100, - }) - ); - const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); - knownPlayVerified = Boolean(candidate) && - await verifyKnownPlayFailure(matching, candidate, currentIdentity); - } catch (error) { - if (error instanceof TerminalGitHubRequestError) throw error; - core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); - } - if (knownPlayVerified) { - const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); - if (freshIdentity?.obsolete) return; - if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { - currentIdentity = freshIdentity; - continue smokeGatePolling; - } - core.setOutput("known_play_exception", "true"); - core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); - await core.summary.addHeading("Canonical PLAY transition exception accepted") - .addRaw("Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.") - .write(); - return; - } - } - core.setFailed( - `Runtime images run ${matching.id} did not complete successfully: run=${matching.conclusion}` - ); - return; - } - - const latestIdentity = await resolveCurrentIdentity( - "Stopping stale completed smoke gate for" - ); - if (latestIdentity?.obsolete) { - return; - } - if (!latestIdentity || identityKey(latestIdentity) !== identityKey(currentIdentity)) { - currentIdentity = latestIdentity; - core.info( - `Runtime images run ${matching.id} was not accepted because the current PR identity changed or is unavailable; waiting for a fresh exact run.` - ); - continue; - } - - let fullSmokeJob = null; - let fullSmokeStep = null; - let canonicalProducerVerified = false; - async function failNonTerminalSnapshot(reason) { - if (await isCurrentPullRequestObsolete("Stopping obsolete stale-snapshot smoke gate for")) { - return; - } - core.setFailed( - `Runtime images run ${matching.id} did not expose a terminal PR Full-Stack Smoke job and smoke step ` + - `${reason}: ` + - `job=${fullSmokeJob?.status ?? "missing"}/${fullSmokeJob?.conclusion ?? "unknown"}, ` + - `step=${fullSmokeStep?.status ?? "missing"}/${fullSmokeStep?.conclusion ?? "unknown"}` - ); - } - const maxCompletedJobSnapshotRetries = 8; - for ( - let completedJobSnapshotAttempt = 0; - completedJobSnapshotAttempt <= maxCompletedJobSnapshotRetries; - completedJobSnapshotAttempt += 1 - ) { - const remainingBeforeJobLookupMs = timeoutMs - (Date.now() - started); - if (remainingBeforeJobLookupMs <= 0) { - await failNonTerminalSnapshot("before the workflow deadline"); - return; - } - const jobs = await withTransientGitHubRetry( - "runtime-images job lookup", - () => github.paginate( - github.rest.actions.listJobsForWorkflowRun, - { - owner, - repo, - run_id: matching.id, - per_page: 100, - } - ) - ); - if (await isCurrentPullRequestObsolete("Stopping obsolete completed smoke gate for")) { - return; - } - const producerJobs = jobs.filter((job) => - job.name === "PR Full-Stack Smoke" || job.name === canonicalSmokeJobName - ); - if (producerJobs.length > 1) { - await failNonTerminalSnapshot("with ambiguous producer jobs"); - return; - } - fullSmokeJob = producerJobs[0] ?? null; - fullSmokeStep = fullSmokeJob?.steps?.find( - (step) => step.name === "Run credential-free full-stack smoke" - ) ?? null; - if (fullSmokeJob?.status === "completed") { - // Known terminal smoke failure/skipping cannot be replaced by job success. - if (fullSmokeStep?.status === "completed") { - break; - } - if (fullSmokeJob.name === canonicalSmokeJobName && - fullSmokeJob.conclusion === "success") { - try { - canonicalProducerVerified = await verifyCanonicalSmokeProducer( - matching, fullSmokeJob, currentIdentity - ); - } catch (error) { - if (error instanceof TerminalGitHubRequestError) throw error; - core.warning(`Canonical smoke producer proof is unavailable: ${error.message}`); - } - if (canonicalProducerVerified) break; - } - } - if (completedJobSnapshotAttempt < maxCompletedJobSnapshotRetries) { - const remainingBeforeSnapshotSleepMs = timeoutMs - (Date.now() - started); - if (remainingBeforeSnapshotSleepMs <= 0) { - await failNonTerminalSnapshot("before the workflow deadline"); - return; - } - core.info( - `Runtime images run ${matching.id} succeeded but its PR Full-Stack Smoke job/step snapshot is not terminal yet: ` + - `job=${fullSmokeJob?.status ?? "missing"}/${fullSmokeJob?.conclusion ?? "unknown"}, ` + - `step=${fullSmokeStep?.status ?? "missing"}/${fullSmokeStep?.conclusion ?? "unknown"}; ` + - `retrying ${completedJobSnapshotAttempt + 1}/${maxCompletedJobSnapshotRetries}` - ); - await new Promise((resolve) => setTimeout( - resolve, - Math.min(snapshotSleepMs, remainingBeforeSnapshotSleepMs) - )); - continue; - } - const snapshotRetrySummary = maxCompletedJobSnapshotRetries === 0 - ? "before the remaining workflow deadline allowed a retry" - : `after ${maxCompletedJobSnapshotRetries} retries`; - await failNonTerminalSnapshot(snapshotRetrySummary); - return; - } - - // A continued probe has API conclusion=success even when its native - // outcome failed. The immutable marker distinguishes that exception. - if (fullSmokeJob?.name === canonicalSmokeJobName) { - const markers = (fullSmokeJob.steps ?? []).filter((step) => - step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" - ); - if (markers.length === 1 && markers[0].status === "completed" && - markers[0].conclusion === "success") { - let knownPlayVerified = false; - try { - knownPlayVerified = await verifyKnownPlayFailure(matching, fullSmokeJob, currentIdentity); - } catch (error) { - if (error instanceof TerminalGitHubRequestError) throw error; - core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); - } - if (!knownPlayVerified) { - core.setFailed("Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."); - return; - } - const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); - if (freshIdentity?.obsolete) return; - if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { - currentIdentity = freshIdentity; - continue smokeGatePolling; - } - core.setOutput("known_play_exception", "true"); - core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); - await core.summary.addHeading("Canonical PLAY transition exception accepted") - .addRaw("Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Held-admission qualification and authenticated cleanup passed. CI passed under exception; no runtime qualification, image export, or publication.") - .write(); - return; - } - if (!canonicalProducerVerified && (markers.length !== 1 || - markers[0].status !== "completed" || markers[0].conclusion !== "skipped")) { - core.setFailed("Runtime smoke proof is missing its unambiguous transition-exception disposition."); - return; - } - } - - if (fullSmokeJob?.conclusion !== "success") { - if (await isCurrentPullRequestObsolete("Stopping obsolete failed full-smoke gate for")) { - return; - } - core.setFailed( - `Runtime images run ${matching.id} succeeded, but PR Full-Stack Smoke job did not complete successfully: ` + - `job=${fullSmokeJob?.status ?? "missing"}/${fullSmokeJob?.conclusion ?? "unknown"}` - ); - return; - } - if (!canonicalProducerVerified && fullSmokeStep?.conclusion !== "success") { - if (await isCurrentPullRequestObsolete("Stopping obsolete skipped full-smoke gate for")) { - return; - } - core.setFailed( - `Runtime images run ${matching.id} succeeded, but its credential-free full-stack smoke step did not pass: ` + - `step=${fullSmokeStep?.status ?? "missing"}/${fullSmokeStep?.conclusion ?? "unknown"}` - ); - return; - } - const finalIdentity = await resolveCurrentIdentity( - "Stopping stale smoke gate before accepting full-stack proof" - ); - if (finalIdentity?.obsolete) { - return; - } - if (!finalIdentity || identityKey(finalIdentity) !== identityKey(currentIdentity)) { - currentIdentity = finalIdentity; - core.info( - `Runtime images run ${matching.id} was not accepted because the current PR identity changed after its smoke snapshot; waiting for a fresh exact run.` - ); - continue smokeGatePolling; - } - return; - } - - core.info( - `No exact ${currentIdentity.sourceEvent} runtime-images/full-smoke run found yet for PR #${prNumber} ` + - `base ${currentIdentity.baseSha} head ${currentIdentity.headSha} merge ${currentIdentity.mergeSha}; waiting...` - ); - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - } - - try { - if (await isCurrentPullRequestObsolete("Stopping obsolete timed-out smoke gate for")) { - return; - } - } catch (error) { - core.warning(`Timed-out smoke gate could not re-check current PR identity: ${error.message}`); - } - const timeoutIdentity = currentIdentity - ? `base ${currentIdentity.baseSha} head ${currentIdentity.headSha} merge ${currentIdentity.mergeSha}` - : `event base ${eventBaseSha} head ${headSha} merge ${eventMergeSha}`; - core.setFailed( - `Timed out waiting for the exact runtime-images/full-smoke run for PR #${prNumber} ${timeoutIdentity}. ` + - `Diagnostic: ${identityDiagnostic}` - ); diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml deleted file mode 100644 index c880f1974c..0000000000 --- a/.github/workflows/static-analysis-summary.yml +++ /dev/null @@ -1,318 +0,0 @@ -name: Static Analysis Summary - -on: - workflow_run: - workflows: - - License Gate - - CodeQL Analysis - types: - - completed - -permissions: - contents: read - actions: read - pull-requests: write - -concurrency: - group: static-analysis-summary-${{ github.event.workflow_run.head_branch || github.ref }}-${{ github.event.workflow_run.head_sha }} - # Serialize the CodeQL and license completion events so a pending summary - # cannot race a terminal summary into creating two comments. A superseded head - # cannot replace the pending callback for the current head. - cancel-in-progress: false - -jobs: - publish-summary: - name: Static Analysis Summary - if: ${{ github.event.workflow_run.event == 'pull_request' }} - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - name: Harden runner - uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 - with: - egress-policy: audit - - - name: ๐Ÿ’ฌ Publish Static Analysis Summary Comment - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - with: - script: | - const pullRequests = context.payload.workflow_run.pull_requests || []; - if (pullRequests.length === 0) { - core.info("No pull request is attached to this workflow run."); - return; - } - - const pullRequest = pullRequests[0]; - const issueNumber = pullRequest.number; - const headSha = context.payload.workflow_run.head_sha; - const { data: currentPullRequest } = await github.rest.pulls.get({ - ...context.repo, - pull_number: issueNumber, - }); - if (currentPullRequest.head?.sha !== headSha) { - core.info("The source run belongs to a superseded pull-request head."); - return; - } - const baseSha = currentPullRequest.base?.sha; - if (!baseSha) { - throw new Error("The current pull-request base SHA is unavailable."); - } - const sourceWorkflowPath = context.payload.workflow_run.path; - const sourceWorkflowName = ({ - ".github/workflows/codeql.yml": "CodeQL Analysis", - ".github/workflows/license-scan.yml": "License Gate", - })[sourceWorkflowPath]; - // The completion is a wake signal, never proof for the current base. - // An older-base callback can replace a pending callback in this head's - // concurrency group, so validate its original title and snapshot the live tuple. - const sourceBaseSha = String(context.payload.workflow_run.display_title || "") - .match(/ base-([0-9a-f]{40}) head-/)?.[1]; - const expectedSourceTitle = `${sourceWorkflowName} pr-${issueNumber} base-${sourceBaseSha} head-${headSha}`; - if ( - currentPullRequest.state !== "open" || - !sourceWorkflowName || - !sourceBaseSha || - (context.payload.workflow_run.name !== sourceWorkflowName && - context.payload.workflow_run.name !== expectedSourceTitle) || - context.payload.workflow_run.display_title !== expectedSourceTitle - ) { - core.info("The source run is not bound to the current open pull request and head."); - return; - } - const detailChecks = [ - ["CodeQL analysis (java)", "CodeQL Analysis (java)", "codeql"], - ["CodeQL analysis (javascript-typescript)", "CodeQL Analysis (javascript-typescript)", "codeql"], - ]; - const gateChecks = [ - ["CodeQL gate", "CodeQL Gate", "codeql"], - ["License gate", "License Gate", "license"], - ]; - const statusIcon = (value) => { - if (value === "success") return "โœ…"; - if (value === "failure") return "โŒ"; - if (value === "cancelled") return "โšช"; - if (value === "pending" || value === "in_progress" || value === "queued") return "โณ"; - return "โญ๏ธ"; - }; - - const parseTimestamp = (value) => { - const parsed = Date.parse(value || ""); - return Number.isNaN(parsed) ? -1 : parsed; - }; - - const numericIdentity = (value) => { - const parsed = Number(value); - return Number.isFinite(parsed) ? parsed : -1; - }; - - const compareWorkflowRuns = (left, right) => { - const createdAtDiff = parseTimestamp(left?.created_at) - parseTimestamp(right?.created_at); - if (createdAtDiff !== 0) return createdAtDiff; - const attemptDiff = numericIdentity(left?.run_attempt) - numericIdentity(right?.run_attempt); - if (attemptDiff !== 0) return attemptDiff; - return numericIdentity(left?.id) - numericIdentity(right?.id); - }; - - const selectLatestWorkflowRun = (workflowRuns) => { - const candidates = (Array.isArray(workflowRuns) ? workflowRuns : []).filter( - (workflowRun) => - workflowRun?.event === "pull_request" && - workflowRun?.head_sha === headSha - ); - return candidates.reduce( - (latest, candidate) => - !latest || compareWorkflowRuns(candidate, latest) > 0 ? candidate : latest, - null - ); - }; - - const workflowRunFor = async (workflowId) => { - const workflowName = workflowId === "codeql.yml" ? "CodeQL Analysis" : "License Gate"; - const expectedTitle = `${workflowName} pr-${issueNumber} base-${baseSha} head-${headSha}`; - const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, { - ...context.repo, - workflow_id: workflowId, - event: "pull_request", - head_sha: headSha, - per_page: 100, - }); - return selectLatestWorkflowRun( - workflowRuns.filter((workflowRun) => workflowRun?.display_title === expectedTitle) - ); - }; - - const checkRunWorkflowId = (checkRun) => { - const match = String(checkRun?.details_url || "").match(/\/actions\/runs\/(\d+)(?:\/|$)/); - return match?.[1] || null; - }; - - const compareCheckRuns = (left, right) => { - const leftTimestamp = Math.max( - parseTimestamp(left?.completed_at), - parseTimestamp(left?.started_at), - parseTimestamp(left?.created_at) - ); - const rightTimestamp = Math.max( - parseTimestamp(right?.completed_at), - parseTimestamp(right?.started_at), - parseTimestamp(right?.created_at) - ); - if (leftTimestamp !== rightTimestamp) return leftTimestamp - rightTimestamp; - return numericIdentity(left?.id) - numericIdentity(right?.id); - }; - - const selectLatestCheckRun = (checkRuns, checkName, workflowRun) => { - if (!workflowRun?.id) return null; - const workflowRunId = String(workflowRun.id); - const candidates = (Array.isArray(checkRuns) ? checkRuns : []).filter( - (checkRun) => - checkRun?.name === checkName && - checkRunWorkflowId(checkRun) === workflowRunId - ); - return candidates.reduce( - (latest, candidate) => - !latest || compareCheckRuns(candidate, latest) > 0 ? candidate : latest, - null - ); - }; - - const normalizeStatus = (checkRun, checkName, workflowRun) => { - if (!checkRun) { - if ( - checkName.startsWith("CodeQL Analysis (") && - workflowRun?.status === "completed" - ) { - return "skipped"; - } - if (workflowRun?.status === "completed") { - return workflowRun.conclusion ?? "pending"; - } - if (workflowRun?.status) return workflowRun.status; - return "pending"; - } - if (checkRun.status !== "completed") return checkRun.status; - return checkRun.conclusion ?? "pending"; - }; - - const loadChecks = async () => { - return github.paginate(github.rest.checks.listForRef, { - ...context.repo, - ref: headSha, - per_page: 100, - }); - }; - - const resolveStatuses = (checkRuns, workflowRuns) => - [...gateChecks, ...detailChecks].map(([label, checkName, workflowKey]) => { - const isCodeQlAnalysis = checkName.startsWith("CodeQL Analysis ("); - const emptyMatrixCodeQlCheck = - "CodeQL Analysis ($" + "{{ matrix.language }})"; - const workflowRun = workflowRuns?.[workflowKey] || null; - const selectedCheckRun = selectLatestCheckRun( - checkRuns, - checkName, - workflowRun - ) || (isCodeQlAnalysis - ? selectLatestCheckRun(checkRuns, emptyMatrixCodeQlCheck, workflowRun) - : null); - return [label, normalizeStatus(selectedCheckRun, checkName, workflowRun)]; - }); - - const workflowRuns = { - codeql: await workflowRunFor("codeql.yml"), - license: await workflowRunFor("license-scan.yml"), - }; - // Each serialized producer completion publishes one bounded snapshot. - // A running counterpart stays pending until its completion callback refreshes this comment. - const checks = resolveStatuses(await loadChecks(), workflowRuns); - - const gateResults = checks.slice(0, gateChecks.length); - const detailResults = checks.slice(gateChecks.length); - - const failedChecks = gateResults.filter(([, result]) => - ["failure", "cancelled", "timed_out", "action_required"].includes(result) - ); - const pendingChecks = gateResults.filter(([, result]) => - ["pending", "in_progress", "queued"].includes(result) - ); - - let headline = "โœ… Static analysis checks passed"; - if (failedChecks.length > 0) { - headline = "โŒ Static analysis checks failed"; - } else if (pendingChecks.length > 0) { - headline = "โณ Static analysis checks are still running"; - } - - const body = [ - "### Static Analysis Summary", - headline, - "", - ...gateResults.map(([name, result]) => `- ${statusIcon(result)} ${name}: \`${result}\``), - "", - "CodeQL breakdown", - "", - ...detailResults.map(([name, result]) => `- ${statusIcon(result)} ${name}: \`${result}\``), - ].join("\n"); - - const { data: finalPullRequest } = await github.rest.pulls.get({ - ...context.repo, - pull_number: issueNumber, - }); - if ( - finalPullRequest.state !== "open" || - finalPullRequest.head?.sha !== headSha || - finalPullRequest.base?.sha !== baseSha - ) { - core.info("The pull-request base or head changed while static analysis was being summarized."); - return; - } - - const comments = await github.paginate(github.rest.issues.listComments, { - ...context.repo, - issue_number: issueNumber, - per_page: 100, - }); - - const summaryComments = comments.filter((comment) => - comment.user?.login === "github-actions[bot]" && - comment.body?.startsWith("### Static Analysis Summary") - ); - const commentTimestamp = (comment) => { - const parsed = Date.parse(comment.created_at || ""); - return Number.isNaN(parsed) ? Number.MAX_SAFE_INTEGER : parsed; - }; - const existing = summaryComments.reduce((oldest, comment) => { - if (!oldest) return comment; - const oldestTimestamp = commentTimestamp(oldest); - const candidateTimestamp = commentTimestamp(comment); - if (candidateTimestamp !== oldestTimestamp) { - return candidateTimestamp < oldestTimestamp ? comment : oldest; - } - return Number(comment.id) < Number(oldest.id) ? comment : oldest; - }, null); - - if (existing && existing.body !== body) { - await github.rest.issues.updateComment({ - ...context.repo, - comment_id: existing.id, - body, - }); - } else if (!existing) { - await github.rest.issues.createComment({ - ...context.repo, - issue_number: issueNumber, - body, - }); - } - - for (const comment of summaryComments) { - if (comment.id === existing?.id) continue; - try { - await github.rest.issues.deleteComment({ - ...context.repo, - comment_id: comment.id, - }); - } catch (error) { - if (error?.status !== 404) throw error; - } - } diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 84e7ac59f2..b0b172190c 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -31,9 +31,9 @@ The environment matrix below is the canonical target state. Current repository i - `./dev-tools/deploy/preflight.py` is the intended entrypoint, but it does not yet enforce every player-facing policy listed in `system-architecture-deploy-preflight-policy.md`; missing enforcement remains a blocker for first player-facing deployment and traffic-open events. - The player-facing expected-binding manifests under `design/operations/environments/` currently describe the intended shape but are not yet complete authoritative inputs for preflight or restore validation. -- Hosted `pr-preview` and `dev-demo-cluster` currently reuse the preview Helm values path. The target requires one environment-unique shared-HMAC signing key and non-secret diagnostic `jwt-jwks` content per deployment event, reused unchanged through render, dry-run, Helm apply, and retries. Current renderers regenerate material per invocation, so retry reuse is not proved. `preflight.py hosted-bridge` provides separate `ci-static` rendered-contract validation and `operator` validation of controller-projected TLS Secret keys; the trusted preview workflow now invokes `ci-static` before runtime apply and `operator` after identity readiness and rollout, while live hosted acceptance remains unproved. The operator form can therefore fail closed for missing or delayed projection without making a pre-projection Secret read circular. It does not prove live JWKS acceptance or asymmetric non-exportable signer custody. Standalone Helm materializes the namespace-scoped `jwt-signing-keys` `Secret` and diagnostic `jwt-jwks` `ConfigMap`; in hosted-controller preview, the trusted runtime lifecycle provisions both and excludes their PR-rendered copies from the sanitized artifact. Account mounts the diagnostic ConfigMap in either mode. Current validators use the Secret/path contract; the ConfigMap content is not the validation key. This preview diagnostic wiring is not the player-facing target: the sole target is Account-published public JWKS with non-exportable signer custody and validator consumption proven separately. The separate `helm-jwks-contract.sh` proof covers only configured preview resource/path/mount wiring, not live JWKS acceptance or target asymmetric, non-exportable signer custody. +- Hosted `pr-preview` and `dev-demo-cluster` currently reuse the preview Helm values path. Preview JWT material follows the trusted provisioning described under [PR preview environment](#pr-preview-environment). `preflight.py hosted-bridge` provides separate `ci-static` rendered-contract validation and `operator` validation of controller-projected TLS Secret keys; the dev-demo workflow invokes `ci-static` before runtime apply and `operator` after identity readiness and rollout. The trusted PR preview workflow does not run either phase: it validates the sanitized artifact, runs a Kubernetes server dry-run before apply, then checks rollouts and its hosted proof. Live hosted acceptance remains unproved. The operator form can therefore fail closed for missing or delayed projection without making a pre-projection Secret read circular. It does not prove live JWKS acceptance or asymmetric non-exportable signer custody. A direct Helm install renders the namespace-scoped `jwt-signing-keys` `Secret` and diagnostic `jwt-jwks` `ConfigMap`; the trusted PR preview lifecycle provisions both in either certificate identity mode and excludes their PR-rendered copies from the sanitized artifact. Account mounts the diagnostic ConfigMap in either mode. Current validators use the Secret/path contract; the ConfigMap content is not the validation key. This preview diagnostic wiring is not the player-facing target: the sole target is Account-published public JWKS with non-exportable signer custody and validator consumption proven separately. The separate `helm-jwks-contract.sh` proof covers only configured preview resource/path/mount wiring, not live JWKS acceptance or target asymmetric, non-exportable signer custody. - Hosted preview and dev-demo Helm currently support direct TCP Proxy TLS on the existing NodePort with a dedicated `-telnet-tls` certificate Secret. Current validation covers hostname/SNI authentication of the certificate served by the Telnet endpoint, while certificate issuance, controller projection, rotation or migration, withdrawal, and staging/production deployment evidence remain gaps. The deployed browser path, shared semantic assertions, head-bound lease handling, isolation proof, and transport-complete acceptance under [ADR 0178](../decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md) also remain implementation gaps. -- The trusted preview workflow now has an explicit, fail-closed exposure mode. Its static/local proof is present for the #2713 private Gateway-to-TCP Proxy bridge path, but no live controller rollout or private bridge proof is claimed; public transport-complete work remains the #2795 path. Preview validation includes the hosted Helm render and Kubernetes server dry-run, with `preflight.py hosted-bridge` providing separate `ci-static` rendered-contract validation and `operator` validation of controller-projected TLS Secret keys after identity readiness and rollout. +- The trusted preview workflow now has an explicit, fail-closed exposure mode. Its static/local proof is present for the #2713 private Gateway-to-TCP Proxy bridge path, but no live controller rollout or private bridge proof is claimed; public transport-complete work remains the #2795 path. Preview validation includes the hosted Helm render, artifact validation and Kubernetes server dry-run; the `preflight.py hosted-bridge` `ci-static` and `operator` phases run in dev-demo, not in the PR preview workflow. - The player-facing Kustomize path (`k8s/overlays/*` over `k8s/base`) now carries digest-pinned workload images and relies on externally managed bootstrap secrets/TLS bindings enforced through expected-bindings plus preflight, rather than shipping placeholder bootstrap secrets inside the rendered player-facing manifests. When this document says an environment โ€œmustโ€ satisfy a gate, that is a target-state requirement. If the current tooling cannot prove the gate yet, the protected deployment transition remains blocked. Manual evidence may record that blocked state or support repair and quarantined investigation, but it cannot replace a canonical phase result, waive ADR 0152's non-waivable promotion or traffic-open checks, or authorize traffic or promotion while the required preflight implementation is incomplete. @@ -91,7 +91,7 @@ The current executable does not implement this candidate-resource lifecycle or e - Player-facing classes (`hobby-self-hosted`, `staging`, `production`) must keep a single expected-binding manifest at `design/operations/environments//expected-bindings.yaml` so deployment preflight and restore validation use the same environment-isolation contract for internal state/trust bindings (PostgreSQL, Redis, JWT/JWKS, certificate issuer, registry pull credentials) and external bindings (backup, asset, outbound-communications, operator bindings). The manifest also declares the profile-resolved log-queryability `selectedProfile`, capability, and freshness budget used by promotion validation; retained evidence cannot substitute an arbitrary profile claim. For backup and asset storage, that manifest must also capture the binding identity proving the environment owns the object-store target. - Classes documented without backup/SLO guarantees (`pr-preview`, default `staging`) must not be used as evidence for backup/SLO guarantees unless their controls are explicitly upgraded. -- `pr-preview` keeps the production-like auth/session and service-isolation model, but its hosted Helm validation is intentionally preview-scoped rather than the player-facing preflight contract. The target requires one preview-unique shared-HMAC signing key and non-secret diagnostic `jwt-jwks` content to remain stable for the deployment event through render, dry-run, Helm apply, and retries; explicit rotation or an explicitly new deployment event, including an intentional clean namespace reset, may replace it. The current renderer regenerates material per invocation, so retry reuse is not proved. Helm materializes `jwt-signing-keys` as a namespace-scoped `Secret` and the diagnostic `jwt-jwks` as a namespace-scoped `ConfigMap`, and Account mounts the latter at the configured JWKS path. Current preview validators use the Secret/path contract. This diagnostic implementation is not the player-facing target; the sole target is Account-published public JWKS with non-exportable signer custody. `helm-jwks-contract.sh` proves only the diagnostic resource and Account mount wiring, not validator consumption or target asymmetric/non-exportable custody. Preview namespaces are not required to satisfy the full player-facing backup/admission binding posture before opening reviewer traffic. +- `pr-preview` keeps the production-like auth/session and service-isolation model, but its hosted Helm validation is intentionally preview-scoped rather than the player-facing preflight contract. The trusted deploy workflow provisions the namespace-scoped `jwt-signing-keys` Secret and diagnostic `jwt-jwks` ConfigMap, as described under [PR preview environment](#pr-preview-environment), and Account mounts the ConfigMap at the configured JWKS path. Current preview validators use the Secret/path contract. This diagnostic implementation is not the player-facing target; the sole target is Account-published public JWKS with non-exportable signer custody. `helm-jwks-contract.sh` proves only the diagnostic resource and Account mount wiring, not validator consumption or target asymmetric/non-exportable custody. Preview namespaces are not required to satisfy the full player-facing backup/admission binding posture before opening reviewer traffic. - `pr-preview` and `dev-demo-cluster` target the same Spring gRPC SSL-bundle mTLS contract as the rest of the Kubernetes-backed environments; they do not define a separate long-term internal gRPC transport mode. The temporary plaintext internal-gRPC exception defined by [gRPC TLS Requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy for the bounded Spring gRPC `1.0.x` SSL-bundle migration and preview re-proof, not the current preview transport mode: current preview uses mTLS. That preview exception is non-player-facing and is neither traffic-open nor promotion evidence; `dev-demo-cluster` has no such exception. Their shared `firemud-grpc-tls` Secret otherwise proves encrypted transport only, not target per-workload identity or player-facing equivalence; distinct workload leaf identities with a shared CA and generic identity proof remain target work. - Staging and production deployments must run the canonical preflight policy gate defined in `system-architecture-deploy-preflight-policy.md`; production promotions must satisfy the attestation contract in `system-architecture-promotion-attestation.md`. - `hobby-self-hosted` deployments are also player-facing and must run equivalent checks for player-facing invariants (the selected JWT custody mode and JWKS resource contract, Redis role split, and `GATEWAY_WS_URL` alignment) before opening traffic, even when not using the staging/production Kustomize overlay workflow. The current `LEGACY_SECRET_DIAGNOSTIC` mode checks the shared-HMAC Secret and `FIREMUD_AUTH_JWT_SECRET_PATH` wiring only and is non-authorizing; the accepted `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` mode requires Account-only private-bundle proof plus public-JWKS validator convergence; target `TARGET_NON_EXPORTABLE_SIGNER` mode requires signer health and no-private-material evidence with that variable absent. In this class, operator preflight is mandatory while overlay PR CI checks are optional/recommended. @@ -348,15 +348,16 @@ Runtime reclaim, redeploy, release, and lease expiry delete only the runtime nam The hosted identity controller's egress boundary is exact-destination and operator-rendered. Its checked-in NetworkPolicy contains no `0.0.0.0/0` or `::/0`; trusted bootstrap substitutes validated `/32` IPv4 CIDRs for the observed `kubernetes.default` Service ClusterIP on TCP/443, the single API endpoint on TCP/6443, and the fixed public preview probe on TCP/443 plus NodePorts 32000-32016. Gateway access is separately limited to `spring-cloud-gateway` pods in the canonical preview and dev-demo namespaces on TCP/443 and TCP/8443. The observed k3s LoadBalancer path additionally requires the exact kube-system Traefik pod selector on TCP/8443 after public HTTPS DNAT, and the public TCP Proxy NodePort path requires the exact `tcp-proxy-service` selectors in those canonical namespaces on TCP/2323 after NodePort DNAT. DNS and the label-scoped Account, Game Session, and Social Groups TCP/6565 selectors remain explicit; the existing Social Groups served-identity probe checks the current projected leaf at its fixed gRPC endpoint. `observe` and `active` bootstrap require all three addresses, require exactly one matching fixed public DNS A record, and verify the API Service and single-endpoint readback before any write; paused mode without addresses renders loopback-only deny markers. Standard NetworkPolicy may exempt traffic to the local node, and CNI post-DNAT behavior must be proven live for the public Traefik HTTPS and NodePort paths; the private proof separately needs live allow/deny evidence for its ClusterIP bridge path. This static boundary does not complete PO-3.2: live allow/deny and served Gatewayโ†”TCP Proxy bridge proof remain required. -- Same-repo pull requests may deploy one Helm release into namespace `pr-` with matching hostname `https://pr-.preview.`. +- Same-repo pull requests may deploy into namespace `pr-` with matching hostname `https://pr-.preview.`. - The preview deployment uses the full application stack, including the gateway, TCP proxy, backend microservices, and stateful supporting services required for normal gameplay flows. -- GitHub Actions builds and smoke-tests PR merge images without registry credentials. A separate trusted default-branch workflow verifies their exact base/head/merge provenance and publishes immutable `pr-merge-` tags to private GHCR, after which the preview workflow deploys or upgrades the Helm release. After a long-lived base-branch CI push run completes, trusted orchestration refreshes the merge-image run and preview request without changing the PR head. For an eligible prioritized stacked PR, the trusted preview reconciler independently detects its parent branch advancing and dispatches the exact new merge candidate. Branch image publication still requires successful CI. A new base commit requires a newly successful PR image run. An ordinary `main`/`develop` PR without runtime-image changes may reuse the proven base-commit images; a stacked PR always publishes and selects its exact `pr-merge-` images because feature-branch head SHAs are not trusted published image identities. The cluster authenticates to GHCR using image pull credentials. -- Each preview namespace must use PR-unique JWT signing material. The target requires one shared-HMAC key and separate non-secret diagnostic `jwt-jwks` content to remain stable for the deployment event across render, dry-run, Helm apply, and retries; explicit rotation or a new deployment event may replace them. The current renderer supplies fresh material per invocation, so retry reuse is not proved. Helm stores the signing key in the namespace-scoped `jwt-signing-keys` `Secret` and the diagnostic content in the namespace-scoped `jwt-jwks` `ConfigMap`, which Account mounts for its configured JWKS path. Current preview validators use the Secret/path contract, not the diagnostic ConfigMap. This diagnostic resource/mount wiring is not the player-facing target; the sole target is Account-published public JWKS with non-exportable signer custody, and the wiring does not prove target public-JWKS validation. Preview auth tokens must not validate across PR namespaces. +- GitHub Actions builds PR merge images locally and runs held-admission smoke when required by runtime scope, without registry credentials. A separate trusted default-branch workflow verifies their exact base/head/merge provenance and publishes immutable `pr-merge-` tags to private GHCR. The preview workflow renders the chart with Helm, and the trusted consumer applies the validated manifest artifact with Kubernetes. After a long-lived base-branch CI push run completes, trusted orchestration refreshes the merge-image run and preview request without changing the PR head. For an eligible prioritized stacked PR, the trusted preview reconciler independently detects its parent branch advancing and dispatches the exact new merge candidate. Branch image publication still requires successful CI. A new base commit requires a successful PR image run for the new comparison when the preview selects PR merge images. An ordinary `main`/`develop` PR without runtime-image changes may reuse the proven base-commit images; a stacked PR always publishes and selects its exact `pr-merge-` images because feature-branch head SHAs are not trusted published image identities. The cluster authenticates to GHCR using image pull credentials. +- Each preview namespace uses PR-unique JWT signing material. The trusted preview deploy workflow provisions the namespace-scoped `jwt-signing-keys` Secret and non-secret diagnostic `jwt-jwks` ConfigMap before dry-run and apply. The provisioner reuses a valid signing key within the same namespace and refuses existing diagnostic content whose fingerprint disagrees with that key. The artifact validator checks the read-only Secret mount and Account's read-only diagnostic ConfigMap mount and source. A namespace reset deletes the Secret, so the next deploy generates a new signing key and matching diagnostic ConfigMap; the key is stable only across retries within the same namespace. Player-facing JWT custody uses Account-published public JWKS with a non-exportable signer. Preview auth tokens must not validate across PR namespaces. - The Telnet `LOGIN -> PLAY -> LOOK` proof remains useful protocol evidence. Continuing preview acceptance under [ADR 0178](../decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md) retains that public Telnet adapter and requires the same bounded semantic gameplay outcomes through the deployed first-party browser adapter. Browser proof must use the static host's frontend documents and `/frontend-assets/**`, with the public router rewriting `/auth/**` to Gateway's existing `/api/account/auth/**` route alongside Gateway's `/api/**` and `/ws/game/**` routes; Gateway-hosted temporary helpers, backend-only WebSocket clients, and SPA fallback do not satisfy it. The public router, dedicated frontend delivery, and browser journey remain unimplemented, so current hosted proof is still TCP/Telnet-only and cannot yet claim transport-complete acceptance. - Preview TCP exposure uses a small reserved preview-only external port range, with one TCP port per live preview namespace on the shared preview host/IP. This is a preview multiplexing concern, not the long-term player-facing Telnet architecture. -- Preview deploys currently reset the namespace before each Helm apply, then reseed the minimum bootstrap state needed for reviewer proof. Within one deployed preview instance, PostgreSQL, MinIO/object storage, and other stateful components persist across normal pod restarts and VM reboot, but preview state does not currently persist across preview redeploys. +- Preview deploys currently reset the namespace before applying the validated manifest, then reseed the minimum bootstrap state needed for reviewer proof. Within one deployed preview instance, PostgreSQL, MinIO/object storage, and other stateful components persist across normal pod restarts and VM reboot, but preview state does not currently persist across preview redeploys. - Preview state is not backed up and is not durable beyond the single preview node. If the node or its attached storage is lost, preview state is lost. - The initial Hetzner/k3s sizing target is one reliably usable full-stack preview on an 8 GB shared-CPU x86 VM. A second concurrent preview is best-effort only and may fail to deploy if capacity is exhausted. +- Hosted dev and preview app services share one JVM footprint profile owned by `previewStack.jvm` in the [hosted Helm chart values](../../../k8s/helm/firemud/values.yaml): C1-only JIT, a 64 MiB reserved code cache, 512 KiB thread stacks, and two glibc malloc arenas. It trades peak JIT throughput for lower resident memory and does not apply to the player-facing Kustomize overlays. The trusted preview validator also accepts the exact Gateway environment from supported merge bases that omit both footprint settings. Both forms require the same identity, routing, and trust wiring. - Open, mergeable, non-dependency-bot same-repository pull requests targeting `main` or `develop` request preview allocation automatically. A stacked pull request whose base is another current branch in the same repository is eligible only while it carries the maintainer-controlled `preview:priority` label; forks and dependency-bot updates remain ineligible. Ordinary allocation in the bounded two-slot pool is first-come at the serialized allocation boundary while capacity remains available; GitHub's raw job-scheduling order is not itself an allocation guarantee. The priority label lets a later priority request claim a free slot or reclaim the oldest ordinary preview, but never another currently priority-labelled preview. Allocation, deployment, hosted proof, reclaim, and cleanup share one durable bounded non-cancelling lifecycle queue so a running proof is not deleted underneath itself and normal waiting lifecycle work uses GitHub's expanded queue instead of its replaceable single pending slot. Both target and victim label state are re-read immediately before reclaim. Removing the label from an ordinary `main`/`develop` pull request returns its environment to ordinary status; removing it from a stacked pull request makes that preview ineligible and permits trusted cleanup. A displaced pull request keeps its ordinary CI and historical preview result, while its current hosted status reports that no environment is allocated. - Each successfully allocated eligible preview receives its own namespace and holds a bounded renewable visible lease. An ordinary active lease is protected except for the explicit priority rule above; a priority-labelled active lease is not silently evicted, while an expired lease may be reclaimed even if the pull request remains open. A request that is eligible but not allocated, including because capacity is exhausted or every slot is priority-protected, reports `preview_unavailable`, not passed. - Any review claiming hosted proof requires successful evidence for its current base SHA, head SHA, two-parent merge SHA, and selected immutable image tag. A parent advance invalidates the prior proof even when the child head is unchanged. diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index d62e9ab4d6..7ce1bb0e90 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -31,7 +31,7 @@ For the TCP Proxy -> Gateway WebSocket mTLS hop, the TCP Proxy client identity a The trusted default-branch workflow treats the hosted preview Gateway configuration as an exact contract. The rendered `firemud-config` must match the canonical `previewStack.sharedConfig` values from the trusted Helm values file; only the two source-only MinIO credential entries are removed before the artifact is applied. Unknown, missing, or changed shared configuration is rejected. In particular, Gateway bridge and route URI variables, `SPRING_APPLICATION_JSON`, and `JAVA_TOOL_OPTIONS` are not accepted through the shared ConfigMap. -The Gateway Deployment has a matching exact contract for its per-container `env` and `envFrom` fields. PR-controlled `extraEnv` or additional configuration references cannot replace the managed listener/trust settings or introduce an equivalent route or JVM override. This contract is enforced by the hosted artifact validator and must be updated together with the trusted Helm defaults when a legitimate Gateway setting is added. +The hosted artifact validator checks the Gateway Deployment's per-container `env` and `envFrom` against the managed listener, trust, and routing settings. For `previewStack.jvm.javaToolOptions` and `previewStack.jvm.mallocArenaMax`, it accepts both values from the [shared JVM profile](../../infrastructure/deployment-environments.md#pr-preview-environment) or both variables absent from the rendered Deployment. Omitting only one variable, supplying a different value, or adding a configuration reference fails validation. Update the trusted Helm defaults and the validator together when adding a legitimate setting. The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Game Session on TCP/8444 for the dedicated authenticated mTLS WebSocket receiver at `/ws/game/tcp`, Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 5d3008b0fd..b41cff1c5c 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -34,7 +34,7 @@ The manual [Game Session factory inventory qualification workflow](../../.github ## Required Gate Preservation -The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. A metadata-only pull-request edit reuses proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and all twenty-five prerequisite jobs, including the four distinct other-module, Account, Game Session, and World Build and Test matrix placeholders and the Account, Game Session, and World Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that any coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. Historical single-matrix inventories do not qualify for this exception; incomplete current inventories cannot fall back to that older shape. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. +The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. Metadata-only edits are PR `edited` events without a base ref change. These events skip substantive jobs and use concurrency groups separate from substantive runs. Base retargets rerun the full gates. Metadata-only edits reuse proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and the exact prerequisite inventory, including the four distinct other-module, Account, Game Session, and World Build and Test matrix placeholders and the Account, Game Session, and World Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that any coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. Historical single-matrix inventories do not qualify for this exception. A gate that declares the dev-tool contract split must include both contract jobs in the exact inventory. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. A supplementary Commit Status with the same required gate name may withhold an otherwise successful native Actions CheckRun. Both must succeed when both exist; the native app-pinned CheckRun remains mandatory, and a status creator, actor name, or URL cannot establish App authority. The controller independently evaluates that native proof and all exact-head same-name status barriers, including foreign barriers. A status success alone never supplies required native proof. @@ -46,7 +46,7 @@ The [publisher action](../../.github/actions/publish-required-gate-status/action Ownership recognition allows an older base in the canonical title as provenance, and accepts a bound dedicated publisher step in progress or completed successfully, unsuccessfully, or cancelled. It binds the exact run/attempt, workflow, repository, head, PR title, gate job and native Actions app without requiring old preservation success. This permits replacing an owned barrier left by overlapping or cancelled metadata runs. Positive native workflow `run_number` and `run_attempt` counters order replacement within the same exact workflow: an older run number is replaceable; equal run numbers require the same run ID and no newer attempt. Historical attempt-specific run/job evidence binds older attempts. Missing or conflicting counters and newer barriers are not overwritten; timestamps and global run IDs do not establish ordering. Skipped, missing, conflicting or unbound publisher evidence is not ownership and grants no overwrite permission. Old-base provenance never becomes current-base proof. The current publishing run must be attributable to its exact metadata-only event and current PR tuple. Both publisher and resolver read rich status records from `/repos///statuses/`; the combined `/commits//status` projection omits `creator` and cannot establish ownership. The [GitHub status-list contract](https://docs.github.com/en/rest/commits/statuses#list-commit-statuses-for-a-reference) returns newest first. Readers stop at the first exact-context record regardless of actor, using that API order even when creation timestamps share a second; they never search older records for an owned predecessor or infer chronology from numeric IDs. Explicit 100-record pages have a ten-page safety budget. Only a short page without a matching context establishes absence; budget exhaustion, unavailable/malformed required pages, duplicate IDs in the traversed prefix, or mismatched head-bound status URLs fail closed. Older records after the selected context are not admission evidence. Null, missing, or foreign creators remain untouched rather than inferred from a URL. Native job reads retain their complete one-page cap of 100 records. Immediately before a single non-retried POST, the publisher re-reads the current PR and unchanged latest context. A successful command must return exactly one valid acknowledgment with a positive status ID, exact `https://api.github.com/repos///statuses/` URL, requested state/context/target URL, bot creator and native timestamps. REST statuses have no per-status SHA or App ID. Missing, malformed, denied or ambiguous acknowledgment never yields a pending native-success allowance. Pending POST acknowledgment has native evidence; repaired recovery and read-only fork-token qualification remain outstanding in [Platform Operations and Delivery](../project-management/implementation-tracking/platform-operations-and-delivery.md#required-ci-gate-preservation). A fork token denied status-write authority leaves the publisher and native gate failed. For a non-cancelled metadata run whose canonical preservation assessment succeeded, the executed failed deferral guard retains eligibility for existing trusted legacy recovery after independent original success. Cancellation remains fail-closed. Callers never escalate fork credentials or substitute a status for original proof. -Resolver/controller support and the separate producer activation are both present in the current workflows. All five metadata gate producers publish pending statuses after canonical preservation assessment. Per-run native pending-status behavior still depends on an acknowledged publication and independently selected current original proof; workflow activation alone does not establish that proof. The resolver retains its targeted legacy rerun path when the distinct dependency-deferral guard executes and fails after successful canonical assessment, including unchanged deferred publication and denied or ambiguous publisher execution. Its existing attribution, chronology, confirmation, and one-attempt constraints remain mandatory. +All five metadata gate producers publish pending statuses after canonical preservation assessment. Per-run native pending-status behavior depends on an acknowledged publication and independently selected current original proof. The resolver retains its targeted rerun path when the distinct dependency-deferral guard executes and fails after successful canonical assessment, including unchanged deferred publication and denied or ambiguous publisher execution. Its attribution, chronology, confirmation, and one-attempt constraints remain mandatory. The shared action assesses original proof once without polling. Exact success passes; invalid, ambiguous, or failed proof fails. A pending or unpublished original produces a dependency-deferred assessment and releases the runner after acknowledged pending publication. An unacknowledged successful publisher result or failed publisher execution fails the distinct dependency-deferral guard and native job; cancellation does not execute that guard. The trusted default-branch [resolver](../../.github/workflows/resolve-required-gates.yml) reacts to both substantive and metadata completions, so either completion ordering can resolve a deferred gate. It never executes PR source or writes check conclusions. Only its job holds `actions: write`, to rerun an exact completed deferred gate after the shared selector confirms original success. @@ -58,9 +58,9 @@ Native admission evidence is bounded by GitHub retention. Known missing, ambiguo All five callers use canonical one-pass assessment and the trusted listener admits ordinary pull-request tuples through the identity and evidence checks above. There is no proof-branch condition, PR allowlist, assessment-mode input, or long polling path. Deploy the caller/action/helper/resolver/fixture change coherently on the default branch; PR source alone cannot widen the trusted listener. Do not depend on callbacks from token-initiated reruns for further recovery. -The fresh disposable [PR #3081](https://github.com/benhook1013/FireMUD/pull/3081) rehearsal exercised the deployed frozen target-window boundary. The substantive Validation completion [callback](https://github.com/benhook1013/FireMUD/actions/runs/37699680343) admitted and confirmed deferred job `113054648672`; its targeted rerun produced successful attempt-2 gate `113060155504`. The other four metadata gates passed on attempt 1. A final settled-source metadata edit produced five successful attempt-1 gates and five successful callbacks with explicitly skipped admission and confirmation. This proves the bounded recovery and settled preservation paths, not five separate deferred admissions or the unproved exotic native cases above. The disposable timing fixture is not part of ordinary CI. Retired proof PR #3056 remains closed without merge, with its branch and evidence preserved; never reopen or reuse its pre-chronology admissions. PR #3081 also remains disposable and must not be merged. Implementation and proof status belongs to [Platform Operations and Delivery](../project-management/implementation-tracking/platform-operations-and-delivery.md). +The shipped [preservation contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) asserts canonical assessment, ordinary listener scope, and the retained fail-closed identity, evidence, chronology, history, admission, and confirmation boundaries. Implementation and proof status belongs to [Platform Operations and Delivery](../project-management/implementation-tracking/platform-operations-and-delivery.md). -The shipped [preservation contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) asserts canonical assessment, ordinary listener scope, and the retained fail-closed identity, evidence, chronology, history, admission, and confirmation boundaries. +Completion callbacks and advisory summaries distinguish the native preservation job from substantive validation. The Runtime Images PR callback requires the preservation step to have been skipped and substantive Validation enforcement to have run. Detached Validation Summary excludes metadata attempts when their change detector skipped. A metadata completion can still enter its source-head queue and displace a pending summary for a retarget without changing required-gate authority. Account Service and Game Session validation each use four independent matrix partitions. Account retains two test forks per partition. On Linux, Game Session caps `integrationTest` at two JVM forks, bounded by Gradleโ€™s worker count; JUnit methods within each suite remain serial, and other platforms retain their existing single-fork behavior. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so the moduleโ€™s partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attemptโ€™s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attemptโ€™s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from every measured partition. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test taskโ€™s execution data, without recompiling aggregate classes. World Management uses the same provenance and aggregation contract with two whole-class partitions balanced collectively across its unit, integration, and cross-service tasks. The existing Validation Gate requires every selected module matrix group and the corresponding coverage aggregate when any of the three slow services is affected. Ordinary local checks for all three services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. @@ -68,9 +68,7 @@ Account Service and Game Session validation each use four independent matrix par Workflows live in the `.github/workflows/` directory. A typical pipeline runs on every pull request and on pushes to the long-lived publication branches (`develop` today, and `main` for release-oriented publication paths). -The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical titleโ€™s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account, Game Session, or World Management module. World requires its native two-partition declaration; historical World full-check jobs remain valid without an aggregate. Account and Game Session retain attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. - -The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. Serialization uses branch and immutable head SHA so superseded heads cannot evict current-head pending callbacks. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. +The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical titleโ€™s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account, Game Session, or World Management module. World requires its native two-partition declaration; historical World full-check jobs remain valid without an aggregate. Account and Game Session retain attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. The optional [PR LOC Report](../../.github/workflows/pr-loc-report.yml) is also a trusted default-branch callback after `CI โ€” Validation` completes. It takes the PR number, base, and head from the `ci.yml` run's canonical title and checks GitHub's native PR association, as Validation Summary does, and acts only on an open, same-repository, non-Renovate PR that still has that exact base and head and on a run that was not metadata-only. It rewrites only the marked LOC section of the PR body with `dev-tools/maintenance/cloc-report.py`, which rechecks that the PR is open on the same refs, base, head, and body and skips while CodeRabbit shows a review in progress (status, check run, or processing comment) immediately before the edit. It skips when metadata inside a complete marked section already matches the head and base. GitHub's body update has no atomic precondition, so the edit is best effort. Each source CI run has its own concurrency group, so callbacks for different runs never cancel each other; a rerun attempt of the same run may replace that run's still-pending callback. Its `GITHUB_TOKEN` edit starts no workflow runs, so it never creates metadata-only gate runs. It is not a gate and adds no check to the PR head. @@ -78,21 +76,18 @@ The optional [PR LOC Report](../../.github/workflows/pr-loc-report.yml) is also | Workflow | Execution context | Responsibility | What its GitHub run means | | --- | --- | --- | --- | -| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | -| [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits keep the required `Smoke Gate` context but do not dispatch or cancel runtime construction; preservation follows [Required Gate Preservation](#required-gate-preservation), including an acknowledged supplementary pending barrier until matching substantive proof succeeds. | +| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run held-admission qualification when required by runtime scope, upload the image archive named for the verified merge SHA, and report the required `Smoke Gate` from the same run | The recorded base/head/merge input was built without registry-write credentials. A build-only archive carries no held-admission smoke proof. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | | [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) (`Publish PR Runtime Images`) | Trusted default-branch `workflow_run` or typed `repository_dispatch` definition | Verify the current PR and exact source artifact identity, then publish immutable `pr-merge-` tags in GHCR | GitHub displays the default branch because the trusted publisher runs there; its summary identifies the source PR run and base/head/merge SHAs. | | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required Smoke Gate accepts a successful credential-free smoke run for its verified PR-event base/head/merge tuple. If GitHub supplies no usable event merge SHA or the event base SHA already lags the event merge's parents, the gate instead requires a successful trusted, typed refresh for the verified current base/head/merge tuple. An unrelated base advance after valid event-tuple smoke does not invalidate that tested merge or require the PR head to absorb new dependencies; a changed PR head or base branch requires new proof. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. The credential-free runtime producer and required Smoke Gate cover every PR base, including same-repository feature branches, while retaining runtime path classification and an explicit no-op for irrelevant changes. Hosted preview and registry publication retain their separate eligibility policy: a stacked pull request requires the maintainer-controlled `preview:priority` label, an open mergeable state, and a current same-repository base. Completed Validation callbacks qualify long-lived branch pushes or substantive same-repository PR heads against the current branch ref before dispatching child-specific exact base/head/merge runtime refreshes. PR callbacks verify the current native CI attempt and executed substantive enforcement with skipped metadata preservation before reconciling their source PR's current tuple, recovering retarget edits whose event merge cannot qualify. Metadata-only, superseded, or unclassifiable attempts do not reconstruct runtime. PR-completion reconciliation is isolated by source run ID and attempt, so a metadata completion cannot cancel a substantive refresh; protected branch publication retains its separate branch serialization. Dependent refresh for `main` and `develop` belongs only to their push callback; PR callbacks whose head is one of those branches still reconcile their own source PR. A stale parent callback cannot dispatch proof for an advanced branch, and the callback itself supplies no child smoke proof. Preview reconciliation is dispatched only for independently eligible targets; scheduled preview reconciliation remains an additional recovery path. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own held-admission qualification succeeds and the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. +The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required `Smoke Gate` is a job in the pull_request run of Build Runtime Images. That run has no path filter: its change detection skips the build jobs for docs-only or frontend-only changes, and the gate then passes without runtime proof. Otherwise the gate requires that run's image build, its full-stack smoke when runtime scope requires it, and its controller smoke when required. Runs are not cancelled, because GitHub orders group cancellation by arrival and a delayed older run could cancel the current one; instead a run whose PR head or base branch has since moved skips its smoke jobs, and each run's gate reports for its own head and test merge. Branch protection requires branches to be up to date before merge, so that proof covers the merged base; a retarget edit is substantive and builds the recomputed test merge. Metadata-only edits preserve the gate through the shared [preservation contract](#required-gate-preservation), which accepts the runtime run title's trailing `merge- mode-` tokens. Typed refreshes build and publish images but do not report the gate. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. The credential-free runtime producer and required Smoke Gate cover every PR base, including same-repository feature branches, while retaining runtime path classification and an explicit no-op for irrelevant changes. Hosted preview and registry publication retain their separate eligibility policy: a stacked pull request requires the maintainer-controlled `preview:priority` label, an open mergeable state, and a current same-repository base. Completed Validation callbacks qualify long-lived branch pushes or substantive same-repository PR heads against the current branch ref before dispatching child-specific exact base/head/merge runtime refreshes. PR callbacks verify the current native CI attempt and executed substantive enforcement with skipped metadata preservation before reconciling their source PR's current tuple, recovering retarget edits whose event merge cannot qualify. Metadata-only, superseded, or unclassifiable attempts do not reconstruct runtime. PR-completion reconciliation is isolated by source run ID and attempt, so a metadata completion cannot cancel a substantive refresh; protected branch publication retains its separate branch serialization. Dependent refresh for `main` and `develop` belongs only to their push callback; PR callbacks whose head is one of those branches still reconcile their own source PR. A stale parent callback cannot dispatch proof for an advanced branch, and the callback itself supplies no child smoke proof. Runtime producers group by exact PR/base/head/merge tuple without cancellation: duplicate requests wait in GitHub's bounded `queue: max` behind the running producer, none replaces another, and a full queue rejects new arrivals. Base-branch callbacks, the dispatch-mode preview job and the trusted preview refresh observer send `pr-runtime-base-refresh` directly. Any writer can send that dispatch, so the receiver treats its payload as untrusted and revalidates the live open same-repository PR, current base ref, head and ordered merge parents before building. A typed refresh builds only when no `pr-merge-` tag exists in GHCR; any existing tag means a publisher already started, and a partial set that no publisher finishes is a manual hold. Hosted consumers wait until every tag exists or their timeout passes; they do not track producer runs. Preview reconciliation is dispatched only for independently eligible targets; scheduled preview reconciliation remains an additional recovery path. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own held-admission qualification succeeds when runtime scope requires it, and after the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed and its image artifact upload succeeds; an exception pass with no uploaded artifact cannot dispatch publication. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. -The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. - -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` โ†’ `PLAY` โ†’ `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` โ†’ `PLAY` โ†’ `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. +The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths. A publisher that finds the complete tag set already published exits without change; otherwise it preserves identical existing images and rejects conflicting image bytes. It publishes only when the source run holds the archive named for its titled merge. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. Provenance is tag-level: the write-once image-ID check proves that a `pr-merge` tag holds a validated artifact for that merge, not which source attempt produced it. If a publisher writes only some fixed merge tags, rerun it while the source artifact exists and the source run still passes validation. Otherwise the partial set is a manual hold: delete the partial tags or push a new PR head, because a rebuild cannot match the published image IDs. -The producer guarantee, independent of smoke-step metadata but requiring an explicit skipped exception marker, is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision, and typed refresh attempts use their native default-branch `head_sha`. During producer rollout, only verified typed refreshes can also use the reviewed previous successful workflow definition. Both paths keep the existing marker, attempt, and execution proof requirements. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. +The full-stack smoke job's terminal guard requires both the smoke step and authenticated cleanup to succeed. A temporary diagnostic exception covers the canonical cutover: when smoke fails only with the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, and authenticated cleanup succeeded, the guard reads the PR's labels from the API at that moment and passes only while the `canonical-play-transition` label is present (rerun the job after adding or removing the label). Every other failure still fails CI. The marker step records that evidence; image export and upload must be skipped, so the publisher has nothing to publish and the trusted workflow-run publisher skips its privileged job. This is gate acceptance for the nonproduction canonical cutover, not runtime qualification, branch-image promotion or preview eligibility. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` โ†’ `PLAY` โ†’ `LOOK` smoke and cannot use this exception; branch images remain on hold until the Account entitlement path is repaired. Remove the marker and the guard's waiver when fresh-image backend `LOGIN` โ†’ `PLAY` โ†’ `LOOK` passes. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. Branch-to-environment promotion contract: @@ -112,7 +107,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions, and World Management uses two; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. - Gradle-based Validation and runtime builds, including affected-module checks, controller builds and the source-built Compose boot-jar command, can recover one exact pinned Gradle-wrapper distribution HTTP 429, 500, 502, 503 or 504 failure before any Gradle task starts. The recovery uses only the official Gradle GitHub release-asset API for the same stable version, requires the release asset digest and downloaded bytes to match the repository's SHA-256 pin, checks the exact asset size, and atomically seeds the ordinary wrapper cache without replacing existing bytes. Metadata and asset requests have bounded time/size limits. The unchanged wrapper command then retries once and still verifies/extracts its own archive. No alternate Gradle version, mirror, compiler/test retry or successful runtime claim is introduced; missing, inconsistent, custom-layout, mixed, interrupted or unrecognized evidence retains the original failure. -- Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command. The retry normally refreshes dependencies. Exact buildSrc, Buf-generated Java and Checkstyle classpath JAR failures consisting entirely of Maven Central HTTP 429 responses keep cached dependency metadata for that retry. The same cached retry applies when a matching annotation-processor classpath fails before compilation because Maven Central returned HTTP 429 for the Spring Boot validation POM. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. +- Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command. The retry normally refreshes dependencies. Exact buildSrc, Buf-generated Java and Checkstyle classpath JAR failures consisting entirely of Maven Central HTTP 429 responses keep cached dependency metadata for that retry. The same cached retry applies when a matching annotation-processor classpath fails before compilation because Maven Central returned HTTP 429 for the Spring Boot validation POM. A typed configuration-cache failure on a module's own `compileClasspath` also keeps cached metadata when every fatal chain identifies a direct dependency and its exact Maven Central POM read returned HTTP 429. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. - On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service, Game Session, and World Management partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partitionโ€™s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, World Management uses a two-partition matrix, with remaining modules in a fourth matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. While unrelated matrix jobs continue uploading artifacts, provenance capture retries whole artifact listings within a fixed bound and accepts only two consecutive identical complete snapshots. Incomplete or shifting pages are discarded; persistent instability or invalid provenance fails closed without publishing a partial snapshot. World partitions balance measured whole-class costs across unit, integration, and cross-service tasks collectively; nested classes stay with their enclosing class, and newly compiled classes receive deterministic assignments. Only partition 1 builds the runtime JAR. Additional runner admission, compilation, and aggregation overhead must be measured before claiming elapsed-time savings. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account, Game Session, and World Management retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Runs the existing module check with Gradle's native `--profile`; Account, Game Session, and World Management partition jobs also profile their existing test-class preparation invocation before class selection. The workflow retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days, including profiles from both invocations when present. These reports expose startup, configuration, dependency and task durations. Profiling does not change the selected checks or recovery behavior; fork concurrency remains controlled by the task configuration above. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. @@ -122,7 +117,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Invokes a dedicated `generate-erd` job that runs [`dev-tools/docs/generate-erd.sh`](../../dev-tools/docs/generate-erd.sh) to build ERD diagrams from service migrations and upload them as artifacts. - Caches Buf modules, Node dependencies, Trivy database, and Gradle artifacts to speed up repeat workflow runs. - Runs markdownlint, blocking internal link checks, structural design contracts, and a MkDocs site build in pull-request CI. Push CI also checks external links; `docs.yml` verifies internal links again before publishing to GitHub Pages. -- Posts a summary comment on pull requests with test status and coverage, while Codecov publishes patch-coverage status separately. Native Validation, Security and Smoke comment jobs run only for uncancelled same-repository PR events whose actor is not `dependabot[bot]`; fork and Dependabot PRs retain check logs and artifacts. Failed dependencies still produce summaries. Publishers verify the current open PR head and base tuple before touching comments. Required gates retain their independent always-running conditions and fail-closed prerequisite evaluation. +- The detached [Validation Summary](../../.github/workflows/validation-summary.yml) publishes test status and coverage after `CI โ€” Validation` completes; inspect that separate `workflow_run` for missing comments. Codecov publishes patch-coverage status separately. The native Security comment job runs only for uncancelled same-repository PR events whose actor is not `dependabot[bot]`; fork and Dependabot PRs retain check logs and artifacts. Smoke reports through the native PR smoke jobs and the `Smoke Gate` check in Build Runtime Images; read their logs there. Failed dependencies still produce summaries. Publishers verify the current open PR head and base tuple before touching comments. Substantive PR runs, including a base retarget, retain independent required-gate evaluation. A title or body edit preserves the earlier canonical result for the same comparison. Both paths fail closed when their required proof is missing. Source-built MinIO helper changes require the same runtime-image smoke tracking and preview image selection as their Dockerfiles. Trusted runtime publication accepts the conventional source workflow API name while separately requiring the exact identity-bearing run title and source provenance. @@ -155,13 +150,13 @@ Other workflows support additional automation: - [`weekly-security-scan.yml`](../../.github/workflows/weekly-security-scan.yml) runs the weekly Trivy image scan. - [`ort-advisory.yml`](../../.github/workflows/ort-advisory.yml) runs the **Weekly ORT Advisory Scan**. - [`publish-base-image.yml`](../../.github/workflows/publish-base-image.yml) runs the **Weekly FireMUD Base Image Refresh** and is also the branch-guarded publication path for explicit base-image rebuilds on `develop` / `main`. -- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token. A successful smoke run proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. The [temporary diagnostic exception](#pull-request-runtime-and-preview-chain) provides no passing `PLAY` or `LOOK` proof and permits no image publication. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. +- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs held-admission qualification when required by runtime scope, without a registry-write token. A build-only archive can supply images for publication. A successful smoke run proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. The [temporary diagnostic exception](#pull-request-runtime-and-preview-chain) provides no passing `PLAY` or `LOOK` proof and permits no image publication. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. [Trusted branch publication](#building-and-pushing-images) smoke-tests the complete pinned image set before assigning aliases. --- ## Building and Pushing Images -Trusted branch images retain commit-SHA tags. Pull-request images are built locally without registry credentials; only the successful artifact for an exact base/head/merge crosses into the trusted publisher, which pushes immutable `pr-merge-` tags to **GitHub Container Registry (GHCR)**. Trusted `develop` and `main` builds first publish unique candidate tags, run full-stack smoke against those candidates, then assign commit-SHA and branch aliases to the tested digests. Shared build-cache tags are not deployment evidence. +Trusted branch images retain commit-SHA tags. Before creating a fixed tag after a manifest 404, trusted publication checks that the same credential can read the exact GHCR package. An unreadable package leaves publication held. Pull-request images are built locally without registry credentials; only the successful artifact for an exact base/head/merge crosses into the trusted publisher, which pushes immutable `pr-merge-` tags to **GitHub Container Registry (GHCR)**. The candidate runtime and controller smoke jobs use GitHub-enforced read-only Actions cache tokens because a typed repository dispatch runs on the default branch while building candidate code. Trusted `develop` and `main` builds publish unique candidate tags and run full-stack smoke before assigning commit-SHA and branch aliases to the tested digests. Runs for the same protected commit serialize. If all fixed SHA images already exist, the later branch skips the redundant service image build, smoke-tests the complete fixed set by digest, and uses those exact bytes for its aliases. If promotion refuses because a failed-job rerun retained stale digest-selection outputs, use **Re-run all jobs** to select and smoke the current complete fixed set before promoting aliases. To complete a partial fixed set, retain every existing fixed tag by its exact digest and build and stage only the missing services. Fresh smoke qualifies the resulting complete set together. Promotion rechecks the full fixed set before writing any missing tag and refuses to replace or reconstruct an existing fixed tag. Shared build-cache tags are not deployment evidence. The `hosted-environment-identity-controller` image is a trusted infrastructure artifact published only by its dedicated job during trusted-source `develop` and `main` runs. That job builds the controller service from the checked-out branch commit against the exact registry-returned `firemud-base` digest produced by its prerequisite job, smokes the exact local controller image, pushes that same image to the dedicated `ghcr.io/benhook1013/firemud-hosted-identity-controller` package, and records SLSA provenance for the registry-returned controller digest. A pre-existing tag is overwritten by the exact smoke-tested build rather than accepted as trusted. Pull-request runs may build and smoke a clearly local controller image without registry credentials, but they exclude it from the exported PR runtime-image artifact, and the trusted PR artifact publisher never publishes it. Runtime deployment accepts only a digest-pinned reference from the dedicated controller package whose GitHub attestation verifies the `runtime-images.yml` signer workflow and a `develop` or `main` source ref. @@ -191,7 +186,7 @@ The mutable `firemud-base:latest` tag is a branch-publication convenience tag fo Hosted Kubernetes rollouts use environment-specific GitHub Actions workflows rather than a generic manual Helm button: - [`preview.yml`](../../.github/workflows/preview.yml) renders and publishes a sanitized full-stack chart artifact without deployment credentials; the trusted default-branch [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) validates the exact source run, pull-request head, and artifact before deploying per-PR preview namespaces in either certificate-identity mode. -- [`dev-demo.yml`](../../.github/workflows/dev-demo.yml) renders and deploys the same chart for the fixed `develop` dev-demo environment. +- [`dev-demo.yml`](../../.github/workflows/dev-demo.yml) renders and deploys the same chart for the fixed `develop` dev-demo environment. Deployment uses the deploy head's immutable SHA tags only and waits until all of them exist in GHCR; tags are published only by the protected promotion after its smoke, so their presence is the publication proof. Re-smoking an already published fixed image set can qualify alias publication. A successful dev-demo deployment additionally requires its own rollout and smoke checks. - Local Kubernetes iteration uses direct `helm template`, `helm lint`, `helm install`, and `kubectl apply -k` commands rather than a GitHub-hosted workflow wrapper. Staging and production deployments rely on environment-specific overlays (for example `k8s/overlays/stage` and `k8s/overlays/prod`). The steady-state production target follows [ADR 0177](decisions/adr-0177-exact-plan-authorized-automated-production-deployment.md): an operator approves one immutable exact plan, then a protected executor revalidates and runs preflight, apply, observation, evidence capture, and only pre-authorized compatible restoration. Manual `kubectl` from a secured workstation or bastion remains the bootstrap, current implementation, and audited break-glass path. @@ -235,22 +230,26 @@ Release dependency-notice automation is a separate concern from repository scrip --- +Runtime image builds and smoke proof retain their source commit and attempt identity. The branch promotion job serializes mutable-tag updates for each branch and verifies its live head inside the promotion queue. + ## PR Preview Environments FireMUD's preview workflow is reserved for real reviewer-accessible PR environments, not CI-only stack boot validation. The [`.github/workflows/preview.yml`](../../.github/workflows/preview.yml) workflow targets a hosted single-node k3s cluster and follows this contract: -- Build and smoke-test PR merge images in the credential-free job, then publish the verified artifact to private GHCR under the immutable `pr-merge-` tag from the trusted default-branch publisher. -- Deploy or upgrade Helm release `pr-` into namespace `pr-`. +- Build the exact PR merge images in the credential-free job and run smoke when runtime scope requires it. The trusted default-branch publisher publishes the verified artifact to private GHCR under the immutable `pr-merge-` tag. An eligible build-only archive supplies the images without smoke proof. +- Render the chart with Helm. The trusted consumer applies the validated Kubernetes manifest in namespace `pr-`. - Expose the environment at `https://pr-.preview.` using cluster ingress/TLS. - Expose a reviewer-usable TCP/Telnet entry path for the preview stack so manual gameplay proof can happen through the normal MUD client surface. - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, the preview source workflow definition runs from the repository default branch on `pull_request_target` or typed `repository_dispatch`; only its GitHub-hosted, read-only render job checks out the PR merge candidate. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance, current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The render checkout loads tools and local actions from the default branch, while a separate exact PR merge checkout supplies Helm chart data only. A pull-request-owned workflow definition can change its own steps, so that checkout is not itself a privilege boundary: the boundary is that PR-controlled build and render work receives no cluster, registry-write, or hosted-identity requester credentials, and only default-branch-owned privileged workflows exercise trusted authority, never executing candidate scripts or actions. The write-capable runtime refresh in the source workflow runs only for typed dispatch. For `pull_request` runs, the default-branch [`preview-runtime-refresh.yml`](../../.github/workflows/preview-runtime-refresh.yml) observer runs on `workflow_run`. It takes nothing from the PR-authored run except GitHub's own PR association (or, when that is empty, the native `refs/pull//merge` workflow path or an open PR for the head branch). It reads the live PR, base ref and test merge, applies the default-branch eligibility and image-selection policy, and sends `pr-runtime-base-refresh` only for an eligible live tuple whose merge has the live base and head as ordered parents and whose base moved since the event or is not `main` or `develop`. It never checks out candidate code or downloads artifacts. The trusted default-branch lifecycle consumes the sanitized render artifact only after validating source-run provenance (a `pull_request` source run binds its PR number through GitHub's association with the artifact's head, or through the exact `refs/pull//merge` workflow path when the association is empty), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. The reconciler and the trusted identity and runtime jobs run on GitHub-hosted `ubuntu-latest` runners; a network path and credentials for those runners to reach the preview cluster API are a separate prerequisite, and both workflows stay inert until the `PREVIEW_GITHUB_HOSTED_CLUSTER_ACCESS` repository variable is `true`. Until then, the self-hosted Preview Namespace Janitor removes runtimes of closed PRs and, whenever requester credentials exist, retires their identities in either certificate mode. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. + +The verified repository event-policy update allows `pull_request`, `pull_request_target`, and `repository_dispatch` for `preview.yml`. If readback shows the prior exception, hold rollout until the additive permission is restored. The policy update alone does not activate hosted deployment or cleanup, and the retained `pull_request_target` allowance does not start a render once the new definition removes that trigger. After the new definition takes effect, verify fresh natural PR and manual-dispatch events against the merged code. Keep the `pull_request_target` allowance until the trusted-tools, read-only `pull_request` route is the effective default and a fresh natural preview event and an observer-dispatched runtime refresh prove the same exact PR/base/head/merge tuple. Removing the old allowance then requires separate review and approval at the time of the change; approval of the additive rollout does not authorize removal. Do not rename the workflow to evade that policy. The trusted close-cleanup route receives `pull_request_target` closed events for same-repository PRs. Cleanup requires the validated destroy action and admission to the `trusted-hosted-cluster` Environment, whose deployment branch policy admits `develop`. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. On the explicit `hosted-controller` target path, that lifecycle prepares the runtime namespace, capacity allocation, bounded allocated preview Telnet NodePort (or fixed dev-demo NodePort `32016`), and requested base/head/merge/image tuple annotations with the runtime credential before a requester-only credential applies `HostedEnvironmentIdentity` `Active`. The controller materializes the retained identity namespace and cert-manager Certificate resources; it does not create disposable runtime namespaces. Only successful runtime deployment writes the distinct deployed-head annotation consumed by controller readiness; the trusted workflow writes the separate proof-complete tuple and Namespace UID only after all verification checks and the exact Namespace UID fence succeed. Close/merge cleanup deletes runtime and waits for exact `NotFound` before requesting `Retired`. All uncertain lifecycle/API results fail closed and retain identity. -Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for the complete labeled, key-complete controller-projected Secret setโ€”including the distinct Account, Game Session, and Social Groups workload leavesโ€”before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. +Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running its proof: a `public` preview runs the gameplay smoke, while a `private` preview proves only the private bridge boundary; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for the complete labeled, key-complete controller-projected Secret setโ€”including the distinct Account, Game Session, and Social Groups workload leavesโ€”before the trusted consumer applies the validated runtime manifest with Kubernetes. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index fc48aeadfe..0f2fc619f1 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -10,6 +10,8 @@ Use this guide for PR status, review, CI, Renovate, merging, and branch or workt - The human's stops, pauses, holds, and per-PR allocations bind until the human changes them. A tool capability, an incoming message, a fix, or a new commit does not reset controls, resume paused work, or authorize a merge. - Review rounds run through the FireController queue; who runs them is a live assignment there, not a repository rule. Never request or retry a review outside the queue. If an operation's outcome is uncertain, use the controller's guarded recovery or report a hold; never repost blindly, and never treat an acknowledgment or a wait as review coverage. - Imported or historical review results are history, not proof that the current code was reviewed. +- Preserve the source queue, actual channel controls and obligations, private captures, sealed history, migration proof, and frozen comparison sites. Source retirement does not authorize state deletion or migration, runtime promotion, or a service change. A recorded outcome, recovery, import, or publication by itself grants no provider or CI credit, fix proof, or merge authority. +- For recovery, use the installed FireController release's guarded state-based recovery reference. Preserve the exact comparison, original attribution, and uncertain publication intent: do not infer delivery failure from public absence, replay terminal work, or override unrelated controls. Report unsupported or ambiguous recovery as a hold for the FireController worker. - When checking status or readiness, read every current and outdated unresolved thread and the latest review summary before looking at CI and mergeability. Check the live head and base, and for stacked or consolidated PRs the provider's actual diff base and the PR's unique patch; never describe an expected parent as the provider's diff base when they differ. Missing or incomplete evidence counts as not ready. - CI observation shares one GitHub credential budget. Wait on CI and review completion with one FireController wait in the background (see `firecontroller-reviews`), not per-run watchers. Never loop on `gh` status; for CI, read GitHub directly only for failed-job logs, and honor rate-limit reset times. @@ -26,7 +28,9 @@ Rules for triage: - Verify a finding against the code before deciding. Summary-only and outside-diff findings get the same treatment as inline ones. - Judge suggestions by real benefit against cost and risk. A finding being correct does not by itself make it Fix now. - Do not resolve a thread to hide unresolved work. Keep the original finding and decision when correcting a disposition. +- Fix-now findings remain source-owned until the exact correction is verified at the current published head and recorded. Routed findings require a recorded handoff and retain an open obligation with the receiving owner, not a fix on the source head. For rejection or withdrawal, record the concrete reason and current-head evidence that no actionable work remains. Report outdated unresolved threads separately. Missing, malformed, unattributed, or incomplete evidence fails closed; an acknowledgment or edited standing summary cannot prove completion or an empty inventory. - Routed findings do not block this PR. The receiving owner decides on them independently, and routes arriving at this PR are dispositioned before it is ready. The Overseer, or the human, reviews the routed backlog at milestones so routes do not pile up unowned. +- Retargeting a route preserves the original finding, its open obligation, and its prior ownership, including honest unassigned work. A route is not a claim that the recipient has accepted or fixed it. - Track whether each round's findings are new or repeats of earlier ones. - Default to the smallest correct fix. When a finding lands in code an earlier review fix added, or in an area that drew findings in earlier rounds, fix the cause instead of adding another special case: simplify or delete within that area, and use the real tool rather than imitating it. A fix should not grow the code without a stated reason. If the cause needs more, such as replacing a component or a cross-module change, raise it as a decision for the Overseer or the human instead of patching around it. - Bot findings do not need routine public replies beyond the route or reject note above. @@ -78,6 +82,7 @@ Merge authority: - Stacked PRs are fine when the base dependency is explicit. After a parent merges, retarget the child to `develop` before rebasing or pushing it. - When active work moves to another worktree, report its absolute path and branch. - CI coverage for stacked bases, required gate names, and preview restrictions are owned by [CI/CD](../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain). +- Verify the committed candidate and live head/base, effective parent, provider-observed diff base, ancestry, and unique patch before relying on review evidence. Refresh the evidence when the reviewed diff changes. Preserve the owned patch, findings, evidence, and configured controls during reconciliation. Evaluate each workflow result under its owning [CI proof contract](../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain). A base-ref retarget requires replacement validation. Metadata-only edits may preserve original proof for the current comparison through the [required-gate preservation contract](../architecture/system-architecture-cicd.md#required-gate-preservation). - Use `dev-tools/validation/report-worktree-pr-topology.sh` for branch, worktree, and PR inventory (`--pr ` for one stack, `--json` for machine output, `--include-renovate` to include Renovate PRs). - After a merge, remove the defunct local worktree and merged branches only after confirming nothing open depends on them. Keep unmerged branches. - Pass PR-body Markdown through a file or stdin, not literal `\n` strings. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index da01ecd184..95e77442b5 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -466,7 +466,7 @@ This is service-level mock proof. It does not establish authenticated creator ac ### Validation and Proof -- Historical `888f` foundation proof: the canonical local Core, Game Design, and documentation gates passed. The published [Source Validation run](https://github.com/benhook1013/FireMUD/actions/runs/38180722581) completed with 316 Game Design tests, including 37 fresh PostgreSQL integration cases with zero skips; the [Rebuilt Runtime run](https://github.com/benhook1013/FireMUD/actions/runs/38180722436) verified credential-based `LOGIN`/`PLAY`/`LOOK` over WebSocket and Telnet. The overall Validation workflow and callbacks completed successfully. Startup-refusal proof was skipped; restart, source-bound fixture execution, and `CHARACTER_CREATE` activation remain unproved. These run links record historical evidence from `888f`. Focused local anchors are [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) and [PublishAttemptServiceTransactionIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java); workflow tooling is linked at [CI validation](../../../.github/workflows/ci.yml), [runtime image builds](../../../.github/workflows/runtime-images.yml), and [smoke validation](../../../.github/workflows/smoke.yml). +- Historical `888f` foundation proof: the canonical local Core, Game Design, and documentation gates passed. The published [Source Validation run](https://github.com/benhook1013/FireMUD/actions/runs/38180722581) completed with 316 Game Design tests, including 37 fresh PostgreSQL integration cases with zero skips; the [Rebuilt Runtime run](https://github.com/benhook1013/FireMUD/actions/runs/38180722436) verified credential-based `LOGIN`/`PLAY`/`LOOK` over WebSocket and Telnet. The overall Validation workflow and callbacks completed successfully. Startup-refusal proof was skipped; restart, source-bound fixture execution, and `CHARACTER_CREATE` activation remain unproved. These run links record historical evidence from `888f`. Focused local anchors are [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) and [PublishAttemptServiceTransactionIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java); workflow tooling is linked at [CI validation](../../../.github/workflows/ci.yml) and [runtime image builds and smoke](../../../.github/workflows/runtime-images.yml). - Fresh-tenant identity prerequisite proof covers bounded owner-local persistence, migrations, exact receipt readback, peer authorization wiring, and server peer identity interception through the seven focused test anchors in its [Capability Status row](#capability-status). The recorded reconciliation executed three physical PostgreSQL migration/repository cases and passed the Game Design and common-platform full checks, formatting, Checkstyle, SpotBugs, link, and Markdown checks; these results establish only the bounded storage/readback slice and are not new validation from this documentation update. - The transferred V1033 original-outcome PostgreSQL test definitions cover typed creation readback/replay, durable tombstone and delayed-write refusal, shared-lock serialization, direct-SQL immutability, and retained V30 rows. Proof2 passed eight selected Game Design cases, but these physical PostgreSQL definitions remain unexecuted locally because Docker and psql were unavailable. Controlled Account bindings do not prove authenticated creator authority or a complete creation flow. - Current #3151 asset-source proof applies only to `0c15969765bd0d48bbf78a4ea5ba93e959597c70`: [Source Validation run 38205959330](https://github.com/benhook1013/FireMUD/actions/runs/38205959330), job `114670029762`, physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips. The run included all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; individual focused-method counts are not asserted. The focused anchors are [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java) for `requireSelectorBinding` and [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java) for V49/V49.1 schema execution; their included cases have no inferred separate counts. [Rebuilt Runtime run 38205959393](https://github.com/benhook1013/FireMUD/actions/runs/38205959393), job `114669861395`, failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`; no rebuilt smoke proof is established for this head. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 78ac613d0d..9554bb0e55 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -80,7 +80,7 @@ These links record implementation and proof gaps; they do not claim that the cor | `PO-3.4` Backup, restore, disaster recovery, and self-hosted recovery | `partial` | `drift-found`: bounded online-dump and backup-verifier helper/image contract checks, non-executing restore wiring, reset, and restart seams are proven locally; no live backup existence/reachability is proven, and the broader recovery capability remains unproven | [Backup/recovery](../../architecture/system-architecture-backup-recovery.md); [recovery evidence](../../architecture/system-architecture-backup-recovery-evidence-and-compliance.md); [CI/CD](../../architecture/system-architecture-cicd.md) | [schedule.yaml](../../../k8s/velero/schedule.yaml); [verify-backups-cronjob.yaml](../../../k8s/velero/verify-backups-cronjob.yaml); [manual-backup-restore.yml](../../../.github/workflows/manual-backup-restore.yml); [pg-dump-rotate.sh](../../../dev-tools/backups/pg-dump-rotate.sh); [restore-cluster.sh](../../../dev-tools/restores/restore-cluster.sh); [reset-service-db.sh](../../../dev-tools/restores/reset-service-db.sh); [smoke-backup-verifier-image.sh](../../../dev-tools/backups/smoke-backup-verifier-image.sh) ยท [Recovery journal](../../../services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java) | [verify-backups.sh](../../../dev-tools/backups/verify-backups.sh); [verify-backups-velero-contract.sh](../../../dev-tools/tests/verify-backups-velero-contract.sh); [verify-backups-cronjob-contract.sh](../../../dev-tools/tests/verify-backups-cronjob-contract.sh); [backup-verifier-image-contract.sh](../../../dev-tools/tests/backup-verifier-image-contract.sh); [reset-service-db-contract.sh](../../../dev-tools/tests/reset-service-db-contract.sh); [verify-restart-state.sh](../../../dev-tools/verify-restart-state.sh) ยท [Recovery PostgreSQL proof](../../../services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The [Backup helper README](../../../dev-tools/backups/README.md) documents the helper boundaries. Measured verified-point RPO, immutable artifact and restore lineage, readable restore execution, environment-wide cold-start quarantine and reconciliation, post-restore trust reset, and controlled traffic reopen remain unimplemented or unproven. The source-only Recovery Controller initial-gameplay journal foundation has landed on this comparison; activation remains unregistered pending owner integration and the [Player Access proof](./player-access-and-session.md#initial-gameplay-recovery-foundation-status). | | `PO-4.1` Logging, metrics, tracing, dashboards, and alerting | `partial` | `drift-found` | [ADR 0017](../../architecture/decisions/adr-0017-capability-gated-operational-tracing.md); [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md); [ADR 0167](../../architecture/decisions/adr-0167-allowlisted-sensitive-trace-attributes.md); [Logging/monitoring](../../architecture/system-architecture-logging-monitoring.md); [tracing](../../architecture/system-architecture-tracing.md) | [RuntimeIdentity.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [MetricsInterceptor.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/MetricsInterceptor.java); [GameplayWebSocketObservability.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [check-metrics-cardinality.py](../../../dev-tools/observability/check-metrics-cardinality.py); [validate-observability-contract.py](../../../dev-tools/observability/validate-observability-contract.py); [player-experience-smoke-runner-contract.sh](../../../dev-tools/tests/player-experience-smoke-runner-contract.sh); [GameplayWebSocketObservabilityTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservabilityTest.java) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player experience](./player-experience-commands-and-communication.md) | ADR 0017 level 1 (baseline observability) is the highest current advertisement: metrics and structured logs are the dependable surface, while generic RPC spans/export and trace-log correlation are best-effort. No named workflow has level-2 end-to-end proof; service-scoped sampling (level 3), tenant/game-instance/region sampling (level 4), broad region enrichment, embedded dashboards, and recovery-participant convergence observability remain unproved. The missing-source alert is fail-safe gap detection only and does not establish recovery readiness. The current profile overlays install only the applicable deadman rules; the player-flow canary and public-path blackbox alert families remain target-only and uninstalled pending deployment-owned gates. Capability-aware installation, deployment-owned external alert authority, atomic profile-transition cleanup, residual-series handling, and live proof remain implementation gaps. | | `PO-4.2` Health, readiness, reliability policy, SLOs, and degraded operation | `partial`: dependency-readiness tracking and bounded gameplay/Telnet readiness gates are live; staged profile-aware SLO enforcement and complete control-action degradation partitions are not | `proven` for the previously named readiness transition, health-indicator, admission, scheduler, and evidence-shape seams only; the Game Session Ping-plus-HTTP dependency-readiness child retains its historical 70-case qualification; the direct Entity Management readiness repair separately passed 40 focused client/indicator cases and selected static/format checks (these suites overlap and are not additive); source-built held-admission smoke at `fc282035` passed backend WORLDS/LOGIN/PLAY/LOOK/LOGOUT with actual Gateway/Telnet denial and clean teardown; deployed Kubernetes readiness and successful public admission remain `unrun`; there is no executable proof of ADR 0160 enforceable SLO claims or ADR 0165 control-action failure modes | [Deployment preflight policy](../../architecture/system-architecture-deploy-preflight-policy.md); [logging and monitoring](../../architecture/system-architecture-logging-monitoring.md); [ADR 0160](../../architecture/decisions/adr-0160-staged-profile-aware-player-experience-slo-contract.md); [ADR 0165](../../architecture/decisions/adr-0165-authoritative-control-actions-during-observability-loss.md) | [DependencyReadinessSupport.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/health/DependencyReadinessSupport.java); [ReadinessTransitionTracker.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/health/ReadinessTransitionTracker.java); [EntityManagementClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java); [GameplayPathReadinessHealthIndicator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [ReadinessTransitionTrackerTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/health/ReadinessTransitionTrackerTest.java); [EntityManagementClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java); [GameplayPathReadinessHealthIndicatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java); [TelnetReadinessAdmissionIntegrationTest.java](../../../services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TelnetReadinessAdmissionIntegrationTest.java); [TickSchedulerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [player-experience-smoke-evidence-contract.sh](../../../dev-tools/tests/player-experience-smoke-evidence-contract.sh) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player access](./player-access-and-session.md) | Representative calibration, minimum-sample handling, enforceable SLO evidence, endpoint-class readiness, owner/audit sequencing, stable retry identity, isolation, and production-scale degraded-operation proof remain gaps. | -| `PO-4.3` Unit, integration, contract, static-analysis, and load verification | `partial`: deterministic repository unit, integration, contract, static-analysis, and bounded load-fixture seams exist; enforceable claims and production-like fault/load verification remain incomplete | `proven` for the named deterministic repository checks and bounded cross-service load fixture only; there is no current proof of enforceable claims or production-like fault/load behavior | [Testing](../../architecture/system-architecture-testing.md); [ADR 0174](../../architecture/decisions/adr-0174-maturity-scoped-protobuf-compatibility.md) | [build.gradle.kts](../../../build.gradle.kts); [ci.yml](../../../.github/workflows/ci.yml); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh); [check-flyway-versions.sh](../../../dev-tools/validation/check-flyway-versions.sh) | [gradle-proof-tooling-contract.sh](../../../dev-tools/tests/gradle-proof-tooling-contract.sh); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh); [check-flyway-versions.py](../../../dev-tools/validation/check-flyway-versions.py); [static-analysis-summary-contract.sh](../../../dev-tools/tests/static-analysis-summary-contract.sh); [MultiplayerLoadProofCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java) | All other trackers | Focused proof for enforceable claims, the maturity-scoped protobuf compatibility gate, and production-like fault/load behavior remains incomplete. | +| `PO-4.3` Unit, integration, contract, static-analysis, and load verification | `partial`: deterministic repository unit, integration, contract, static-analysis, and bounded load-fixture seams exist; enforceable claims and production-like fault/load verification remain incomplete | `proven` for the named deterministic repository checks and bounded cross-service load fixture only; static analysis runs in every module `check` but has no focused proof anchor, so it is not claimed as proven; there is no current proof of enforceable claims or production-like fault/load behavior | [Testing](../../architecture/system-architecture-testing.md); [ADR 0174](../../architecture/decisions/adr-0174-maturity-scoped-protobuf-compatibility.md) | [build.gradle.kts](../../../build.gradle.kts); [ci.yml](../../../.github/workflows/ci.yml); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh); [check-flyway-versions.sh](../../../dev-tools/validation/check-flyway-versions.sh) | [gradle-proof-tooling-contract.sh](../../../dev-tools/tests/gradle-proof-tooling-contract.sh); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh); [check-flyway-versions.py](../../../dev-tools/validation/check-flyway-versions.py); [MultiplayerLoadProofCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java) | All other trackers | Focused proof for enforceable claims, the maturity-scoped protobuf compatibility gate, and production-like fault/load behavior remains incomplete. | | `PO-4.4` Smoke, canary, incident evidence, and architecture conformance proof | `partial`: local smoke, restart/image entrypoints, the player-experience runner, and retained evidence-shape validation are live; independently scheduled synthetic canaries, asynchronous backend emit-and-query execution, and complete profile/event/fault evidence are not | `proven` for the current transport smoke, runner, and retained evidence-shape contracts only; there is no proof of a continuously scheduled hosted canary, supported-backend queryability, recovery-event-bound execution, or transport-complete acceptance | [Testing](../../architecture/system-architecture-testing.md); [player-experience runbook](../../architecture/system-architecture-player-experience-incident-runbook.md); [ADR 0161](../../architecture/decisions/adr-0161-profile-aware-isolated-synthetic-player-flow-canaries.md); [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md); [ADR 0164](../../architecture/decisions/adr-0164-three-boundary-profile-aware-verification-evidence.md); [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md) | [verify-fresh-bootstrap.sh](../../../dev-tools/verify-fresh-bootstrap.sh); [verify-restart-state.sh](../../../dev-tools/verify-restart-state.sh); [verify-smoke-images.sh](../../../dev-tools/verify-smoke-images.sh); [run-player-experience-smoke.py](../../../dev-tools/observability/run-player-experience-smoke.py); [validate-player-experience-smoke-evidence.py](../../../dev-tools/observability/validate-player-experience-smoke-evidence.py); [preview.yml](../../../.github/workflows/preview.yml); [dev-demo.yml](../../../.github/workflows/dev-demo.yml); [smoke-full.yml](../../../.github/workflows/smoke-full.yml) | [smoke-transport-contract.sh](../../../dev-tools/tests/smoke-transport-contract.sh); [player-experience-smoke-runner-contract.sh](../../../dev-tools/tests/player-experience-smoke-runner-contract.sh); [player-experience-smoke-evidence-contract.sh](../../../dev-tools/tests/player-experience-smoke-evidence-contract.sh); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh) | All other trackers | Hosted scheduling/queryability, evidence binding/freshness, profile/fault coverage, isolation, recovery-bound proof, and same-head-bound disposable preview proof for both required Telnet and deployed-browser public paths remain incomplete. | ## Runtime Publisher Handoff Implementation Status diff --git a/dev-tools/hosted/preview/preview-runtime-refresh.cjs b/dev-tools/hosted/preview/preview-runtime-refresh.cjs new file mode 100644 index 0000000000..a7751e8288 --- /dev/null +++ b/dev-tools/hosted/preview/preview-runtime-refresh.cjs @@ -0,0 +1,113 @@ +"use strict"; + +// Live-API observer for completed PR-authored preview runs. The only input +// taken from the run is GitHub's PR association; everything else is re-read. +const { execFileSync } = require("node:child_process"); + +const SHA = /^[0-9a-f]{40}$/; + +function candidatePullNumbers(run, owner) { + const numbers = new Set(); + for (const pull of Array.isArray(run.pull_requests) ? run.pull_requests : []) { + if (Number.isSafeInteger(pull?.number) && pull.number > 0) numbers.add(pull.number); + } + // GitHub can report an empty association, for example after the test merge + // moved. The native workflow path then still names the PR merge ref. + const path = /^\.github\/workflows\/preview\.yml@refs\/pull\/([1-9][0-9]*)\/merge$/.exec(run.path ?? ""); + if (numbers.size === 0 && path) numbers.add(Number(path[1])); + return { numbers: [...numbers], headLookup: numbers.size === 0 && typeof run.head_branch === "string" && run.head_branch + ? `${owner}:${run.head_branch}` : null }; +} + +function defaultEligibility(pull, repository) { + try { + execFileSync("python3", [ + "./dev-tools/hosted/preview/preview-eligibility.py", "--revalidate-deploy", + "--expected-repository", repository, "--expected-head-sha", pull.head.sha, + ], { encoding: "utf8", input: JSON.stringify(pull) }); + return true; + } catch (error) { + if (error.status !== 1) throw error; + return false; + } +} + +function defaultImageTag(mergeSha, prNumber, baseSha) { + return execFileSync("bash", [ + "./dev-tools/hosted/preview/resolve-preview-image-tag.sh", mergeSha, String(prNumber), baseSha, + ], { encoding: "utf8", env: process.env }).trim(); +} + +async function observe({ github, context, core, isEligible = defaultEligibility, imageTag = defaultImageTag, + wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }) { + const run = context.payload.workflow_run; + const repository = `${context.repo.owner}/${context.repo.repo}`; + if (run?.event !== "pull_request" || run.head_repository?.full_name !== repository) { + core.info("Not a same-repository pull_request preview run; no dispatch."); + return []; + } + const { numbers, headLookup } = candidatePullNumbers(run, context.repo.owner); + if (headLookup) { + const { data: pulls } = await github.rest.pulls.list({ ...context.repo, state: "open", head: headLookup, per_page: 10 }); + for (const pull of pulls ?? []) numbers.push(pull.number); + } + const associations = new Map((run.pull_requests ?? []).map((pull) => [pull?.number, pull])); + const dispatched = []; + for (const number of numbers) { + // GitHub reports mergeable: null while it computes the test merge. + let pull; + for (let attempt = 1; attempt <= 3; attempt += 1) { + ({ data: pull } = await github.rest.pulls.get({ ...context.repo, pull_number: number })); + if (pull?.mergeable !== null || attempt === 3) break; + await wait(5000); + } + if (pull?.number !== number || pull.state !== "open" || + pull.head?.repo?.full_name !== repository || pull.base?.repo?.full_name !== repository || + !SHA.test(pull.head?.sha ?? "") || pull.mergeable !== true || !SHA.test(pull.merge_commit_sha ?? "")) { + core.info(`PR #${number} is closed, foreign, conflicted or not yet mergeable; no dispatch.`); + continue; + } + if (!isEligible(pull, repository)) { + core.info(`PR #${number} is not preview-eligible; no dispatch.`); + continue; + } + let base; + try { + ({ data: base } = await github.rest.git.getRef({ ...context.repo, ref: `heads/${pull.base.ref}` })); + } catch (error) { + // A deleted base branch makes this candidate obsolete; other errors stay fatal. + if (error?.status !== 404) throw error; + core.info(`PR #${number} base branch ${pull.base.ref} no longer exists; no dispatch.`); + continue; + } + const { data: merge } = await github.rest.repos.getCommit({ ...context.repo, ref: pull.merge_commit_sha }); + const parents = (merge?.parents ?? []).map((parent) => parent?.sha); + if (!SHA.test(base?.object?.sha ?? "") || merge?.sha !== pull.merge_commit_sha || parents.length !== 2 || + parents[0] !== base.object.sha || parents[1] !== pull.head.sha) { + core.info(`PR #${number} test merge is not yet the live base/head merge; no dispatch.`); + continue; + } + // The native pull_request runtime build already covers the event's own + // base on main or develop. Other bases and moved bases need a refresh. + const eventBase = associations.get(number)?.base; + if (["main", "develop"].includes(pull.base.ref) && eventBase?.sha === base.object.sha) { + core.info(`PR #${number} native runtime build already covers the live base; no dispatch.`); + continue; + } + if (imageTag(merge.sha, number, base.object.sha) !== `pr-merge-${merge.sha}`) { + core.info(`PR #${number} deploys base images; no runtime refresh.`); + continue; + } + const payload = { + pr_number: String(number), base_ref: pull.base.ref, base_sha: base.object.sha, + head_sha: pull.head.sha, merge_sha: merge.sha, + }; + await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: "pr-runtime-base-refresh", client_payload: payload }); + core.info(`Dispatched PR #${number} runtime refresh for ${pull.base.ref}@${base.object.sha} / ${merge.sha}.`); + dispatched.push(payload); + } + return dispatched; +} + +module.exports = observe; +module.exports.candidatePullNumbers = candidatePullNumbers; diff --git a/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh b/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh index b4b949ed09..e796776545 100644 --- a/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh +++ b/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh @@ -58,8 +58,9 @@ if [[ "$retire_terminal_identities" == true ]]; then echo "--retire-terminal-identities requires --apply" >&2 exit 2 fi - if [[ "${HOSTED_IDENTITY_MODE:-}" != hosted-controller ]]; then - echo "refusing terminal identity retirement unless HOSTED_IDENTITY_MODE=hosted-controller" >&2 + # Standalone mode still retires identities kept from hosted-controller mode. + if [[ "${HOSTED_IDENTITY_MODE:-}" != hosted-controller && "${HOSTED_IDENTITY_MODE:-}" != standalone ]]; then + echo "refusing terminal identity retirement unless HOSTED_IDENTITY_MODE is hosted-controller or standalone" >&2 exit 2 fi hosted_identity_requester_kubeconfig="${HOSTED_IDENTITY_REQUESTER_KUBECONFIG:-}" diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index 45736497fb..d68661eecb 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -27,10 +27,15 @@ runtime_relevant() { local file="$1" case "${file}" in + # Packaged resources reach the service JAR; other Markdown never reaches an + # image. The native changes job applies the same rule. + *.md) + [[ "${file}" == */src/main/* ]] || return 1 + ;;& build.gradle.kts | settings.gradle.kts | gradle.properties | gradlew | gradlew.bat | .python-version) return 0 ;; - .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) + .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 7d4b38d199..c1b5bf73fa 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -881,6 +881,11 @@ def _expected_gateway_container_env(expected_namespace: str) -> list[dict]: {"name": "SPRING_PROFILES_ACTIVE", "value": "prod"}, {"name": "SPRING_FLYWAY_TABLE", "value": "flyway_schema_history_gateway"}, {"name": "SERVICE_SCHEMA", "value": "gateway"}, + { + "name": "JAVA_TOOL_OPTIONS", + "value": "-XX:TieredStopAtLevel=1 -XX:ReservedCodeCacheSize=64m -Xss512k", + }, + {"name": "MALLOC_ARENA_MAX", "value": "2"}, { "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, @@ -926,7 +931,13 @@ def _expected_gateway_container_env(expected_namespace: str) -> list[dict]: def _validate_gateway_container_environment(container: dict, expected_namespace: str) -> None: - if container.get("env") != _expected_gateway_container_env(expected_namespace): + expected = _expected_gateway_container_env(expected_namespace) + # The default-branch validator can receive a supported merge base whose + # Gateway chart predates the two JVM footprint settings. + without_footprint_tuning = [ + entry for entry in expected if entry["name"] not in {"JAVA_TOOL_OPTIONS", "MALLOC_ARENA_MAX"} + ] + if container.get("env") not in (expected, without_footprint_tuning): fail("Deployment/spring-cloud-gateway has an unsafe container env") if container.get("envFrom") != EXPECTED_GATEWAY_ENV_FROM: fail("Deployment/spring-cloud-gateway has an unsafe envFrom contract") @@ -2028,8 +2039,8 @@ def validate_metadata( fail("PR number must be a positive canonical decimal string") normalized_pr_number = int(pr_number) event = metadata.get("event") - if event not in {"pull_request_target", "repository_dispatch"}: - fail("metadata event must be pull_request_target or repository_dispatch") + if event not in {"pull_request", "repository_dispatch"}: + fail("metadata event must be pull_request or repository_dispatch") if event == "repository_dispatch" and metadata.get("action") != "deploy": fail("repository_dispatch render metadata action must be deploy") expected = { diff --git a/dev-tools/hosted/preview/wait-for-base-images.sh b/dev-tools/hosted/preview/wait-for-base-images.sh index 046e9f756f..cca6a7188d 100644 --- a/dev-tools/hosted/preview/wait-for-base-images.sh +++ b/dev-tools/hosted/preview/wait-for-base-images.sh @@ -12,60 +12,30 @@ if [[ ! "$base_sha" =~ ^[0-9A-Fa-f]{40}$ ]]; then exit 1 fi -workflow_file=".github/workflows/runtime-images.yml" -if [[ ! -f "$workflow_file" ]]; then - echo "required runtime-image workflow is missing: $workflow_file" >&2 +inventory_file="$(dirname -- "${BASH_SOURCE[0]}")/../shared/protected-runtime-image-registry.sh" +if [[ ! -r "$inventory_file" ]]; then + echo "required runtime-image service inventory is missing: $inventory_file" >&2 exit 1 fi -mapfile -t services < <( - python3 - "$workflow_file" <<'PY' -import sys -from pathlib import Path - -import yaml - -workflow_path = Path(sys.argv[1]) -try: - workflow = yaml.safe_load(workflow_path.read_text(encoding="utf-8")) -except (OSError, yaml.YAMLError) as exc: - print(f"unable to parse runtime-image workflow {workflow_path}: {exc}", file=sys.stderr) - raise SystemExit(1) - -if not isinstance(workflow, dict): - print(f"runtime-image workflow must be a YAML mapping: {workflow_path}", file=sys.stderr) - raise SystemExit(1) -jobs = workflow.get("jobs") -runtime_build = jobs.get("build-runtime-images") if isinstance(jobs, dict) else None -strategy = runtime_build.get("strategy") if isinstance(runtime_build, dict) else None -matrix = strategy.get("matrix") if isinstance(strategy, dict) else None -services = matrix.get("service") if isinstance(matrix, dict) else None -if not isinstance(services, list) or not services or any(not isinstance(service, str) for service in services): - print( - "required runtime-image service matrix must be a non-empty list of strings: " - f"{workflow_path}", - file=sys.stderr, - ) - raise SystemExit(1) - -for service in services: - print(service) -PY -) - +# The protected build matrix lists only missing images. Reuse the complete +# inventory that branch selection, digest pinning, and promotion use. +declare -a services=() +# shellcheck source=dev-tools/hosted/shared/protected-runtime-image-registry.sh +source "$inventory_file" if ((${#services[@]} == 0)); then - echo "required runtime-image service matrix is missing: $workflow_file" >&2 + echo "required runtime-image service inventory is empty: $inventory_file" >&2 exit 1 fi declare -A seen_services=() for service in "${services[@]}"; do if [[ ! "$service" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then - echo "invalid runtime-image service in $workflow_file: $service" >&2 + echo "invalid runtime-image service in $inventory_file: $service" >&2 exit 1 fi if [[ -n "${seen_services[$service]:-}" ]]; then - echo "duplicate runtime-image service in $workflow_file: $service" >&2 + echo "duplicate runtime-image service in $inventory_file: $service" >&2 exit 1 fi seen_services["$service"]=1 diff --git a/dev-tools/hosted/shared/delete-hosted-namespace.sh b/dev-tools/hosted/shared/delete-hosted-namespace.sh index c987179d06..6669e4c485 100644 --- a/dev-tools/hosted/shared/delete-hosted-namespace.sh +++ b/dev-tools/hosted/shared/delete-hosted-namespace.sh @@ -10,6 +10,12 @@ namespace="$1" release_name="$2" wait_seconds="${PREVIEW_NAMESPACE_DELETE_TIMEOUT_SECONDS:-180}" expected_namespace_uid="${PREVIEW_EXPECTED_NAMESPACE_UID:-}" +require_cleanup_proof="${PREVIEW_REQUIRE_CLEANUP_PROOF:-false}" +# Any value other than exactly true or false would silently disable proof mode. +if [[ "$require_cleanup_proof" != true && "$require_cleanup_proof" != false ]]; then + echo "PREVIEW_REQUIRE_CLEANUP_PROOF must be true or false" >&2 + exit 2 +fi if [[ "$namespace" == "dev" ]]; then if [[ "$release_name" != "dev" ]]; then @@ -38,6 +44,12 @@ if [[ -n "$expected_namespace_uid" ]] && exit 2 fi +if [[ "$require_cleanup_proof" == true ]] && + [[ "$namespace" == dev || -z "$expected_namespace_uid" ]]; then + echo "cleanup proof deletion requires an exact preview namespace UID" >&2 + exit 2 +fi + if ! namespace_json="$( kubectl get namespace "$namespace" --ignore-not-found -o json )"; then @@ -83,12 +95,24 @@ if [[ -n "$expected_namespace_uid" && "$namespace_uid" != "$expected_namespace_u echo "hosted namespace ${namespace} UID changed before deletion" >&2 exit 1 fi +if [[ "$require_cleanup_proof" == true ]] && + ! jq -e '.metadata.annotations["firemud.dev/cleanup-proof"] == "true"' <<<"$namespace_json" >/dev/null; then + echo "hosted namespace ${namespace} cleanup-proof marker is missing at deletion" >&2 + exit 1 +fi delete_uid="${expected_namespace_uid:-$namespace_uid}" +# A proof deletion also fences the marker read: any later update fails the delete. +delete_resource_version="" +if [[ "$require_cleanup_proof" == true ]] && + ! delete_resource_version="$(jq -er '.metadata.resourceVersion | select(type == "string" and length > 0)' <<<"$namespace_json")"; then + echo "hosted namespace ${namespace} has no resourceVersion for proof deletion" >&2 + exit 1 +fi delete_options="$( jq -cn \ - --arg uid "$delete_uid" \ - '{apiVersion:"v1",kind:"DeleteOptions",preconditions:{uid:$uid}}' + --arg uid "$delete_uid" --arg resource_version "$delete_resource_version" \ + '{apiVersion:"v1",kind:"DeleteOptions",preconditions:({uid:$uid} + (if $resource_version == "" then {} else {resourceVersion:$resource_version} end))}' )" delete_status=0 printf '%s\n' "$delete_options" | diff --git a/dev-tools/hosted/shared/protected-runtime-image-registry.sh b/dev-tools/hosted/shared/protected-runtime-image-registry.sh new file mode 100644 index 0000000000..b13ab98979 --- /dev/null +++ b/dev-tools/hosted/shared/protected-runtime-image-registry.sh @@ -0,0 +1,248 @@ +#!/usr/bin/env bash +# Sourced by trusted branch runtime selection, digest pinning, promotion, and +# the PR merge image publication checks. + +services=( + account-service + automation-scripting-service + entity-management-service + game-design-service + game-logic-service + game-session-service + logging-admin-service + social-groups-service + spring-cloud-gateway + tcp-proxy-service + world-management-service +) + +declare -A registry_tokens=() +registry_manifest_state() { + local image="$1" output_name="$2" + local image_path="${image#ghcr.io/}" + local repository_path="${image_path%:*}" + local tag="${image_path##*:}" + local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" + local registry_token="${registry_tokens[$repository_path]:-}" + local status readable_repository + + [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { + echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 + return 1 + } + if [[ -z "$registry_token" ]]; then + if ! registry_token="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ + --get \ + --data-urlencode 'service=ghcr.io' \ + --data-urlencode "scope=repository:${repository_path}:pull" \ + --header 'Accept: application/json' \ + 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then + echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 + return 1 + fi + registry_tokens["$repository_path"]="$registry_token" + fi + # `docker manifest inspect "$image"` conflates a 404 with auth, + # registry, and network failures, so it is never an absence check. + if ! status="$(curl --silent --show-error --location --head \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ + --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then + echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 + return 1 + fi + case "$status" in + 200) printf -v "$output_name" '%s' existing ;; + 404) + # A tag response alone cannot prove this token has pull access to the package. + if ! readable_repository="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/json' \ + "https://ghcr.io/v2/${repository_path}/tags/list?n=1")" || + ! jq -e --arg repository "$repository_path" --arg tag "$tag" ' + type == "object" and .name == $repository + and (.tags == null or (.tags | type == "array" + and all(.[]; type == "string" and . != $tag))) + and has("tags") + ' <<<"$readable_repository" >/dev/null; then + echo "Unable to establish pull access and consistent tag evidence for $image; refusing to infer absence." >&2 + return 1 + fi + printf -v "$output_name" '%s' missing + ;; + 401) + # Drop the rejected bearer so the next call exchanges a fresh one. + unset 'registry_tokens[$repository_path]' + echo "GHCR rejected the cached pull bearer for $image; refusing to infer absence." >&2 + return 1 + ;; + *) + echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 + return 1 + ;; + esac +} + +registry_digest() { + local image="$1" + local inspect_output inspect_status + local line digest='' + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" + fi + while IFS= read -r line; do + [[ "$line" == Digest:* ]] || continue + if [[ -n "$digest" || ! "$line" =~ ^Digest:[[:space:]]+(sha256:[0-9a-f]{64})[[:space:]]*$ ]]; then + echo "Registry manifest for $image has malformed or ambiguous digest metadata." >&2 + return 1 + fi + digest="${BASH_REMATCH[1]}" + done <<<"$inspect_output" + [[ -n "$digest" ]] || { + echo "Registry manifest for $image has no exact digest." >&2 + return 1 + } + printf '%s\n' "$digest" +} + +assert_current_branch_head() { + local current_sha + current_sha="$(gh api \ + "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ + --jq '.object.sha')" + [[ "$current_sha" == "$HEAD_SHA" ]] || { + echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 + exit 1 + } +} + +select_existing_fixed_digests() { + local service image state digest manifest missing + local -a entries=() missing_services=() + for service in "${services[@]}"; do + image="ghcr.io/benhook1013/${service}:${HEAD_SHA}" + registry_manifest_state "$image" state || return + if [[ "$state" == missing ]]; then + missing_services+=("$service") + continue + fi + digest="$(registry_digest "$image")" || return + entries+=("$service=$digest") + done + manifest="$(encode_digest_inventory "${entries[@]}")" || return + validate_digest_inventory "$manifest" false || return + missing="$(printf '%s\n' "${missing_services[@]}" | jq -nRc '[inputs | select(length > 0)]')" || return + printf 'fixed_digests=%s\nmissing_services=%s\n' "$manifest" "$missing" >> "$GITHUB_OUTPUT" +} + +encode_digest_inventory() { + printf '%s\n' "$@" | jq -nRcS '[inputs | select(length > 0) | split("=") | {key:.[0],value:.[1]}] | from_entries' +} + +validate_digest_inventory() { + local manifest="$1" complete="${2:-true}" inventory + inventory="$(printf '%s\n' "${services[@]}" | jq -nRc '[inputs] | sort')" || return + jq -e --argjson services "$inventory" --argjson complete "$complete" ' + type == "object" and + (if $complete then keys == $services else (keys - $services | length) == 0 end) and + all(.[]; type == "string" and test("^sha256:[0-9a-f]{64}$")) + ' <<<"$manifest" >/dev/null +} + +pin_runtime_digests() { + local fixed_manifest="${FIXED_RUNTIME_DIGESTS:-}" manifest service digest + local -a entries=() + validate_digest_inventory "$fixed_manifest" false || return + for service in "${services[@]}"; do + digest="$(jq -r --arg service "$service" '.[$service] // empty' <<<"$fixed_manifest")" || return + if [[ -z "$digest" ]]; then + [[ "$CANDIDATE_TAG" =~ ^candidate-[0-9a-f]{40}-[0-9]+-[0-9]+$ ]] || return 1 + digest="$(registry_digest "ghcr.io/benhook1013/$service:$CANDIDATE_TAG")" || return + fi + entries+=("$service=$digest") + done + manifest="$(encode_digest_inventory "${entries[@]}")" || return + validate_digest_inventory "$manifest" || return + printf 'runtime_digests=%s\n' "$manifest" >> "$GITHUB_OUTPUT" +} + +# Check the entire smoke-qualified set and every existing fixed tag before +# writing an alias. A reused fixed tag must stay present and unchanged. +declare -A smoke_sources=() retained_fixed=() +preflight_fixed_digest_set() { + local manifest="${RUNTIME_DIGESTS:-}" fixed_manifest="${FIXED_RUNTIME_DIGESTS:-}" + local service repository fixed state expected actual retained_digest + validate_digest_inventory "$manifest" || return + validate_digest_inventory "$fixed_manifest" false || return + for service in "${services[@]}"; do + repository="ghcr.io/benhook1013/$service" + fixed="$repository:$HEAD_SHA" + expected="$(jq -er --arg service "$service" '.[$service]' <<<"$manifest")" || return + retained_digest="$(jq -r --arg service "$service" '.[$service] // empty' <<<"$fixed_manifest")" || return + if [[ -n "$retained_digest" && "$retained_digest" != "$expected" ]]; then + echo "Retained fixed runtime digest for $service differs from the tested digest." >&2 + return 1 + fi + # The promotion workflow retains this per-service fence through its final tag check. + # shellcheck disable=SC2034 + retained_fixed[$service]="$retained_digest" + smoke_sources[$service]="$repository@$expected" + actual="$(registry_digest "${smoke_sources[$service]}")" || return + if [[ "$actual" != "$expected" ]]; then + echo "Registry source for $service does not match tested digest $expected (got $actual)." >&2 + return 1 + fi + registry_manifest_state "$fixed" state || return + if [[ "$state" == missing ]]; then + if [[ -n "$retained_digest" ]]; then + echo "Fixed runtime tag $fixed disappeared after smoke qualification." >&2 + return 1 + fi + continue + fi + actual="$(registry_digest "$fixed")" || return + if [[ "$actual" != "$expected" ]]; then + echo "Refusing to overwrite fixed runtime tag $fixed: existing digest $actual differs from tested digest $expected." >&2 + return 1 + fi + # A fixed tag first witnessed here must not be recreated during promotion. + # shellcheck disable=SC2034 + retained_fixed[$service]="$actual" + done +} + +# Classify the pr-merge- tags (services plus backup-verifier, which the PR +# publisher also pushes) as complete, partial or none in one sweep. +pr_merge_publication_state() { + # Locals must not shadow the caller's output variable name. + local merge_sha="$1" output_name="$2" image tag_state present=0 + local -a images=("${services[@]}" backup-verifier) missing=() + [[ "$merge_sha" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR merge SHA must be 40 lowercase hexadecimal characters." >&2 + return 1 + } + for image in "${images[@]}"; do + registry_manifest_state "ghcr.io/benhook1013/${image}:pr-merge-${merge_sha}" tag_state || return + if [[ "$tag_state" == existing ]]; then + present=$((present + 1)) + else + missing+=("$image") + fi + done + if (( present == ${#images[@]} )); then + printf -v "$output_name" '%s' complete + elif (( present == 0 )); then + printf -v "$output_name" '%s' none + else + echo "Missing pr-merge-${merge_sha} images: ${missing[*]}" >&2 + printf -v "$output_name" '%s' partial + fi +} diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 7c84d3bb13..abd633ea51 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -1,417 +1,70 @@ #!/usr/bin/env bash +# Wait until every runtime image tag exists in GHCR, or the timeout passes. +# Published tags are write-once, so existence is the only proof; producer runs +# are not tracked, because a newer build or a rerun can still publish the set. set -euo pipefail if [[ $# -ne 1 && $# -ne 3 ]]; then - echo "usage: $0 | $0 " >&2 + echo "usage: $0 | $0 " >&2 exit 1 fi +for value in "$@"; do + if [[ ! "$value" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "arguments must be 40-character hexadecimal SHAs" >&2 + exit 1 + fi +done if [[ -z "${GH_TOKEN:-}" || -z "${GITHUB_REPOSITORY:-}" ]]; then echo "GH_TOKEN and GITHUB_REPOSITORY are required" >&2 exit 1 fi +export GHCR_USERNAME="${GHCR_USERNAME:-${PREVIEW_GHCR_USERNAME:-}}" +export GHCR_TOKEN="${GHCR_TOKEN:-${PREVIEW_GHCR_TOKEN:-}}" +# Missing credentials cannot succeed on a retry. +if [[ -z "$GHCR_USERNAME" || -z "$GHCR_TOKEN" ]]; then + echo "GHCR_USERNAME and GHCR_TOKEN (or PREVIEW_GHCR_*) are required" >&2 + exit 1 +fi + +# shellcheck source=dev-tools/hosted/shared/protected-runtime-image-registry.sh +source "$(dirname -- "${BASH_SOURCE[0]}")/protected-runtime-image-registry.sh" if [[ $# -eq 1 ]]; then - wait_mode=branch - branch_name=develop - image_tag="$1" - merge_sha="" - base_sha="" - head_sha="$1" + # dev-demo waits for the protected develop build's immutable SHA tags. + image_tag="${1,,}" + images=("${services[@]}") else - wait_mode=pull-request - branch_name="" - merge_sha="$1" - base_sha="$2" - head_sha="$3" - for value_name in merge_sha base_sha head_sha; do - value="${!value_name}" - if [[ ! "$value" =~ ^[0-9a-fA-F]{40}$ ]]; then - echo "${value_name} must be exactly 40 hexadecimal characters" >&2 - exit 1 - fi - printf -v "$value_name" '%s' "${value,,}" - done - image_tag="pr-merge-${merge_sha}" + # The PR publisher pushes backup-verifier after the services. + image_tag="pr-merge-${1,,}" + images=("${services[@]}" backup-verifier) fi + timeout_seconds="${HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS:-${PREVIEW_IMAGE_WAIT_TIMEOUT_SECONDS:-1800}}" sleep_seconds="${HOSTED_IMAGE_WAIT_SLEEP_SECONDS:-${PREVIEW_IMAGE_WAIT_SLEEP_SECONDS:-10}}" -missing_workflow_timeout_seconds="${HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS:-${PREVIEW_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS:-180}}" -publisher_timeout_seconds="${HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS:-${timeout_seconds}}" -start_epoch="${SECONDS}" deadline=$((SECONDS + timeout_seconds)) -fetch_workflow_runs() { - local endpoint="$1" - local wait_context="$2" - local payload - - if ! payload="$(gh api --paginate --slurp "${endpoint}")"; then - printf 'GitHub API poll failed while %s; retrying within the existing wait deadline.\n' \ - "${wait_context}" >&2 - return 1 - fi - - printf '%s' "${payload}" -} - -read_run_state() { - python3 -c ' -import json -import sys -import re -from datetime import datetime, timezone - -wait_mode, image_tag, merge_sha, base_sha, head_sha = sys.argv[1:] -try: - payload = json.load(sys.stdin) -except json.JSONDecodeError: - raise SystemExit(1) -pages = payload if isinstance(payload, list) else [payload] -if not pages or any( - not isinstance(page, dict) or not isinstance(page.get("workflow_runs"), list) - for page in pages -): - raise SystemExit(1) -workflow_runs = [ - run - for page in pages - for run in page["workflow_runs"] -] -if any(not isinstance(run, dict) for run in workflow_runs): - raise SystemExit(1) - -def is_matching_run(run): - if wait_mode == "branch": - display_title = run.get("display_title", "") - tokens = display_title.split() - return ( - run.get("event") == "workflow_run" - and display_title.startswith("Build Runtime Images trusted-branch ") - and "branch-develop" in tokens - and f"sha-{head_sha}" in tokens - and len(tokens) == 6 - ) - - # A base refresh is dispatched as the typed pr-runtime-base-refresh event; - # the workflow-run API exposes its source only as repository_dispatch. - if run.get("event") not in {"pull_request", "repository_dispatch"}: - return False - display_title = run.get("display_title", "") - tokens = display_title.split() - return ( - display_title.startswith("Build Runtime Images secure-pr-artifact ") - and f"base-{base_sha}" in tokens - and f"head-{head_sha}" in tokens - and f"merge-{merge_sha}" in tokens - and display_title.endswith(" mode-required") - ) - -matching_runs = [run for run in workflow_runs if is_matching_run(run)] -if not matching_runs: - print("missing") - raise SystemExit(0) - -run = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True)[0] -# Every tab-delimited field must be nonempty so Bash IFS cannot shift positions. -def clean_field(value): - return isinstance(value, str) and bool(value) and not any(character.isspace() or ord(character) < 32 or ord(character) == 127 for character in value) - -run_id = run.get("id") -if type(run_id) is not int or run_id <= 0: - raise SystemExit(1) -if not all(clean_field(run.get(field)) for field in ("status", "html_url", "event")): - raise SystemExit(1) -conclusion = run.get("conclusion") -if conclusion is None or conclusion == "": - if run["status"] == "completed": - raise SystemExit(1) - conclusion = "pending" -elif not clean_field(conclusion): - raise SystemExit(1) -created_at = run.get("created_at") -if not isinstance(created_at, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", created_at): - raise SystemExit(1) -try: - created = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) -except ValueError: - raise SystemExit(1) -if created > datetime.now(timezone.utc): - raise SystemExit(1) -print( - "found\t{}\t{}\t{}\t{}\t{}\t{}".format( - run_id, - run["status"], - conclusion, - run["html_url"], - run["event"], - created_at, - ) -) -' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" -} - -fetch_publisher_runs() { - python3 - "${GITHUB_REPOSITORY}" "$1" "$2" "$3" <<'PY_PUBLISHERS' -import json -import re -import subprocess -import sys -from datetime import datetime, timezone - -repository, event, lower_text, upper_text = sys.argv[1:] - -def unavailable(reason): - print(f"Publisher coverage unavailable: {reason}.", file=sys.stderr) - raise SystemExit(1) - -def timestamp(value): - if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", value): - unavailable("creation-window timestamp is malformed") - try: - return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) - except ValueError: - unavailable("creation-window timestamp is invalid") - -lower, upper = timestamp(lower_text), timestamp(upper_text) -if lower > upper or event not in {"workflow_run", "repository_dispatch"}: - unavailable("creation window or event is invalid") -endpoint = f"repos/{repository}/actions/workflows/publish-pr-runtime-images.yml/runs?event={event}&created={lower_text}..{upper_text}&per_page=100" -records, seen, total = [], set(), None -page_number = 1 -while True: - result = subprocess.run(["gh", "api", f"{endpoint}&page={page_number}"], capture_output=True, text=True) - if result.returncode: - unavailable("exact-window GitHub API lookup failed") - try: - page = json.loads(result.stdout) - except json.JSONDecodeError: - unavailable("exact-window API response is malformed") - if not isinstance(page, dict) or type(page.get("total_count")) is not int or not isinstance(page.get("workflow_runs"), list): - unavailable("exact-window API envelope is malformed") - count = page["total_count"] - if count < 0 or count > 1000: - unavailable("exact-window run count exceeds the 1000-record filtered API ceiling") - if total is None: - total = count - elif total != count: - unavailable("exact-window page totals changed") - runs = page["workflow_runs"] - if len(runs) != min(100, total - len(records)): - unavailable("exact-window page coverage is incomplete") - for run in runs: - if not isinstance(run, dict) or type(run.get("id")) is not int or run["id"] <= 0 or run["id"] in seen or run.get("event") != event: - unavailable("exact-window run identity or event is malformed") - if not lower <= timestamp(run.get("created_at")) <= upper: - unavailable("run creation time is outside the exact window") - seen.add(run["id"]) - records.append(run) - if len(records) == total: - break - page_number += 1 -print(json.dumps({"workflow_runs": records})) -PY_PUBLISHERS -} - -read_publisher_state() { - python3 -c ' -import json -import re -import sys - -wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id = sys.argv[1:] -if not re.fullmatch(r"[1-9][0-9]*", source_run_id): - raise SystemExit(1) -try: - payload = json.load(sys.stdin) -except json.JSONDecodeError: - raise SystemExit(1) -pages = payload if isinstance(payload, list) else [payload] -if not pages or any( - not isinstance(page, dict) or not isinstance(page.get("workflow_runs"), list) - for page in pages -): - raise SystemExit(1) -workflow_runs = [ - run - for page in pages - for run in page["workflow_runs"] -] -if any(not isinstance(run, dict) for run in workflow_runs): - raise SystemExit(1) -if wait_mode == "pull-request": - matching_runs = [ - run for run in workflow_runs - if (run.get("event") == "repository_dispatch" and - run.get("display_title") == f"Publish PR Runtime Images source-run-{source_run_id}") - or (run.get("event") == "workflow_run" and - (tokens := run.get("display_title", "").split())[:8] == [ - "Publish", "PR", "Runtime", "Images", "Build", "Runtime", "Images", - "secure-pr-artifact", - ] - and len(tokens) == 13 - and re.fullmatch(r"pr-[1-9][0-9]{0,50}", tokens[8]) - and tokens[9] == f"base-{base_sha}" - and tokens[10] == f"head-{head_sha}" - and tokens[11] == f"merge-{merge_sha}" - and tokens[12] == "mode-required") - ] -else: - matching_runs = [] -if not matching_runs: - print("missing") - raise SystemExit(0) - -run = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True)[0] -print( - "found\t{}\t{}\t{}\t{}".format( - run.get("id", ""), - run.get("status", ""), - run.get("conclusion", ""), - run.get("html_url", ""), - ) -) -' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$1" -} - -wait_for_pr_publisher() { - local source_run_id="$1" - local source_created_at="$2" - local coverage_unavailable=false - local publisher_start_epoch="${SECONDS}" - local publisher_deadline=$((SECONDS + publisher_timeout_seconds)) - while (( SECONDS < publisher_deadline )); do - local publisher_payload publisher_state event_payload publisher_event fetch_failed - publisher_payload="" - fetch_failed=false - local poll_upper_bound - poll_upper_bound="$(date -u +%Y-%m-%dT%H:%M:%SZ)" - # Preserve complete discovery within the verified source creation window. - for publisher_event in workflow_run repository_dispatch; do - if ! event_payload="$( - fetch_publisher_runs "${publisher_event}" "${source_created_at}" "${poll_upper_bound}" - )"; then - fetch_failed=true - break - fi - publisher_payload+="${publisher_payload:+,}${event_payload}" - done - if [[ "${fetch_failed}" == "true" ]]; then - coverage_unavailable=true - sleep "${sleep_seconds}" - continue - fi - coverage_unavailable=false - publisher_payload="[${publisher_payload}]" - if ! publisher_state="$(read_publisher_state "${source_run_id}" <<<"${publisher_payload}")"; then - printf 'GitHub API response was empty or invalid while waiting for the trusted PR image publisher; retrying.\n' >&2 - sleep "${sleep_seconds}" - continue - fi - - local state run_id run_status run_conclusion run_url - IFS=$'\t' read -r state run_id run_status run_conclusion run_url <<<"${publisher_state}" - - if [[ "${state}" == "missing" ]]; then - local elapsed_seconds=$((SECONDS - publisher_start_epoch)) - if (( elapsed_seconds >= missing_workflow_timeout_seconds )); then - printf 'No trusted PR image publisher appeared for %s after %ss.\n' \ - "${image_tag}" "${elapsed_seconds}" >&2 - exit 1 - fi - printf 'Waiting for trusted PR image publisher for %s after %ss.\n' \ - "${image_tag}" "${elapsed_seconds}" - sleep "${sleep_seconds}" - continue - fi - - if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then - printf 'Trusted PR image publisher %s succeeded for %s.\n' "${run_id}" "${image_tag}" - return 0 - fi - if [[ "${run_status}" == "completed" ]]; then - printf 'Trusted PR image publisher %s completed with %s for %s.\n' \ - "${run_id}" "${run_conclusion}" "${image_tag}" >&2 - [[ -z "${run_url}" ]] || printf 'Workflow URL: %s\n' "${run_url}" >&2 - exit 1 - fi - - printf 'Waiting for trusted PR image publisher %s for %s. status=%s conclusion=%s\n' \ - "${run_id}" "${image_tag}" "${run_status}" "${run_conclusion:-pending}" - sleep "${sleep_seconds}" +# Returns 0 when every tag exists, 1 when one is absent, 2 when GHCR is unreadable. +all_images_exist() { + local image state + for image in "${images[@]}"; do + registry_manifest_state "ghcr.io/benhook1013/${image}:${image_tag}" state || return 2 + [[ "$state" == existing ]] || return 1 done - - if [[ "${coverage_unavailable}" == "true" ]]; then - printf 'Publisher coverage unavailable at the wait deadline for %s.\n' "${image_tag}" >&2 - exit 1 - fi - printf 'Timed out waiting for trusted PR image publisher for %s.\n' "${image_tag}" >&2 - exit 1 } -while (( SECONDS < deadline )); do - if ! workflow_payload="$( - fetch_workflow_runs \ - "repos/${GITHUB_REPOSITORY}/actions/workflows/runtime-images.yml/runs?per_page=100" \ - "waiting for the runtime-images workflow" - )"; then - sleep "${sleep_seconds}" - continue - fi - if ! run_state="$(read_run_state <<<"${workflow_payload}")"; then - printf 'GitHub API response was empty or invalid while waiting for the runtime-images workflow; retrying.\n' >&2 - sleep "${sleep_seconds}" - continue - fi - - IFS=$'\t' read -r state run_id run_status run_conclusion run_url _run_event run_created_at <<<"${run_state}" - - if [[ "${state}" == "missing" ]]; then - elapsed_seconds=$((SECONDS - start_epoch)) - if (( elapsed_seconds >= missing_workflow_timeout_seconds )); then - if [[ "${wait_mode}" == "branch" ]]; then - printf 'No trusted branch runtime-image publication appeared for branch %s and exact head SHA %s after %ss.\n' \ - "${branch_name}" "${head_sha}" "${elapsed_seconds}" >&2 - else - printf 'No runtime-images workflow appeared for %s after %ss.\n' \ - "${image_tag}" "${elapsed_seconds}" >&2 - printf 'The PR image source or trusted current-base refresh did not appear for the exact merge SHA.\n' >&2 - fi - exit 1 - fi - - printf 'Waiting for runtime-images workflow for %s after %ss. Matching run not visible yet.\n' \ - "${image_tag}" "${elapsed_seconds}" - sleep "${sleep_seconds}" - continue - fi - - if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then - printf 'Matching runtime-images workflow %s succeeded for %s after %ss.\n' \ - "${run_id}" "${image_tag}" "$((SECONDS - start_epoch))" - if [[ "${wait_mode}" == "pull-request" ]]; then - wait_for_pr_publisher "${run_id}" "${run_created_at}" - fi +while :; do + status=0 + all_images_exist || status=$? + if (( status == 0 )); then + echo "All runtime images for ${image_tag} exist in GHCR." exit 0 fi - - if [[ "${run_status}" == "completed" ]]; then - printf 'Matching runtime-images workflow %s completed with %s for %s.\n' \ - "${run_id}" "${run_conclusion}" "${image_tag}" >&2 - if [[ -n "${run_url}" ]]; then - printf 'Workflow URL: %s\n' "${run_url}" >&2 - fi + (( status == 1 )) || echo "GHCR lookup failed; retrying." >&2 + remaining=$((deadline - SECONDS)) + if (( remaining <= 0 )); then + echo "::error title=Runtime images unavailable::Timed out after ${timeout_seconds}s waiting for ${image_tag} in GHCR." >&2 exit 1 fi - - printf 'Waiting for runtime-images workflow %s for %s after %ss. status=%s conclusion=%s\n' \ - "${run_id}" "${image_tag}" "$((SECONDS - start_epoch))" "${run_status}" "${run_conclusion:-pending}" - if [[ -n "${run_url}" ]]; then - printf 'Workflow URL: %s\n' "${run_url}" - fi - sleep "${sleep_seconds}" + sleep "$(( sleep_seconds < remaining ? sleep_seconds : remaining ))" done - -printf 'Timed out waiting for runtime-images workflow for %s after %ss.\n' \ - "${image_tag}" "$((SECONDS - start_epoch))" >&2 -exit 1 diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 37a750bcab..99c747dbef 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1014,7 +1014,8 @@ require_contains( require_contains( "design/architecture/system-architecture-cicd.md", [ - "builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token", + "builds pull-request images locally and runs held-admission qualification when required by runtime scope, without a registry-write token", + "A build-only archive carries no held-admission smoke proof.", "Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission.", "The diagnostic exception below provides no passing `PLAY` or `LOOK` proof.", "image export and upload must be skipped", @@ -1028,7 +1029,7 @@ require_contains( require_contains( "design/architecture/infrastructure/deployment-environments.md", [ - "builds and smoke-tests PR merge images without registry credentials", + "builds PR merge images locally and runs held-admission smoke when required by runtime scope, without registry credentials", "verifies their exact base/head/merge provenance and publishes immutable", ], ) diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 625bba7f65..7a8ed87fb0 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -149,6 +149,7 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput [[{filename: "dev-tools/validation/another_test.py", status: "renamed", previous_filename: "dev-tools/validation/test_validate_preview_artifact.py"}], true, true, false, true], [[{filename: "dev-tools/validation/gradle-run-supervisor.py"}], false], + [[{filename: "services/account-service/src/main/java/Example.java"}], false], [[{filename: "services/recovery-controller-service/src/main/java/Example.java"}], false], [[{filename: "README.md", status: "renamed", previous_filename: "services/new-service/Main.java"}], false], [[{filename: "services/new-service/README.md"}], false], @@ -584,7 +585,6 @@ REMAINING_FULL_RUN_COMMANDS = ( 'bash ./dev-tools/tests/gradle-proof-tooling-contract.sh', 'bash ./dev-tools/tests/testcontainers-disabled-contract.sh', 'bash ./dev-tools/tests/pr-retarget-workflow-contract.sh', - 'bash ./dev-tools/tests/static-analysis-summary-contract.sh', 'bash ./dev-tools/tests/ci-validation-summary-contract.sh', 'bash ./dev-tools/tests/security-summary-contract.sh', 'bash ./dev-tools/tests/pr-runtime-image-publication-contract.sh', @@ -599,6 +599,9 @@ REMAINING_FULL_RUN_COMMANDS = ( 'bash ./dev-tools/tests/hosted-gateway-bridge-contract.sh', 'bash ./dev-tools/tests/postgres-runtime-upgrade-contract.sh', 'bash ./dev-tools/tests/preview-runner-isolation-contract.sh', + 'bash ./dev-tools/tests/privileged-workflow-policy-contract.sh', + 'bash ./dev-tools/tests/required-gate-names-contract.sh', + 'bash ./dev-tools/tests/play-waiver-guard-contract.sh', 'bash ./dev-tools/tests/preview-standalone-transport-certificates-contract.sh', 'bash ./dev-tools/tests/preview-ca-recovery-contract.sh', 'bash ./dev-tools/tests/trust-bootstrap-rbac-contract.sh', @@ -621,6 +624,7 @@ REMAINING_FULL_RUN_COMMANDS = ( 'bash ./dev-tools/tests/account-workload-namespace-contract.sh', 'bash ./dev-tools/tests/preview-image-tag-contract.sh', 'bash ./dev-tools/tests/preview-merge-image-tag-contract.sh', + 'bash ./dev-tools/tests/wait-for-runtime-images-contract.sh', 'bash ./dev-tools/tests/overlay-preflight-contract.sh', 'bash ./dev-tools/tests/validate-external-credentials-contract.sh', 'bash ./dev-tools/tests/observability-validator-contract.sh', @@ -2288,7 +2292,7 @@ for path_item in ( ): require_list_item( preview, - ("on", "pull_request_target", "paths-ignore"), + ("on", "pull_request", "paths-ignore"), path_item, "preview workflow", ) diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index 8382900889..b21c4bad3f 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -195,6 +195,10 @@ async function noWrites(config, reject = false) { } const metadataSplit = clone(jobs); for (const job of metadataSplit) { job.conclusion = 'skipped'; job.steps = []; } + const metadataGate = metadataSplit.find(job => job.name === 'Validation Gate'); + metadataGate.conclusion = 'success'; + metadataGate.steps = jobs.find(job => job.name === 'Validation Gate').steps.filter( + step => step.name === 'Declare dev tool contract split'); assert.equal((await noWrites({ jobs: metadataSplit })).comments.length, 0); // A later native run publishes first; a delayed older callback may neither rewrite it nor delete it as a duplicate. const newerSource = { ...clone(source), id: 71, run_number: 8 }; diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 09e0c0c18a..437a4e3e9d 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -214,6 +214,17 @@ assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2 assert_output_contains "Connection reset" assert_output_contains "refresh-complete" +new_case netty-reset-conflicting-cache-task +sed '/^- Task /s/:load-testing:compileJava/:account-service:compileJava/' \ + "$TEMP_DIR/netty-reset/gradlew" > "$CASE_DIR/gradlew" +# Match Gradle's literal backtick-delimited task name. +# shellcheck disable=SC2016 +grep -Fq -- '- Task `:account-service:compileJava`' "$CASE_DIR/gradlew" || + fail "conflicting Netty fixture must change the emitted task attribution" +chmod +x "$CASE_DIR/gradlew" +run_case load-testing 1 +assert_no_retry + # Preserve the c515-style pinned missing-artifact recovery path without # claiming the miss is stale: a passing refreshed full check is still required. new_case absent-pinned-artifact @@ -461,6 +472,28 @@ for mutation in auth wrong-origin wrong-artifact truncated-chain extra-coordinat assert_no_retry done +# Gradle 9.9 can wrap compileClasspath Maven Central 429 downloads in the +# JavaCompile.classpath configuration-cache serialization failure. +write_compile_classpath_429_cause() { + cat > "$CASE_DIR/cause.log" <<'LOG' +FAILURE: Build failed with an exception. + +* What went wrong: +Configuration cache state could not be cached: field `classpath` of task `:account-service:compileJava` of type `org.gradle.api.tasks.compile.JavaCompile`: error writing value of type 'org.gradle.api.internal.artifacts.configurations.DefaultResolvableConfiguration' +> Could not resolve all files for configuration ':account-service:compileClasspath'. + > Could not download guava-33.6.0-jre.jar (com.google.guava:guava:33.6.0-android) + > Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/33.6.0-jre/guava-33.6.0-jre.jar'. + > Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/33.6.0-jre/guava-33.6.0-jre.jar'. + > Received status code 429 from server: Too Many Requests + > Could not download spring-data-commons-4.1.0.jar (org.springframework.data:spring-data-commons:4.1.0) + > Could not get resource 'https://repo.maven.apache.org/maven2/org/springframework/data/spring-data-commons/4.1.0/spring-data-commons-4.1.0.jar'. + > Could not GET 'https://repo.maven.apache.org/maven2/org/springframework/data/spring-data-commons/4.1.0/spring-data-commons-4.1.0.jar'. + > Received status code 429 from server: Too Many Requests +* Try: +> Run with --stacktrace option to get the stack trace. +LOG +} + # The processor failure can surface an earlier Spring Boot metadata 429 # while Gradle reports Maven Central as disabled for the Lombok lookup. write_disabled_processor_pom_429_cause() { @@ -480,6 +513,164 @@ write_disabled_processor_pom_429_cause() { LOG } +new_case compile-classpath-429 +write_compile_classpath_429_cause +# shellcheck disable=SC2016 +write_wrapper 'if [[ "$call_count" -eq 1 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; echo refreshed-compile-classpath; exit 0' +run_case account-service 0 +assert_call_count 2 +assert_rate_limit_delay +assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :account-service:check -PfullCheck --profile --info --console=plain" +assert_output_contains "refreshed-compile-classpath" + +# The same-task cache summary entry inside the body is not an extra cause. +new_case compile-classpath-429-task-summary +write_compile_classpath_429_cause +sed -i "/^\* What went wrong:/a 1 problem was found storing the configuration cache.\\n- Task \`:account-service:compileJava\` of type \`org.gradle.api.tasks.compile.JavaCompile\`: error writing value of type 'org.gradle.api.internal.artifacts.configurations.DefaultResolvableConfiguration'" "$CASE_DIR/cause.log" +# shellcheck disable=SC2016 +write_wrapper 'if [[ "$call_count" -eq 1 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; echo refreshed-compile-classpath; exit 0' +run_case account-service 0 +assert_call_count 2 + +for mutation in auth wrong-module unterminated-configuration compile-started unrelated-guava-artifact; do + new_case "compile-classpath-429-$mutation" + write_compile_classpath_429_cause + case "$mutation" in + auth) sed -i '0,/429 from server: Too Many Requests/s//403 from server: Forbidden/' "$CASE_DIR/cause.log" ;; + wrong-module) sed -i 's/:account-service:compileClasspath/:common-platform-core:compileClasspath/' "$CASE_DIR/cause.log" ;; + unterminated-configuration) sed -i "s/:account-service:compileClasspath'\./:account-service:compileClasspathX./" "$CASE_DIR/cause.log" ;; + compile-started) sed -i '1i > Task :account-service:compileJava FAILED' "$CASE_DIR/cause.log" ;; + unrelated-guava-artifact) sed -i 's/guava-33.6.0-jre.jar/guava-33.6.0-unrelated.jar/g' "$CASE_DIR/cause.log" ;; + esac + # shellcheck disable=SC2016 + write_wrapper 'cat "$CASE_DIR/cause.log"; exit 1' + run_case account-service 1 + assert_no_retry +done + +write_compile_classpath_pom_429_cause() { + write_compile_classpath_429_cause + sed -i '/^ > Could not download/,$d; s/:account-service:/:hosted-environment-identity-controller:/g' "$CASE_DIR/cause.log" + cat >> "$CASE_DIR/cause.log" <<'LOG' + > Could not resolve io.javaoperatorsdk:operator-framework-spring-boot-starter:6.8.0. + Required by: + project ':hosted-environment-identity-controller' + > Could not resolve io.javaoperatorsdk:operator-framework-spring-boot-starter:6.8.0. + > Could not get resource 'https://repo.maven.apache.org/maven2/io/javaoperatorsdk/operator-framework-spring-boot-starter/6.8.0/operator-framework-spring-boot-starter-6.8.0.pom'. + > Could not GET 'https://repo.maven.apache.org/maven2/io/javaoperatorsdk/operator-framework-spring-boot-starter/6.8.0/operator-framework-spring-boot-starter-6.8.0.pom'. + > Received status code 429 from server: Too Many Requests + > Could not resolve io.fabric8:kubernetes-client:7.9.0. + Required by: + project ':hosted-environment-identity-controller' + > Could not resolve io.fabric8:kubernetes-client:7.9.0. + > Could not get resource 'https://repo.maven.apache.org/maven2/io/fabric8/kubernetes-client/7.9.0/kubernetes-client-7.9.0.pom'. + > Could not GET 'https://repo.maven.apache.org/maven2/io/fabric8/kubernetes-client/7.9.0/kubernetes-client-7.9.0.pom'. + > Received status code 429 from server: Too Many Requests +* Try: +> Run with --stacktrace option to get the stack trace. +LOG +} + +for requester in direct transitive multiple; do + new_case "compile-classpath-pom-429-$requester" + write_compile_classpath_pom_429_cause + if [[ "$requester" == transitive ]]; then + sed -i '/^ project /s/$/ > org.springframework.boot:spring-boot-dependencies:4.1.1/' "$CASE_DIR/cause.log" + elif [[ "$requester" == multiple ]]; then + sed -i '/^ project /{p;s/$/ > org.springframework.boot:spring-boot-dependencies:4.1.1/;}' "$CASE_DIR/cause.log" + fi + # shellcheck disable=SC2016 + write_wrapper 'if [[ "$call_count" -eq 1 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; exit 0' + run_case hosted-environment-identity-controller 0 + assert_call_count 2 + assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :hosted-environment-identity-controller:check -PfullCheck --profile --info --console=plain" + assert_rate_limit_delay + assert_output_contains "with cached dependency metadata" +done + +for mutation in auth wrong-project wrong-extra-requester wrong-coordinate wrong-origin wrong-pom missing-get malformed-path mixed-cause missing-coordinate compile-started task-started; do + new_case "compile-classpath-pom-429-$mutation" + write_compile_classpath_pom_429_cause + case "$mutation" in + auth) sed -i '0,/429 from server: Too Many Requests/s//403 from server: Forbidden/' "$CASE_DIR/cause.log" ;; + wrong-project) sed -i '/Required by:/{n;s/identity-controller/identity-operator/;}' "$CASE_DIR/cause.log" ;; + wrong-extra-requester) sed -i '/^ project /{p;s/identity-controller/identity-operator/;}' "$CASE_DIR/cause.log" ;; + wrong-coordinate) sed -i '/^ > Could not resolve/s/client:7.9.0/client:7.8.0/' "$CASE_DIR/cause.log" ;; + wrong-origin) sed -i 's/repo.maven.apache.org/repository.invalid/g' "$CASE_DIR/cause.log" ;; + wrong-pom) sed -i '/Could not GET/s/client-7.9.0.pom/client-7.8.0.pom/' "$CASE_DIR/cause.log" ;; + missing-get) sed -i '/Could not GET/d' "$CASE_DIR/cause.log" ;; + malformed-path) sed -i '/^ project /s/$/ > not-a-coordinate/' "$CASE_DIR/cause.log" ;; + mixed-cause) sed -i '/^[*] Try:/i > A second unrelated failure.' "$CASE_DIR/cause.log" ;; + missing-coordinate) sed -i '/^[*] Try:/i > Could not find org.example:missing-lib:1.2.3.' "$CASE_DIR/cause.log" ;; + compile-started) sed -i '1i > Task :hosted-environment-identity-controller:compileJava FAILED' "$CASE_DIR/cause.log" ;; + task-started) sed -i '1i > Task :hosted-environment-identity-controller:processResources' "$CASE_DIR/cause.log" ;; + esac + # shellcheck disable=SC2016 + write_wrapper 'cat "$CASE_DIR/cause.log"; exit 1' + run_case hosted-environment-identity-controller 1 + assert_no_retry +done + +# Maven Central can disable the repository and repeat the same exact failure +# once while Gradle serializes the Gateway compile classpath. +write_disabled_compile_classpath_pom_429_cause() { + cat > "$CASE_DIR/cause.log" <<'LOG' +> Task :buildSrc:compileKotlin FROM-CACHE +> Task :buildSrc:jar +FAILURE: Build failed with an exception. + +* What went wrong: +Configuration cache state could not be cached: field `classpath` of task `:spring-cloud-gateway:compileJava` of type `org.gradle.api.tasks.compile.JavaCompile`: error writing value of type 'org.gradle.api.internal.artifacts.configurations.DefaultResolvableConfiguration' +> Could not resolve all files for configuration ':spring-cloud-gateway:compileClasspath'. + > Could not resolve org.springframework.cloud:spring-cloud-starter-gateway-server-webflux:5.1.0. + Required by: + project ':spring-cloud-gateway' + > Repository MavenRepo is disabled due to earlier error below: + > Could not resolve org.springframework.cloud:spring-cloud-starter-gateway-server-webflux:5.1.0. + > Could not get resource 'https://repo.maven.apache.org/maven2/org/springframework/cloud/spring-cloud-starter-gateway-server-webflux/5.1.0/spring-cloud-starter-gateway-server-webflux-5.1.0.pom'. + > Could not GET 'https://repo.maven.apache.org/maven2/org/springframework/cloud/spring-cloud-starter-gateway-server-webflux/5.1.0/spring-cloud-starter-gateway-server-webflux-5.1.0.pom'. + > Received status code 429 from server: Too Many Requests +> There is 1 more failure with an identical cause. + +* Try: +> Run with --stacktrace option to get the stack trace. +LOG +} + +for retry_status in 0 1; do + new_case "compile-classpath-disabled-repository-429-retry-$retry_status" + write_disabled_compile_classpath_pom_429_cause + # shellcheck disable=SC2016 + write_wrapper 'if [[ "$call_count" -eq 1 || '"$retry_status"' -ne 0 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; exit 0' + run_case spring-cloud-gateway "$retry_status" + assert_call_count 2 + for attempt in 1 2; do + assert_call "$attempt" "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :spring-cloud-gateway:check -PfullCheck --profile --info --console=plain" + done + assert_rate_limit_delay + assert_output_contains "with cached dependency metadata" +done + +for mutation in wrong-module wrong-coordinate wrong-repository wrong-origin wrong-pom missing-duplicate extra-cause auth test-started; do + new_case "compile-classpath-disabled-repository-429-$mutation" + write_disabled_compile_classpath_pom_429_cause + case "$mutation" in + wrong-module) sed -i 's/:spring-cloud-gateway:compileClasspath/:account-service:compileClasspath/' "$CASE_DIR/cause.log" ;; + wrong-coordinate) sed -i '/^ > Could not resolve/s/webflux:5.1.0/webflux:5.1.1/' "$CASE_DIR/cause.log" ;; + wrong-repository) sed -i 's/Repository MavenRepo/Repository OtherRepo/' "$CASE_DIR/cause.log" ;; + wrong-origin) sed -i 's/repo.maven.apache.org/repository.invalid/g' "$CASE_DIR/cause.log" ;; + wrong-pom) sed -i '/Could not GET/s/webflux-5.1.0.pom/webflux-5.1.1.pom/' "$CASE_DIR/cause.log" ;; + missing-duplicate) sed -i '/There is 1 more failure/d' "$CASE_DIR/cause.log" ;; + extra-cause) sed -i '/^[*] Try:/i > A second unrelated failure.' "$CASE_DIR/cause.log" ;; + auth) sed -i 's/429 from server: Too Many Requests/403 from server: Forbidden/' "$CASE_DIR/cause.log" ;; + test-started) sed -i '1i > Task :spring-cloud-gateway:test FAILED' "$CASE_DIR/cause.log" ;; + esac + # shellcheck disable=SC2016 + write_wrapper 'cat "$CASE_DIR/cause.log"; exit 1' + run_case spring-cloud-gateway 1 + assert_no_retry +done + new_case annotation-processor-disabled-repository-429 write_disabled_processor_pom_429_cause # shellcheck disable=SC2016 @@ -1477,6 +1668,82 @@ chmod +x "$CASE_DIR/bin/tee" run_case common-web-support 125 assert_no_retry +prepare_jacoco_case() { + new_case "$1" + mkdir -p "$CASE_DIR/dev-tools/tests" + cp "$ROOT_DIR/dev-tools/tests/jacoco-combined-report-contract.sh" "$CASE_DIR/dev-tools/tests/" +} + +# shellcheck disable=SC2030,SC2031 +run_jacoco_case() ( + cd "$CASE_DIR" + export CASE_DIR + export FAKE_CALL_LOG="$CASE_DIR/calls" + export FAKE_DIAGNOSTIC_CALL_LOG="$CASE_DIR/diagnostic-calls" + export FAKE_LOCK_CALL_LOG="$CASE_DIR/locked-calls" + export FAKE_SLEEP_LOG="$CASE_DIR/sleeps" + export PATH="$CASE_DIR/bin:$PATH" + bash ./dev-tools/tests/jacoco-combined-report-contract.sh > "$CASE_DIR/output" 2>&1 +) + +# An eligible first graph gets one refresh. The real script then checks +# all six graphs, including failures in the graph content itself. +for report_result in valid invalid; do + prepare_jacoco_case "jacoco-task-graph-recovered-$report_result" + write_buildsrc_429_cause + # shellcheck disable=SC2016 + write_wrapper 'if [[ "$call_count" -eq 1 ]]; then + cat "$CASE_DIR/buildsrc-cause.log" + exit 1 +fi +if [[ "${1:-}" == --refresh-dependencies ]]; then shift; fi +case "$1" in + :common-saga:test) echo ":common-saga:test SKIPPED" ;; + :common-saga:check|:common-saga:jacocoTestReport) + printf "%s\n" ":common-saga:integrationTest SKIPPED" ":common-saga:jacocoTestReport SKIPPED" ;; + :account-service:jacocoTestReport|:game-session-service:jacocoTestReport) + echo "$1 SKIPPED" ;; + :world-management-service:jacocoTestReport) + if [[ "${FAKE_JACOCO_REPORT_RESULT:?}" == invalid ]]; then + echo ":world-management-service:classes SKIPPED" + fi + echo "$1 SKIPPED" ;; + *) exit 99 ;; +esac' + status=0 + FAKE_JACOCO_REPORT_RESULT="$report_result" run_jacoco_case || status=$? + if [[ "$report_result" == valid ]]; then + [[ "$status" -eq 0 ]] || fail "JaCoCo graph did not recover from eligible bootstrapping failure" + assert_output_contains "JaCoCo combined and slow-service partition report task graph contracts passed" + else + [[ "$status" -eq 1 ]] || fail "JaCoCo accepted a malformed graph after recovery" + assert_output_contains "World coverage aggregation recompiled classes instead of using measured partition classes." + fi + assert_call_count 7 + assert_call 1 ":common-saga:test -PfullCheck --dry-run --no-configuration-cache" + assert_call 2 "--refresh-dependencies :common-saga:test -PfullCheck --dry-run --no-configuration-cache" + assert_call 3 ":common-saga:check -PfullCheck --dry-run --no-configuration-cache" + assert_call 4 ":common-saga:jacocoTestReport -PfullCheck --dry-run --no-configuration-cache" + aggregate_call=5 + for aggregate in account-service game-session-service world-management-service; do + assert_call "$aggregate_call" ":$aggregate:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=$aggregate -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail" + aggregate_call=$((aggregate_call + 1)) + done + [[ "$(grep -c '^--refresh-dependencies ' "$CASE_DIR/calls")" -eq 1 ]] || fail "JaCoCo repeated dependency refresh" + assert_rate_limit_delay + cmp "$CASE_DIR/calls" "$CASE_DIR/locked-calls" || fail "JaCoCo bypassed the existing locked runner" +done + +# Preserve unrelated Gradle configuration failures without another attempt. +prepare_jacoco_case jacoco-task-graph-semantic-failure +write_wrapper 'printf "%s\n" "FAILURE: Build failed with an exception." "* What went wrong:" "Could not create task :common-saga:test." "* Try:" "BUILD FAILED"; exit 42' +status=0 +run_jacoco_case || status=$? +[[ "$status" -eq 42 ]] || fail "JaCoCo task-graph semantic failure did not retain exit code 42" +assert_no_retry +assert_output_contains "Could not create task :common-saga:test." +cmp "$CASE_DIR/calls" "$CASE_DIR/locked-calls" || fail "JaCoCo bypassed the existing locked runner" + echo "Gradle dependency-recovery contract passed." diff --git a/dev-tools/tests/hosted-gateway-bridge-contract.sh b/dev-tools/tests/hosted-gateway-bridge-contract.sh index 2cc9febab7..baa5639e5e 100644 --- a/dev-tools/tests/hosted-gateway-bridge-contract.sh +++ b/dev-tools/tests/hosted-gateway-bridge-contract.sh @@ -243,6 +243,9 @@ assert_restricted_workload(seed_job, 1000) gateway_deployment = named("Deployment", "spring-cloud-gateway") proxy_deployment = named("Deployment", "tcp-proxy-service") gateway, gateway_env = env_map(gateway_deployment) +if not {"JAVA_TOOL_OPTIONS", "MALLOC_ARENA_MAX"} <= gateway_env.keys(): + raise SystemExit("hosted Gateway render did not include both JVM footprint settings") +validator._validate_gateway_container_environment(gateway, "pr-42") proxy, proxy_env = env_map(proxy_deployment) _, session_env = env_map(named("Deployment", "game-session-service")) if session_env.get("FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED") != "true" or session_env.get("FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT") != "8444": diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index fc45886f37..b06cf6d1e4 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -40,7 +40,7 @@ push_verified_image="$ROOT_DIR/dev-tools/hosted/shared/push-verified-image.sh" runner_label_validator="$ROOT_DIR/dev-tools/tests/preview_runner_labels.py" python3 "$runner_label_validator" --self-test -python3 "$runner_label_validator" "$trusted" "$preview_reconciler" "$janitor" +python3 "$runner_label_validator" "$janitor" python3 - "$preview_reconciler" "$janitor" <<'PY' import sys from pathlib import Path @@ -66,7 +66,7 @@ contains() { } } -contains "$runtime" 'services/**' +contains "$runtime" '"services/",' # shellcheck disable=SC2016 # These assertions intentionally match literal publisher shell. contains "$publisher" 'source_image_id="$(docker image inspect --format' # shellcheck disable=SC2016 # This assertion intentionally matches literal publisher shell. @@ -157,15 +157,17 @@ for job in workflow["jobs"].values(): assert_immutable_action_pin(step, action) pull_request = workflow[True]["pull_request"] -assert "dev-tools/smoke/**" in pull_request["paths"] +assert "paths" not in pull_request +changes_script = workflow["jobs"]["changes"]["steps"][-1]["with"]["script"] for required_path in ( - ".github/actions/setup-python/**", - ".python-version", - "config/python/smoke-requirements.txt", - "config/python/smoke-requirements.in", - "services/**", + '"dev-tools/smoke/"', + '".github/actions/setup-python/"', + '".python-version"', + '"config/python/smoke-requirements.txt"', + '"config/python/smoke-requirements.in"', + '"services/"', ): - assert required_path in pull_request["paths"], required_path + assert required_path in changes_script, required_path image_meta = workflow["jobs"]["image-meta"] assert image_meta["outputs"]["runtime_smoke_required"] == ( "${{ steps.smoke_scope.outputs.runtime_smoke_required }}" @@ -184,8 +186,7 @@ smoke_scope_script = smoke_scope["with"]["script"] for required in ( "let runtimeSmokeRequired = true;", "let controllerSmokeRequired = true;", - "github.rest.pulls.listFiles", - "context.payload.pull_request.changed_files", + "GET /repos/{owner}/{repo}/compare/{basehead}", "file.previous_filename", "services/hosted-environment-identity-controller/", "docker/base.Dockerfile", @@ -194,7 +195,7 @@ for required in ( ".python-version", "config/python/smoke-requirements.txt", "config/python/smoke-requirements.in", - "PR smoke scope detection was incomplete; running both local smokes.", + "incomplete immutable test-merge file comparison", "PR smoke scope detection failed; running both local smokes:", 'core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired))', 'core.setOutput("controller_smoke_required", String(controllerSmokeRequired))', @@ -242,13 +243,18 @@ const changedFiles = %s; const apiCalls = []; const warnings = []; const outputs = {}; +const base = "a".repeat(40); const github = { - paginate: async () => changedFiles, - rest: { - pulls: { listFiles: async () => undefined }, - repos: {}, + request: async (route, args) => { + apiCalls.push([route, args.basehead]); + return { data: { + base_commit: { sha: base }, merge_base_commit: { sha: base }, + status: %s ? "ahead" : "diverged", files: changedFiles, + } }; }, }; +process.env.VERIFIED_BASE_SHA = base; +process.env.VERIFIED_MERGE_SHA = "c".repeat(40); const context = { eventName: "pull_request", repo: { owner: "base-owner", repo: "base-repo" }, @@ -256,7 +262,6 @@ const context = { repository: { full_name: "base-owner/base-repo" }, pull_request: { number: 2786, - changed_files: %s, base: { sha: "a".repeat(40) }, head: { sha: "b".repeat(40), repo: { full_name: "fork-owner/fork-repo" } }, }, @@ -277,11 +282,7 @@ process.stdout.write(JSON.stringify({ outputs, warnings, apiCalls })); """ % ( json.dumps(smoke_scope_script), json.dumps([{"filename": path} for path in changed_paths]), - json.dumps( - len(changed_paths) - if changed_file_count is None - else changed_file_count - ), + json.dumps(changed_file_count is None), ) result = subprocess.run( ["node", "--input-type=module", "-e", node_source], @@ -300,7 +301,9 @@ assert authority_change["outputs"] == { "runtime_smoke_required": "true", "controller_smoke_required": "false", } -assert authority_change["apiCalls"] == [] +assert authority_change["apiCalls"] == [ + ["GET /repos/{owner}/{repo}/compare/{basehead}", "a" * 40 + "..." + "c" * 40] +] incomplete_file_list = run_scope([authority_path], changed_file_count=2) assert incomplete_file_list["outputs"] == { @@ -339,7 +342,9 @@ assert "if" not in build_runtime_step # Gate publication on the native smoke outcome, never its continued conclusion. artifact_gate = ( "${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' " - "|| steps.runtime-smoke.outcome == 'success') }}" + "|| steps.runtime-smoke.outcome == 'success') " + # A recomputed retarget merge cannot be selected by the publisher. + "&& (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }}" ) assert export_step["if"] == artifact_gate assert upload_step["if"] == artifact_gate @@ -376,7 +381,6 @@ assert exception_step["id"] == "canonical-play-transition" for condition in ( "always()", "github.repository == 'benhook1013/FireMUD'", - "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", "needs.image-meta.outputs.runtime_smoke_required == 'true'", "steps.runtime-smoke.outcome == 'failure'", "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", @@ -390,9 +394,9 @@ assert guard["env"] == { "RUNTIME_SMOKE_OUTCOME": "${{ steps.runtime-smoke.outcome }}", "RUNTIME_CLEANUP_OUTCOME": "${{ steps.runtime-cleanup.outcome }}", "KNOWN_PLAY_EXCEPTION_OUTCOME": "${{ steps.canonical-play-transition.outcome }}", + "PR_NUMBER": "${{ needs.image-meta.outputs.pr_number }}", } -# Executed success/failure, skipped, cancelled and malformed-outcome guard cases -# are exercised by pr-required-gate-context-contract.sh. +# The guard's live-label waiver decision is exercised by play-waiver-guard-contract.sh. assert "needs.pr-local-smoke.outputs.publishable == 'true'" in ( workflow["jobs"]["dispatch-pr-runtime-publication"]["if"] ) @@ -431,8 +435,9 @@ assert base_step["with"] == { "load": True, "tags": "${{ env.BASE_IMAGE }}", "cache-from": "type=gha,scope=pr-controller-smoke", - "cache-to": "type=gha,mode=max,scope=pr-controller-smoke", } +# Candidate code may read but never write the shared Actions cache. +assert controller_job["cache-mode"] == "read" assert "docker/login-action@" not in str(controller_job) assert "GITHUB_TOKEN" not in str(controller_job) assert '--build-arg BASE_IMAGE="$BASE_IMAGE"' in build_step["run"] @@ -1031,15 +1036,16 @@ assert jobs["retire-identity"]["if"] == ( for job_name in ("destroy-runtime", "retire-identity"): assert "certificate_identity_mode" not in jobs[job_name]["if"], job_name assert validate_job["if"] == ( - "${{ (github.event_name == 'workflow_run' && " + "${{ vars.PREVIEW_GITHUB_HOSTED_CLUSTER_ACCESS == 'true' && (" + "(github.event_name == 'workflow_run' && " "github.event.workflow_run.conclusion == 'success' && " "github.event.workflow_run.head_repository.full_name == github.repository && " "github.event.workflow_run.name == 'PR Preview Environment' && " - "(github.event.workflow_run.event == 'pull_request_target' || " + "(github.event.workflow_run.event == 'pull_request' || " "github.event.workflow_run.event == 'repository_dispatch')) || " "(github.event_name == 'pull_request_target' && " "github.event.action == 'closed' && " - "github.event.pull_request.head.repo.full_name == github.repository) }}" + "github.event.pull_request.head.repo.full_name == github.repository)) }}" ) assert validate_job["permissions"] == { "actions": "read", @@ -4063,7 +4069,7 @@ run_preview_derive_target() { local error_path="$4" env \ PATH="$preview_derive_stub_dir:$PATH" \ - EVENT_NAME=pull_request_target \ + EVENT_NAME=pull_request \ GITHUB_REF=refs/heads/develop \ DEFAULT_BRANCH=develop \ EVENT_ACTION=synchronize \ @@ -4097,7 +4103,7 @@ if run_preview_derive_target \ "$preview_derive_base_lower" \ "$preview_derive_stale_head_output" \ "$TEMP_DIR/preview-derive-stale-head.error"; then - echo "preview plan accepted a stale pull_request_target head SHA" >&2 + echo "preview plan accepted a stale pull_request head SHA" >&2 exit 1 fi grep -Fxq \ @@ -6566,7 +6572,7 @@ if [[ "$1" == run && "$2" == download ]]; then if [[ "${FAKE_ARTIFACT_FILES:-valid}" == valid || "${FAKE_ARTIFACT_FILES:-valid}" == extra ]]; then manifest_sha="$(sha256sum "${VALID_RENDER_MANIFEST:?}" | awk '{print $1}')" jq -nc \ - --arg event "${FAKE_METADATA_EVENT:-pull_request_target}" \ + --arg event "${FAKE_METADATA_EVENT:-pull_request}" \ --arg action "${FAKE_METADATA_ACTION:-}" \ --argjson pr_number "${FAKE_METADATA_PR_NUMBER:-900}" \ --arg base_sha "${FAKE_METADATA_BASE_SHA:-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb}" \ @@ -6720,9 +6726,9 @@ chmod +x "$target_fixture_bin/python3" target_real_python3="$(command -v python3)" canonical_artifact_name='preview-render-pr-900-cccccccccccccccccccccccccccccccccccccccc' -valid_workflow_run_json='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900}]}' +valid_workflow_run_json='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"cccccccccccccccccccccccccccccccccccccccc"}}]}' distinct_source_sha=dddddddddddddddddddddddddddddddddddddddd -distinct_source_workflow_run_json='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900}]}' +distinct_source_workflow_run_json='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"cccccccccccccccccccccccccccccccccccccccc"}}]}' valid_artifacts_json='[{"artifacts":[{"name":"'"$canonical_artifact_name"'","expired":false},{"name":"old-preview","expired":true},{"name":"unrelated-artifact","expired":false}]}]' run_deploy_target_fixture() { @@ -6836,6 +6842,24 @@ FAKE_FIXTURE_WORKFLOW_RUN_JSON="$distinct_source_workflow_run_json" \ FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ run_deploy_target_fixture distinct-source-head 0 'action=deploy' grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-distinct-source-head.output" +# With an empty association, only the native refs/pull path binds the artifact's PR. +FAKE_FIXTURE_WORKFLOW_RUN_JSON='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml@refs/pull/900/merge","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[]}' \ + run_deploy_target_fixture path-bound 0 'action=deploy' +# With distinct head and merge SHAs, a source run carrying the merge SHA is not the head. +FAKE_FIXTURE_WORKFLOW_RUN_JSON='{"conclusion":"success","head_sha":"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee","path":".github/workflows/preview.yml@refs/pull/900/merge","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[]}' \ +FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee \ +FAKE_FIXTURE_METADATA_MERGE_SHA=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee \ + run_deploy_target_fixture path-merge-as-head 0 'Ignoring artifact not bound to the source run pull request and head.' +FAKE_FIXTURE_WORKFLOW_RUN_JSON='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml@refs/pull/901/merge","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[]}' \ + run_deploy_target_fixture path-other-pr 0 'Ignoring artifact not bound to the source path pull request.' +if grep -Fxq 'action=deploy' "$TEMP_DIR/deploy-target-path-other-pr.output"; then + echo "a refs/pull path for another PR must not deploy" >&2 + exit 1 +fi +# Without an association, the source run's own head must be the expected head. +FAKE_FIXTURE_WORKFLOW_RUN_JSON='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml@refs/pull/900/merge","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[]}' \ +FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ + run_deploy_target_fixture path-other-head 0 'Ignoring artifact not bound to the source run pull request and head.' FAKE_FIXTURE_ARTIFACTS_JSON='[{"artifacts":[]}]' \ run_deploy_target_fixture missing-canonical 0 \ @@ -6957,19 +6981,19 @@ run_invalid_source_field() { run_invalid_source_field \ conclusion \ - '{"conclusion":"failure","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"}}' \ + '{"conclusion":"failure","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run conclusion::Expected success; actual failure.' run_invalid_source_field \ head \ - '{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"}}' \ + '{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run head::Expected cccccccccccccccccccccccccccccccccccccccc; actual dddddddddddddddddddddddddddddddddddddddd.' run_invalid_source_field \ path \ - '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/other.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"}}' \ + '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/other.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run path::Expected .github/workflows/preview.yml; actual .github/workflows/other.yml.' run_invalid_source_field \ repository \ - '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"fork/FireMUD"}}' \ + '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"fork/FireMUD"}}' \ '::error title=Unexpected source run repository::Expected example/FireMUD; actual fork/FireMUD.' target_python_log="$TEMP_DIR/closed-target-python.log" diff --git a/dev-tools/tests/jacoco-combined-report-contract.sh b/dev-tools/tests/jacoco-combined-report-contract.sh index b27d0d0f06..535afe3d74 100644 --- a/dev-tools/tests/jacoco-combined-report-contract.sh +++ b/dev-tools/tests/jacoco-combined-report-contract.sh @@ -3,6 +3,7 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" LOCKED_GRADLE="$ROOT_DIR/dev-tools/validation/run-locked-gradle.sh" +RECOVERY_GRADLE="$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" TMP_DIR="$(mktemp -d)" trap 'rm -rf "$TMP_DIR"' EXIT @@ -13,12 +14,25 @@ account_aggregate_graph="$TMP_DIR/account-aggregate-graph" game_session_aggregate_graph="$TMP_DIR/game-session-aggregate-graph" world_aggregate_graph="$TMP_DIR/world-aggregate-graph" -bash "$LOCKED_GRADLE" :common-saga:test -PfullCheck --dry-run --no-configuration-cache >"$unit_graph" -bash "$LOCKED_GRADLE" :common-saga:check -PfullCheck --dry-run --no-configuration-cache >"$check_graph" -bash "$LOCKED_GRADLE" :common-saga:jacocoTestReport -PfullCheck --dry-run --no-configuration-cache >"$report_graph" -bash "$LOCKED_GRADLE" :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$account_aggregate_graph" -bash "$LOCKED_GRADLE" :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$game_session_aggregate_graph" -bash "$LOCKED_GRADLE" :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$world_aggregate_graph" +run_task_graph() { + local graph="$1" + local status + shift + if bash "$RECOVERY_GRADLE" --runner "$LOCKED_GRADLE" -- "$@" >"$graph"; then + return 0 + else + status=$? + cat "$graph" >&2 + return "$status" + fi +} + +run_task_graph "$unit_graph" :common-saga:test -PfullCheck --dry-run --no-configuration-cache +run_task_graph "$check_graph" :common-saga:check -PfullCheck --dry-run --no-configuration-cache +run_task_graph "$report_graph" :common-saga:jacocoTestReport -PfullCheck --dry-run --no-configuration-cache +run_task_graph "$account_aggregate_graph" :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail +run_task_graph "$game_session_aggregate_graph" :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail +run_task_graph "$world_aggregate_graph" :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail if grep -Eq '^:common-saga:(integrationTest|crossServiceTest|jacocoTestReport)([[:space:]]|$)' "$unit_graph"; then echo "Focused :common-saga:test unexpectedly scheduled categorized tests or the combined report." >&2 diff --git a/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh b/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh index 6c7da1d629..fd91a8aff9 100644 --- a/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh +++ b/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh @@ -93,9 +93,16 @@ require_contains "$trusted_builder" 'run: bash ./dev-tools/minio/build-and-smoke require_contains "$trusted_builder" 'if: github.event_name == '\''push'\''' require_contains "$trusted_builder" 'uses: actions/upload-artifact@' -runtime_workflow="$(<"$WORKFLOW")" -require_contains "$runtime_workflow" " - 'dev-tools/minio/**'" -require_count "$runtime_workflow" '"dev-tools/minio/"' 2 +# No paths filter: change detection, the PR smoke scope and the refresh +# selector each name MinIO sources. +python3 - "$WORKFLOW" <<'PY' +import sys +import yaml +jobs = yaml.safe_load(open(sys.argv[1], encoding="utf-8"))["jobs"] +for job in ("changes", "image-meta", "dispatch-pr-base-refreshes"): + if '"dev-tools/minio/"' not in str(jobs[job]): + sys.exit(f"{job} must classify dev-tools/minio/ changes") +PY overlay="$(<"$OVERLAY")" require_contains "$overlay" 'minio:' diff --git a/dev-tools/tests/play-waiver-guard-contract.sh b/dev-tools/tests/play-waiver-guard-contract.sh new file mode 100644 index 0000000000..5c7c5d3c0e --- /dev/null +++ b/dev-tools/tests/play-waiver-guard-contract.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# Behaviour test: the PR Full-Stack Smoke terminal guard waives a failed smoke +# only for the exact known PLAY failure with successful cleanup, and only while +# a live API read shows the canonical-play-transition label. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +work="$(mktemp -d)" +trap 'rm -rf -- "$work"' EXIT + +python3 - "$ROOT_DIR/.github/workflows/runtime-images.yml" "$work" <<'PY' +import sys +from pathlib import Path +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["pr-local-smoke"]["steps"] +guard, = (s for s in steps if s.get("name") == "Require successful runtime smoke and authenticated cleanup") +# The terminal guard always runs and its failure fails the job. +assert guard.get("if") in ("always()", "${{ always() }}"), guard.get("if") +assert str(guard.get("continue-on-error", "false")).lower() == "false" +marker, = (s for s in steps if s.get("id") == "canonical-play-transition") +Path(sys.argv[2], "guard.js").write_text(guard["with"]["script"]) +Path(sys.argv[2], "marker.txt").write_text(marker["if"]) +gate, = (s for s in workflow["jobs"]["smoke-gate"]["steps"] if s.get("name") == "Require this run's runtime smoke") +# The enforcement runs whenever the gate executes for a runtime-scoped change. +assert gate["if"] == "${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full == 'true' }}", gate["if"] +assert str(gate.get("continue-on-error", "false")).lower() == "false" +assert gate["env"] == { + "IMAGE_META_RESULT": "${{ needs.image-meta.result }}", + "LOCAL_SMOKE_RESULT": "${{ needs.pr-local-smoke.result }}", + "CONTROLLER_SMOKE_RESULT": "${{ needs.pr-controller-smoke.result }}", + "CONTROLLER_SMOKE_REQUIRED": "${{ needs.image-meta.outputs.controller_smoke_required }}", +}, gate["env"] +Path(sys.argv[2], "gate.sh").write_text(gate["run"]) +PY + +# The marker attests only the exact failure code and cleanup; labels are not read there. +for clause in "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'" \ + "steps.runtime-cleanup.outcome == 'success'" "steps.runtime-smoke.outcome == 'failure'"; do + grep -Fq "$clause" "$work/marker.txt" || { echo "PLAY marker lacks: $clause" >&2; exit 1; } +done +# Every clause is required: no alternative branch can set the marker. +if grep -Fq '||' "$work/marker.txt"; then + echo "PLAY marker clauses must all be required" >&2 + exit 1 +fi +if grep -Fq 'labels' "$work/marker.txt"; then + echo "PLAY marker must not read event-payload labels; the guard reads them live" >&2 + exit 1 +fi + +# Smoke Gate passes only on this run's successful smoke jobs. +gate() { + IMAGE_META_RESULT="$1" LOCAL_SMOKE_RESULT="$2" CONTROLLER_SMOKE_RESULT="$3" CONTROLLER_SMOKE_REQUIRED="$4" \ + bash "$work/gate.sh" >/dev/null 2>&1 +} +gate success success success true || { echo "Smoke Gate must pass on successful smoke" >&2; exit 1; } +gate success success skipped false || { echo "Smoke Gate must pass without required controller smoke" >&2; exit 1; } +for args in "success failure success true" "success success skipped true" "failure success success true" \ + "success cancelled skipped false"; do + # shellcheck disable=SC2086 + if gate $args; then echo "Smoke Gate must fail for: $args" >&2; exit 1; fi +done + +node - "$work/guard.js" <<'NODE' +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const guard = new AsyncFunction("github", "context", "core", "process", fs.readFileSync(process.argv[2], "utf8")); + +async function run(env, labels) { + const failures = [], warnings = [], reads = []; + const github = {rest: {pulls: {get: async args => { + reads.push(args.pull_number); + if (labels instanceof Error) throw labels; + return {data: {labels}}; + }}}}; + await guard(github, {repo: {owner: "o", repo: "r"}}, + {setFailed: m => failures.push(m), warning: m => warnings.push(m)}, + {env: {RUNTIME_SMOKE_REQUIRED: "true", RUNTIME_CLEANUP_OUTCOME: "success", PR_NUMBER: "42", ...env}}); + return {failures, warnings, reads}; +} +const waiver = {RUNTIME_SMOKE_OUTCOME: "failure", KNOWN_PLAY_EXCEPTION_OUTCOME: "success"}; +const label = [{name: "canonical-play-transition"}]; + +(async () => { + let r = await run({RUNTIME_SMOKE_OUTCOME: "success"}, []); + assert.deepEqual([r.failures, r.reads], [[], []], "passing smoke needs no label read"); + r = await run({RUNTIME_SMOKE_REQUIRED: "false"}, []); + assert.deepEqual(r.failures, [], "out-of-scope smoke passes"); + r = await run({RUNTIME_SMOKE_REQUIRED: ""}, []); + assert.equal(r.failures.length, 1, "unknown scope fails"); + + r = await run(waiver, label); + assert.deepEqual([r.failures, r.reads, r.warnings.length], [[], [42], 1], "labelled exact PLAY failure is waived"); + for (const labels of [[], [{name: "preview:priority"}], null, new Error("HTTP 503")]) { + r = await run(waiver, labels); + assert.equal(r.failures.length, 1, `no waiver without a readable live label: ${labels}`); + } + for (const env of [ + {...waiver, KNOWN_PLAY_EXCEPTION_OUTCOME: "skipped"}, + {...waiver, RUNTIME_CLEANUP_OUTCOME: "failure"}, + {...waiver, RUNTIME_SMOKE_OUTCOME: "cancelled"}, + {RUNTIME_SMOKE_OUTCOME: "success", RUNTIME_CLEANUP_OUTCOME: "skipped"}, + ]) { + r = await run(env, label); + assert.equal(r.failures.length, 1, `must fail: ${JSON.stringify(env)}`); + } + console.log("PLAY waiver guard contract passed"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh old mode 100644 new mode 100755 index 166ef685dc..2834fecdf6 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -129,6 +129,11 @@ while IFS='|' read -r workflow gate_job_id gate workflow_name workflow_file work exit 1 } expected_run_name="run-name: ${workflow_name} \${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}" + if [[ "$workflow" == runtime-images.yml ]]; then + # The runtime title appends the built merge and a mode the publisher matches + # (mode-required for substantive PRs and refreshes, mode-metadata for edits). + expected_run_name="run-name: ${workflow_name} \${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }}" + fi grep -Fxq "$expected_run_name" "$path" || { echo "$workflow must publish its canonical pull-request run title" >&2 exit 1 @@ -191,7 +196,7 @@ while IFS='|' read -r workflow gate_job_id gate workflow_name workflow_file work print } ' <<<"$gate_block")" - if [[ "$workflow" == "smoke.yml" ]]; then + if [[ "$workflow" == "runtime-images.yml" ]]; then # shellcheck disable=SC2016 # Assert literal smoke classification output syntax. expected_preserve_condition=" if: \${{ steps.smoke_gate_context.outputs.required != 'true' }}" else @@ -300,7 +305,7 @@ change_job_names = { "ci.yml": "Detect CI-Relevant Changes", "security.yml": "Detect Security-Relevant Changes", "license-scan.yml": "Detect License-Relevant Changes", - "smoke.yml": "Detect Smoke-Relevant Changes", + "runtime-images.yml": "Detect Smoke-Relevant Changes", "codeql.yml": "Detect CodeQL-Relevant Changes", } @@ -381,7 +386,7 @@ if not isinstance(result_env, dict) or result_env.get("CHANGES_RESULT") != "${{ PY group_line=$(grep -m1 '^ group:' "$path" || true) - if [[ "$workflow" == "ci.yml" || "$workflow" == "security.yml" || "$workflow" == "smoke.yml" ]]; then + if [[ "$workflow" == "ci.yml" || "$workflow" == "security.yml" || "$workflow" == "runtime-images.yml" ]]; then if [[ "$group_line" != *"format('metadata-{0}', github.run_id) || 'required' }}"* ]]; then echo "$workflow concurrency group must give every metadata-only run a unique namespace" >&2 exit 1 @@ -394,7 +399,8 @@ PY echo "$workflow concurrency group must remain scoped to the PR number" >&2 exit 1 fi - if ! grep -Fq ' cancel-in-progress: true' "$path"; then + # runtime-images never cancels: superseded comparisons skip smoke instead. + if ! grep -Fq ' cancel-in-progress: true' "$path" && [[ "$workflow" != runtime-images.yml ]]; then echo "$workflow must cancel only within its metadata/required concurrency namespace" >&2 exit 1 fi @@ -406,64 +412,743 @@ done <<'EOF' ci.yml|validation-gate|Validation Gate|CI โ€” Validation|ci.yml|.github/workflows/ci.yml security.yml|security-gate|Security Gate|Security Gate|security.yml|.github/workflows/security.yml license-scan.yml|license-gate|License Gate|License Gate|license-scan.yml|.github/workflows/license-scan.yml -smoke.yml|smoke-gate|Smoke Gate|PR Smoke Gate|smoke.yml|.github/workflows/smoke.yml +runtime-images.yml|smoke-gate|Smoke Gate|Build Runtime Images|runtime-images.yml|.github/workflows/runtime-images.yml codeql.yml|codeql-gate|CodeQL Gate|CodeQL Analysis|codeql.yml|.github/workflows/codeql.yml EOF -# Model two rapid metadata edits against the unchanged head. Each lightweight -# run gets an independent namespace, while the required gate contexts remain -# the sole authoritative checks and optional summaries cannot leave cancelled -# or failed residue in the aggregate rollup. python3 - "$ROOT_DIR" <<'PY' +import ast +import io +import os from pathlib import Path +import re +import subprocess import sys +import tokenize import yaml +if not __debug__: + raise SystemExit("Required-gate assertions must run with Python optimization disabled") + root = Path(sys.argv[1]) -workflows = { - "ci.yml": ("validation-gate", "Validation Gate", True), - "security.yml": ("security-gate", "Security Gate", True), - "license-scan.yml": ("license-gate", "License Gate", False), - "smoke.yml": ("smoke-gate", "Smoke Gate", True), - "codeql.yml": ("codeql-gate", "CodeQL Gate", False), +META = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null" +SUBSTANTIVE = "(github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null)" +PR_SUBSTANTIVE = "(github.event.action != 'edited' || github.event.changes.base.ref != null)" +gates = { + # workflow: (workflow name, gate job, gate name, change job name, result step, PR-only, run-scoped metadata group) + "ci.yml": ("CI โ€” Validation", "validation-gate", "Validation Gate", "Detect CI-Relevant Changes", "Enforce validation success", False, True), + "security.yml": ("Security Gate", "security-gate", "Security Gate", "Detect Security-Relevant Changes", "Enforce security success", False, True), + "license-scan.yml": ("License Gate", "license-gate", "License Gate", "Detect License-Relevant Changes", "Verify ORT results", False, False), + "runtime-images.yml": ("Build Runtime Images", "smoke-gate", "Smoke Gate", "Detect Smoke-Relevant Changes", "Classify smoke gate execution", True, True), + "codeql.yml": ("CodeQL Analysis", "codeql-gate", "CodeQL Gate", "Detect CodeQL-Relevant Changes", "Enforce successful CodeQL analysis", True, False), } -metadata_guard = "github.event.action != 'edited' || github.event.changes.base.ref != null" -for workflow, (gate_job, gate_name, run_scoped_metadata) in workflows.items(): - path = root / ".github" / "workflows" / workflow - data = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) - concurrency = data["concurrency"] - group = concurrency["group"] - required_group_parts = ( - "github.event.pull_request.number", - "github.event.action == 'edited'", - "github.event.changes.base.ref == null", - "|| 'required'", + +def translate_actions(body, values): + tokens = re.compile( + r"""(?P'(?:''|[^'])*')|(?P"(?:\\.|[^"\\])*")|""" + + r"(?P(?&&|\|\|)|(?P\b(?:null|true|false)\b)|(?P[A-Za-z_][A-Za-z0-9_]*)" + ) + translations = {"&&": " and ", "||": " or ", "null": "None", "true": "True", "false": "False"} + + def translate(token): + value = token[0] + if token.lastgroup == "single": + return repr(value[1:-1].replace("''", "'")) + if token.lastgroup == "double": + raise ValueError("Actions expression string literals must be single-quoted") + if token.lastgroup == "context": + return values[value] + if token.lastgroup == "identifier": + if value == "format": + return value + raise ValueError(f"Unsupported Actions expression token: {value}") + return translations[value] + + translated = tokens.sub(translate, body) + previous = None + for token in tokenize.generate_tokens(io.StringIO(translated.strip()).readline): + if token.type in (tokenize.NEWLINE, tokenize.NL): + continue + if token.type == tokenize.COMMENT: + raise ValueError("Actions expressions do not allow comments") + if token.type == tokenize.STRING and previous == tokenize.STRING: + raise ValueError("Actions expression does not allow adjacent string literals") + previous = token.type + return translated + + +def evaluate(expression, action, base_ref, event="pull_request"): + """Evaluate the narrow boolean gate expressions used here.""" + body = expression.strip() + if body.startswith("${{") and body.endswith("}}"): + body = body[3:-2].strip() + values = { + "github.event.changes.base.ref": repr(base_ref), + "github.event.action": repr(action), + "github.event_name": repr(event), + "always()": "True", + } + return bool(evaluate_selector(ast.parse(translate_actions(body, values).strip(), mode="eval").body)) + + +def push_branch_matches(push_config, branch): + if not isinstance(push_config, dict): + raise ValueError("Unsupported push trigger shape") + if "branches-ignore" in push_config: + raise ValueError("Unsupported push branch exclusion syntax") + if "paths" in push_config or "paths-ignore" in push_config: + raise ValueError("Protected push triggers must not filter paths") + branches = push_config.get("branches") + if branches is None: + return "tags" not in push_config and "tags-ignore" not in push_config + if not isinstance(branches, list) or any(not isinstance(pattern, str) for pattern in branches): + raise ValueError("Unsupported push branch filter shape") + for pattern in branches: + if any(character in pattern for character in "!?[]+") or "**" in pattern: + raise ValueError(f"Unsupported push branch glob syntax: {pattern!r}") + for pattern in branches: + expression = "^" + re.escape(pattern).replace(r"\*", "[^/]*") + "$" + if re.fullmatch(expression, branch): + return True + return False + + +assert push_branch_matches({"branches": ["main", "release/*"]}, "main") +assert push_branch_matches({}, "main") +assert not push_branch_matches({"tags": ["release-*"]}, "main") +assert not push_branch_matches({"tags-ignore": ["next-*"]}, "develop") +assert push_branch_matches({"branches": ["main", "release/*"]}, "release/2026") +assert not push_branch_matches({"branches": ["main", "release/*"]}, "release/2026/hotfix") +for unsupported_filter in ( + {"branches": ["!main"]}, {"branches": ["release/**"]}, + {"branches": ["feature/?"]}, {"branches": ["release/[0-9]"]}, + {"branches": ["m+ain", "develop"]}, + {"branches-ignore": ["main"]}, + {"branches": ["main"], "paths": ["README.md"]}, + {"branches": ["main"], "paths-ignore": ["**"]}, +): + try: + push_branch_matches(unsupported_filter, "main") + except ValueError: + pass + else: + raise AssertionError(f"accepted unsupported push branch filter: {unsupported_filter!r}") + + + +def actions_scalar_text(value): + if value is None: + return "" + if type(value) is bool: + return "true" if value else "false" + if type(value) is int and abs(value) > 2**53 - 1: + raise ValueError("Actions integer formatting exceeds the supported precision") + return str(value) + + +def literal_format(pattern, *args): + if type(pattern) is not str: + raise ValueError("Concurrency format requires a literal string") + parts = [] + cursor = 0 + for match in re.finditer(r"\{([0-9]+)\}", pattern): + literal = pattern[cursor:match.start()] + if "{" in literal or "}" in literal: + raise ValueError("Unsupported concurrency format placeholder") + index = int(match[1]) + if index >= len(args): + raise ValueError("Concurrency format placeholder out of range") + parts.extend((literal, actions_scalar_text(args[index]))) + cursor = match.end() + tail = pattern[cursor:] + if "{" in tail or "}" in tail: + raise ValueError("Unsupported concurrency format placeholder") + return "".join((*parts, tail)) + + +def selector_equal(left, right): + # GitHub Actions compares like kinds directly and coerces unlike kinds + # to numbers. Object values compare only with values of the same kind. + if type(left) is type(right): + if isinstance(left, str): + if left == right: + return True + # The harness also uses the known Unicode display name for Validation. + # Its em dash has no case variants. + if not left.replace("โ€”", "").isascii() or not right.replace("โ€”", "").isascii(): + raise ValueError("Unsupported non-ASCII Actions string comparison") + return left.lower() == right.lower() + if type(left) is int: + return float(left) == float(right) + return left == right + if type(left) not in (str, bool, int, float, type(None)) or \ + type(right) not in (str, bool, int, float, type(None)): + return False + + def to_number(value): + if value is None: + return 0 + if type(value) in (bool, int, float): + return float(value) + if type(value) is str: + number = value.strip() + if not number: + return 0 + if re.fullmatch(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?", number): + return float(number) + if number.startswith(("0x", "0o")) or number.lstrip("+-").casefold() == "infinity": + raise ValueError("Unsupported concurrency numeric string") + return float("nan") + raise ValueError("Unsupported concurrency comparison operand") + + return to_number(left) == to_number(right) + + +assert selector_equal("DeVeLoP", "develop") +try: + selector_equal("straรŸe", "strasse") +except ValueError: + pass +else: + raise AssertionError("non-ASCII Actions equality must not use Python folding") + + +def validate_selector(node): + if isinstance(node, ast.Constant) and type(node.value) in (str, int, bool, type(None)): + return + if isinstance(node, ast.Dict): + children = [*node.keys, *node.values] + elif isinstance(node, ast.BoolOp) and isinstance(node.op, (ast.And, ast.Or)): + children = node.values + elif (isinstance(node, ast.Compare) and len(node.ops) == 1 + and isinstance(node.ops[0], (ast.Eq, ast.NotEq))): + children = [node.left, *node.comparators] + elif (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id == "format" and not node.keywords and node.args + and isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str)): + children = node.args + else: + raise ValueError("Unsupported concurrency selector") + for child in children: + validate_selector(child) + + +def evaluate_selector(node): + validate_selector(node) + return interpret_selector(node) + + +def interpret_selector(node): + if isinstance(node, ast.Constant) and type(node.value) in (str, int, bool, type(None)): + return node.value + if isinstance(node, ast.Dict): + return {interpret_selector(key): interpret_selector(value) for key, value in zip(node.keys, node.values)} + if isinstance(node, ast.BoolOp) and isinstance(node.op, (ast.And, ast.Or)): + # GitHub's boolean operators return operands and short-circuit. + value = interpret_selector(node.values[0]) + for operand in node.values[1:]: + if bool(value) == isinstance(node.op, ast.Or): + return value + value = interpret_selector(operand) + return value + if (isinstance(node, ast.Compare) and len(node.ops) == 1 + and isinstance(node.ops[0], (ast.Eq, ast.NotEq))): + left = interpret_selector(node.left) + right = interpret_selector(node.comparators[0]) + return selector_equal(left, right) == isinstance(node.ops[0], ast.Eq) + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id == "format" and not node.keywords and node.args + and isinstance(node.args[0], ast.Constant)): + return literal_format(*(interpret_selector(arg) for arg in node.args)) + raise ValueError("Unsupported concurrency selector") + + +for expression, expected in ( + ("'Develop' == 'develop'", True), + ("'Develop' != 'develop'", False), + ("12 == '12'", True), + ("9007199254740993 != '9007199254740993'", False), + ("9007199254740993 == 9007199254740992", True), + ("12 != ' 1.2e1 '", False), + ("False == 0", True), + ("None == 0", True), + ("1 == 'one'", False), + ("1 == '01'", True), + ("2 == '+002.0'", True), + ("0 == ' '", True), +): + assert interpret_selector(ast.parse(expression, mode="eval").body) is expected + +assert not evaluate(SUBSTANTIVE + " && github.event.action != 'SYNCHRONIZE'", "synchronize", None) +try: + evaluate('github.event.action == "synchronize"', "synchronize", None) +except ValueError as error: + assert "single-quoted" in str(error) +else: + raise AssertionError("double-quoted Actions literal was accepted") + + + +assert literal_format("metadata-{0}", 123) == "metadata-123" +assert literal_format("{0}", 2**53 - 1) == str(2**53 - 1) +for value in (2**53, -(2**53)): + try: + literal_format("{0}", value) + except ValueError as error: + assert "precision" in str(error) + else: + raise AssertionError("Actions formatting accepted an integer outside the supported precision") +for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{1}"): + try: + literal_format(forbidden, 123) + except ValueError: + pass + else: + raise AssertionError(f"Accepted unsupported concurrency format: {forbidden}") + + +for expression in ("true || unsupported()", "false && unsupported()", + SUBSTANTIVE + " and true", "false or true", "True", "None", "not false", + "0xffffffff != '-1'", "1_000 == 1000", "true # 0"): + try: + evaluate(expression, "edited", None) + except ValueError: + pass + else: + raise AssertionError(f"Unsupported Actions expression was accepted: {expression}") +assert evaluate("github.event.changes.base.ref == null", "edited", None) +assert not evaluate("'null' == 'None'", "edited", None) +assert evaluate("'it''s' == 'IT''S'", "edited", None) +assert evaluate("'head#0' == 'HEAD#0'", "edited", None) +try: + evaluate("true && 'run' 'me'", "edited", None) +except ValueError: + pass +else: + raise AssertionError("Actions expressions cannot concatenate adjacent literals") +assert evaluate("'room!=hall||garden' == 'room!=hall||garden'", "edited", None) +assert not evaluate("'room!=hall' == 'room != hall'", "edited", None) + + +def effective_group(group, action, base_ref, workflow_name="Required Gate", *, pr_number=42, push_branch=None, run_id="123"): + values = { + "github.event.changes.base.ref": repr(base_ref), + "github.event.pull_request.number": repr("") if push_branch else str(pr_number), + "github.event.action": repr(action), + "github.event_name": repr("push" if push_branch else "pull_request"), + "github.workflow": repr(workflow_name), + "github.run_id": repr(run_id), + "github.ref": repr(f"refs/heads/{push_branch}" if push_branch else f"refs/pull/{pr_number}/merge"), + } + # Build Runtime Images also keys typed refreshes and CI callbacks; those + # contexts are empty for pull_request and push events. + for context_name in ( + "github.sha", "github.event.client_payload.pr_number", "github.event.client_payload.base_sha", + "github.event.client_payload.head_sha", "github.event.client_payload.merge_sha", + "github.event.workflow_run.event", "github.event.workflow_run.id", "github.event.workflow_run.run_attempt", + "github.event.workflow_run.conclusion", "github.event.workflow_run.head_branch", + "github.event.workflow_run.head_sha", + ): + values.setdefault(context_name, repr("")) + + def render(match): + body = translate_actions(match[1].strip(), values) + tree = ast.parse(body, mode="eval") + return actions_scalar_text(evaluate_selector(tree.body)) + return re.sub(r"\$\{\{(.*?)\}\}", render, group, flags=re.DOTALL) + + +assert effective_group("${{ 'null' == 'None' && 'failed' || 'ok' }}", None, None) == "ok" +assert effective_group("${{ 'true && false' }}", None, None) == "true && false" +assert effective_group("${{ 'github.ref' }}", None, None) == "github.ref" +assert effective_group("${{ 'it''s null' }}", None, None) == "it's null" +assert effective_group("${{ true && 'a||b' == 'a or b' }}", None, None) == "false" + +assert effective_group("${{ format('gate{0}{1}{2}', null, true, false) }}", None, None) == "gatetruefalse" +assert effective_group("${{ null }}-${{ true }}-${{ false }}", None, None) == "-true-false" +assert effective_group("${{\n github.run_id }}-required", None, None, run_id="456") == "456-required" + + +def concurrency_group_collisions(rendered_groups): + owners = {} + collisions = [] + for workflow, owner, group in rendered_groups: + key = group.casefold() + prior = owners.get(key) + if prior is not None and prior[:2] != (workflow, owner): + collisions.append((prior, (workflow, owner, group))) + else: + owners[key] = (workflow, owner, group) + return collisions + + +def can_reuse_required_name(name, required_names): + if not name: + return False + # These current matrix templates have fixed delimiters that can never + # render any required context. Do not assume arbitrary dynamics are safe. + matrix_prefixes = ( + "Build and Test (${{ matrix.module }} / ${{ matrix.partition }})", + "Build and Test (account-service / ${{ matrix.partition }})", + "Build and Test (game-session-service / ${{ matrix.partition }})", + "Build and Test (world-management-service / ${{ matrix.partition }})", + "CodeQL Analysis (${{ matrix.language }})", + ) + if name in matrix_prefixes and all( + not gate.startswith(("Build and Test (", "CodeQL Analysis (")) for gate in required_names + ): + return False + # A rendered name starts with its literal text before the first + # expression, so it cannot equal a required context without that prefix. + literal = name.split("${{", 1)[0] + if "${{" in name and literal and not any(gate.startswith(literal) for gate in required_names): + return False + dynamic = re.fullmatch(r"\$\{\{(.*?)\}\}", name) + if not dynamic: + return "${{" in name or name in required_names + body = dynamic[1].strip() + # Limit dynamic names to the existing exact metadata ternary shape or a + # constant literal; other shapes need an explicitly reviewed model. + if re.fullmatch(r"'[^']*'", body): + return body[1:-1] in required_names + summary = re.fullmatch( + re.escape("github.event.action == 'edited' && github.event.changes.base.ref == null") + + r" && '([^']*)' \|\| '([^']*)'", + body, + ) + return not summary or any(option in required_names for option in summary.groups()) + + +assert can_reuse_required_name("${{ 'CodeQL Gate' }}", {"CodeQL Gate"}) +assert not can_reuse_required_name("${{ 'Auxiliary Report' }}", {"CodeQL Gate"}) +assert can_reuse_required_name("${{ matrix.language }}", {"CodeQL Gate"}) +assert not can_reuse_required_name("CodeQL Analysis (${{ matrix.language }})", {"CodeQL Gate"}) + + +def isolates_metadata_group(group, run_scoped, workflow_name, *, pr_number=42): + metadata_groups = [ + effective_group(group, "edited", None, workflow_name, pr_number=pr_number, run_id=run_id) + for run_id in ("123", "456") + ] + expected_suffixes = ("-metadata-123", "-metadata-456") if run_scoped else ("-metadata", "-metadata") + substantive = [ + effective_group(group, action, base_ref, workflow_name, pr_number=pr_number, run_id=run_id) + for action, base_ref in ( + ("edited", {"from": "main", "to": "develop"}), ("opened", None), ("synchronize", None), ("reopened", None), + ) + for run_id in ("123", "456") + ] + if len({name.casefold() for name in substantive}) != 1: + return False + distinct_metadata_groups = metadata_groups[0].casefold() != metadata_groups[1].casefold() + if distinct_metadata_groups != run_scoped: + return False + return all( + name.endswith(suffix) for name, suffix in zip(metadata_groups, expected_suffixes) + ) and all(name.endswith("-required") for name in substantive) + + +def excludes_metadata(expression): + body = expression.strip() + if body.startswith("${{") and body.endswith("}}"): + body = body[3:-2].strip() + if body == SUBSTANTIVE[1:-1] or body == PR_SUBSTANTIVE[1:-1]: + return True + # Only a required top-level conjunction can enforce the exclusion. + # Parenthesized additional conditions may contain OR without bypassing it. + depth = 0 + quoted = False + start = 0 + terms = [] + index = 0 + while index < len(body): + char = body[index] + if char == "'": + if quoted and index + 1 < len(body) and body[index + 1] == "'": + index += 2 + continue + quoted = not quoted + elif not quoted: + if char == "(": + depth += 1 + elif char == ")": + depth -= 1 + if depth < 0: + return False + elif depth == 0 and body[index:index + 2] == "||": + return False + elif depth == 0 and body[index:index + 2] == "&&": + terms.append(body[start:index].strip()) + start = index + 2 + index += 1 + index += 1 + terms.append(body[start:].strip()) + return not quoted and depth == 0 and any(term in (SUBSTANTIVE, PR_SUBSTANTIVE) for term in terms) + + +assert excludes_metadata("${{ " + SUBSTANTIVE + " && needs.changes.result == 'success' }}") +assert excludes_metadata("${{ always() && " + PR_SUBSTANTIVE + " && (true || false) }}") +assert not excludes_metadata("${{ github.event_name == 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }}") +assert not excludes_metadata("${{ " + SUBSTANTIVE + " || always() }}") +assert not excludes_metadata("${{ (" + SUBSTANTIVE + " || always()) }}") + +for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_only, run_scoped) in gates.items(): + path = root / ".github/workflows" / workflow + text = path.read_text(encoding="utf-8") + data = yaml.load(text, Loader=yaml.BaseLoader) + if data.get("name") != workflow_name: + raise SystemExit(f"{workflow} must keep workflow name {workflow_name!r}") + pr_trigger = data["on"]["pull_request"] + if not isinstance(pr_trigger, dict) or set(pr_trigger) != {"types"} or set(pr_trigger["types"]) != { + "opened", "synchronize", "reopened", "edited" + }: + raise SystemExit(f"{workflow} must trigger on all supported PR comparisons, including base retargets") + expected_title = ( + f"{workflow_name} ${{{{ github.event_name == 'pull_request' && format('pr-{{0}} base-{{1}} head-{{2}}', " + "github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}" ) - if any(part not in group for part in required_group_parts): - raise SystemExit(f"{workflow} concurrency expression lost PR-scoped metadata isolation") - metadata_suffix = "format('metadata-{0}', github.run_id)" if run_scoped_metadata else "&& 'metadata' || 'required'" - if metadata_suffix not in group: - raise SystemExit(f"{workflow} concurrency expression changed its metadata group") - if concurrency.get("cancel-in-progress") != "true": - raise SystemExit(f"{workflow} must cancel obsolete required-gate runs") + if workflow == "runtime-images.yml": + # Pinned in full by the run-name check above; here only the mode switch. + title_matches = ("github.event_name == 'pull_request' && github.event.action == 'edited' && " + "github.event.changes.base.ref == null && 'metadata' || 'required')") in str(data.get("run-name", "")) + else: + title_matches = data.get("run-name") == expected_title + if not title_matches: + raise SystemExit(f"{workflow} must publish its canonical pull-request run title") + if data["jobs"]["changes"].get("name") != change_job: + raise SystemExit(f"{workflow} change detection job must stay {change_job!r}") gate = data["jobs"][gate_job] if gate.get("name") != gate_name: - raise SystemExit(f"{workflow} required gate context changed") + raise SystemExit(f"{workflow} {gate_name} must retain its required context for metadata edits") + expected_if = "${{ always() && github.event_name == 'pull_request' }}" if pr_only else "${{ always() }}" + if gate.get("if") != expected_if or not evaluate(gate["if"], "edited", None): + raise SystemExit(f"{workflow} {gate_name} must evaluate the preservation path on title/body edits") + retarget_change = {"from": "main", "to": "develop"} + for action, base_ref in (("edited", retarget_change), ("opened", None), ("synchronize", None), ("reopened", None)): + if not evaluate(gate["if"], action, base_ref): + raise SystemExit(f"{workflow} {gate_name} must run for {action} (base change={base_ref})") + if not pr_only and not evaluate(gate["if"], None, None, event="push"): + raise SystemExit(f"{workflow} {gate_name} must still run on push") + needs = gate.get("needs") + needs = needs if isinstance(needs, list) else [needs] + if "changes" not in needs: + raise SystemExit(f"{workflow} {gate_name} must depend on change detection") + if workflow == "codeql.yml" and "analyze" not in needs: + raise SystemExit(f"{workflow} {gate_name} must depend directly on analyze") + result_steps = [step for step in gate.get("steps", []) if step.get("name") == result_step] + if len(result_steps) != 1 or result_steps[0].get("env", {}).get("CHANGES_RESULT") != "${{ needs.changes.result }}": + raise SystemExit(f"{workflow} {gate_name} must enforce through one {result_step!r} step reading CHANGES_RESULT") + if result_steps[0].get("continue-on-error", "false") != "false": + raise SystemExit(f"{workflow} {gate_name} result step cannot ignore failures") + if workflow == "runtime-images.yml": + if "if" in result_steps[0] or result_steps[0]["env"].get("SMOKE_GATE_REQUIRED") != ( + "${{ github.event.action != 'edited' || github.event.changes.base.ref != null }}" + ): + raise SystemExit("Smoke classification must distinguish metadata edits from substantive proof") + else: + condition = result_steps[0].get("if", "") + if not condition or evaluate(condition, "edited", None): + raise SystemExit(f"{workflow} {gate_name} substantive enforcement must skip metadata edits") + for action, base_ref in (("edited", retarget_change), ("opened", None), ("synchronize", None), ("reopened", None)): + if not evaluate(condition, action, base_ref): + raise SystemExit(f"{workflow} {gate_name} must enforce failure for {action}") + if not pr_only and not evaluate(condition, None, None, event="push"): + raise SystemExit(f"{workflow} {gate_name} must enforce failure on push") + if workflow == "ci.yml": + step = result_steps[0] + if step["env"].get("HELM_TRANSACTION_PROOF") != "${{ needs.helm-transaction-proof.result }}": + raise SystemExit("Validation enforcement must use the Helm transaction proof result") + # A gate can read only the results of its direct dependencies. + if "helm-transaction-proof" not in data["jobs"][gate_job].get("needs", []): + raise SystemExit("Validation Gate must depend directly on the Helm transaction proof") + successful_results = {name: "success" for name, binding in step["env"].items() + if binding.endswith(".result }}")} + validation_inputs = dict.fromkeys(( + "DOCS_CHANGED", "FRONTEND_CHANGED", "PYTHON_CHANGED", "DESIGN_DOCS_CHANGED", + "VALIDATION_PYTHON_CHANGED", "POSTGRES_RUNTIME_PROOF_CHANGED", "OTHER_MODULES_AFFECTED", + "ACCOUNT_MODULE_AFFECTED", "GAME_SESSION_MODULE_AFFECTED", "WORLD_MODULE_AFFECTED", + ), "true") + validation_inputs["LIGHTWEIGHT_ONLY"] = "false" + for changes, helm_proof, diagnostic in ( + ("success", "success", None), + ("failure", "success", "Change detection did not succeed: failure"), + ("success", "failure", "Helm Transaction Proof => failure"), + ): + outcome = subprocess.run(["bash", "-e", "-c", step["run"]], check=False, capture_output=True, + env={**os.environ, **successful_results, **validation_inputs, + "CHANGES_RESULT": changes, "HELM_TRANSACTION_PROOF": helm_proof}, text=True) + if diagnostic is None and outcome.returncode != 0: + raise SystemExit(f"Validation enforcement rejected successful dependencies: {outcome.stderr}") + if diagnostic is not None and ( + outcome.returncode != 1 or diagnostic not in outcome.stdout + outcome.stderr + ): + raise SystemExit(f"Validation enforcement did not fail for {diagnostic}") + if workflow == "codeql.yml": + detector_condition = data["jobs"]["changes"].get("if", "") + for action, base_ref in (("edited", retarget_change), ("opened", None), ("synchronize", None), ("reopened", None)): + if not detector_condition or not evaluate(detector_condition, action, base_ref): + raise SystemExit(f"CodeQL detector must run for {action} (base change={base_ref})") + # Protected pushes rely on the same detector to start analysis. + if not evaluate(detector_condition, None, None, event="push"): + raise SystemExit("CodeQL detector must run on protected pushes") + step = result_steps[0] + if step["env"].get("SHOULD_RUN") != "${{ needs.changes.outputs.should_run }}" or \ + step["env"].get("ANALYZE_RESULT") != "${{ needs.analyze.result }}": + raise SystemExit("CodeQL enforcement must use actual detector and analyzer results") + for changes, should_run, analyze, success in ( + ("success", "true", "failure", False), + ("success", "true", "success", True), + ("success", "false", "skipped", True), + ("failure", "false", "skipped", False), + ("success", "", "skipped", False), + ): + outcome = subprocess.run(["bash", "-e", "-c", step["run"]], check=False, capture_output=True, + env={**os.environ, "CHANGES_RESULT": changes, + "SHOULD_RUN": should_run, "ANALYZE_RESULT": analyze}) + if (outcome.returncode == 0) != success: + raise SystemExit(f"CodeQL enforcement returned {outcome.returncode} for {changes}/{should_run}/{analyze}") + + # Every other job also stays idle for metadata-only edits, and none of + # them may hold a required gate name. + for job_id, job in data["jobs"].items(): + if job_id == gate_job: + continue + if can_reuse_required_name(job.get("name", job_id), {name for _, _, name, *_ in gates.values()}): + raise SystemExit(f"{workflow} job {job_id} has a possible required gate name collision") + condition = job.get("if", "") + if workflow == "runtime-images.yml" and ( + "github.event_name == 'pull_request'" not in condition or + "github.event_name != 'pull_request'" in condition or + PR_SUBSTANTIVE[1:-1] in condition + ): + # Runtime jobs serve several events; a pull_request path must carry the guard. + continue + if not excludes_metadata(condition): + raise SystemExit(f"{workflow} job {job_id} can run for a metadata-only edit") -for workflow in ("ci.yml", "security.yml", "smoke.yml"): - path = root / ".github" / "workflows" / workflow - data = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) - for job_name, job in data["jobs"].items(): - if job_name == workflows[workflow][0]: + # Metadata runs never cancel or replace the substantive run. + concurrency = data["concurrency"] + group = concurrency["group"] + suffix = "format('metadata-{0}', github.run_id) || 'required'" if run_scoped else "&& 'metadata' || 'required'" + if "github.event.pull_request.number" not in group or META.split(" && ", 1)[1] not in group or suffix not in group: + raise SystemExit(f"{workflow} concurrency group must keep metadata runs out of the PR's required namespace") + for pr_number in (42, 43, 44): + if workflow == "runtime-images.yml": + # Every PR run has its own workflow group; metadata runs stay out of the required namespace. + metadata = effective_group(group, "edited", None, workflow_name, pr_number=pr_number) + substantive = effective_group(group, "synchronize", None, workflow_name, pr_number=pr_number) + if not (metadata.endswith("-metadata-123") and substantive.endswith("-required") and metadata != substantive): + raise SystemExit(f"{workflow} PR {pr_number} effective metadata and substantive groups must differ") + continue + if not isolates_metadata_group(group, run_scoped, workflow_name, pr_number=pr_number): + raise SystemExit(f"{workflow} PR {pr_number} effective metadata and substantive groups must differ") + # The old substring guard would accept this expression despite its bypass. + bypassed = group.replace(META, "true && 'required' || " + META, 1) + assert bypassed != group and META in bypassed and suffix in bypassed + assert effective_group(bypassed, "edited", None, workflow_name) == effective_group( + bypassed, "edited", {"from": "main", "to": "develop"}, workflow_name + ), workflow + assert effective_group(bypassed, "edited", None, workflow_name).endswith("-required"), workflow + assert not isolates_metadata_group(bypassed, run_scoped, workflow_name), workflow + collided = group.replace(META, f"github.event.action == 'synchronize' || {META}", 1) + assert collided != group and not isolates_metadata_group(collided, run_scoped, workflow_name), workflow + per_run = "${{ github.run_id }}-" + group + assert not isolates_metadata_group(per_run, run_scoped, workflow_name), workflow + if workflow == "ci.yml": + split_opened = ( + "${{ github.workflow == 'CI โ€” Validation' && github.event.action == 'opened' && 'opened-' || '' }}" + + group + ) + assert isolates_metadata_group(split_opened, run_scoped, "Required Gate") + assert not isolates_metadata_group(split_opened, run_scoped, workflow_name), workflow + # Build Runtime Images queues (queue: max) and so never cancels at workflow level; + # its PR build jobs cancel the older PR build instead. + expected_cancel = "false" if workflow == "runtime-images.yml" else "true" + if concurrency.get("cancel-in-progress") != expected_cancel: + raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") + +rendered_groups = [] +workflow_data = {} +for workflow, (workflow_name, *_rest) in gates.items(): + data = yaml.load((root / ".github/workflows" / workflow).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + workflow_data[workflow] = data + group = data["concurrency"]["group"] + if data.get("name") != workflow_name: + raise SystemExit(f"{workflow} actual name must match its required-gate contract") + run_scoped = gates[workflow][-1] + for pr_number in (42, 43, 44): + for run_id in ("123", "456"): + metadata_owner = ("metadata", pr_number, run_id) if run_scoped else ("metadata", pr_number) + rendered_groups.append(( + workflow, metadata_owner, + effective_group(group, "edited", None, workflow_name, pr_number=pr_number, run_id=run_id), + )) + pr_group_owners = {} + for action, base_ref in (("opened", None), ("synchronize", None), ("reopened", None), + ("edited", {"from": "main", "to": "develop"})): + for pr_number in (42, 43, 44): + rendered = effective_group(group, action, base_ref, workflow_name, pr_number=pr_number) + prior_pr = pr_group_owners.setdefault(rendered.casefold(), pr_number) + if prior_pr != pr_number: + raise SystemExit(f"{workflow} PRs {prior_pr} and {pr_number} share concurrency group {rendered!r}") + rendered_groups.append((workflow, ("pr", pr_number), rendered)) + +required_push_branches = { + "ci.yml": ("main", "develop"), + "codeql.yml": ("main",), + "security.yml": ("main", "develop"), + "license-scan.yml": ("main", "develop"), +} +for workflow, branches in required_push_branches.items(): + triggers = workflow_data[workflow]["on"] + for branch in branches: + if "push" not in triggers or not push_branch_matches(triggers["push"] or {}, branch): + raise SystemExit(f"{workflow} must admit protected push branch {branch}") + +for branch in ("main", "develop"): + for workflow, data in workflow_data.items(): + if "push" not in data["on"]: continue - condition = job.get("if", "") if isinstance(job, dict) else "" - if metadata_guard not in condition: - raise SystemExit( - f"{workflow} job {job_name} can run for a metadata-only edited event" - ) + if not push_branch_matches(data["on"]["push"] or {}, branch): + continue + groups = [ + effective_group(data["concurrency"]["group"], None, None, data["name"], + push_branch=branch, run_id=run_id) + for run_id in ("123", "456") + ] + assert groups[0].casefold() == groups[1].casefold(), (workflow, branch, groups) + rendered_groups.append((workflow, ("push", branch), groups[0])) +missing_pr_collision = "${{ github.event.pull_request.number == null && 'protected-main' || github.ref }}" +assert effective_group(missing_pr_collision, None, None, push_branch="develop") == effective_group( + missing_pr_collision, None, None, push_branch="main" +), "missing push PR context must expose a cross-branch collision" +collisions = concurrency_group_collisions(rendered_groups) +if collisions: + first, second = collisions[0] + raise SystemExit( + f"{first[0]} {first[1]} and {second[0]} {second[1]} share a " + f"concurrency group (case-insensitive): {first[2]!r} / {second[2]!r}" + ) +assert concurrency_group_collisions([ + ("ci.yml", ("pr", 42), "required-pr-42"), + ("runtime-images.yml", ("pr", 42), "REQUIRED-PR-42"), +]), "the collision detector must model GitHub's case-insensitive group comparison" +assert concurrency_group_collisions([ + ("ci.yml", ("pr", 42), "required-pr-42"), + ("ci.yml", ("push", "develop"), "required-pr-42"), +]), "a push and PR in the same workflow cannot replace each other" +assert concurrency_group_collisions([ + ("ci.yml", ("metadata", 42, "123"), "pr-42-metadata-123"), + ("runtime-images.yml", ("push", "develop"), "PR-42-METADATA-123"), +]), "a metadata edit cannot share another workflow's protected-push group" +assert not concurrency_group_collisions([ + ("ci.yml", ("pr", 42), "required-pr-42"), + ("ci.yml", ("pr", 42), "REQUIRED-PR-42"), +]), "substantive events of the same PR may share its concurrency group" PY # shellcheck disable=SC2016 # Match the checked-in arithmetic assignment literally. @@ -491,410 +1176,6 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT -# The Smoke consumer must outlive its producer and still terminate fail closed. -smoke_clock_fixture="$tmp_dir/smoke-clock.js" -python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' -from pathlib import Path -import base64 -import hashlib -import json -import re -import sys -import yaml - -root = Path(sys.argv[1]) -smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) -producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) -job = smoke["jobs"]["smoke-gate"] -script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") -producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) -overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) -if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): - raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") -if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: - raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") -if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: - raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") -fingerprint = re.search(r'const canonicalRuntimeWorkflowSha256 = "([0-9a-f]{64})";', script) -expected = hashlib.sha256((root / ".github/workflows/runtime-images.yml").read_bytes()).hexdigest() -if fingerprint is None or fingerprint[1] != expected: - raise SystemExit( - "Smoke Gate producer fingerprint is stale: after reviewing runtime-images.yml, update " - f"canonicalRuntimeWorkflowSha256 in smoke.yml to {expected} and rerun this contract." - ) -classifier_paths = ( - "dev-tools/verify-smoke-images.sh", - "dev-tools/smoke/smoke_common.py", - "services/game-session-service/websocket-login-look-smoke.sh", - "dev-tools/smoke/demo-smoke-defaults.sh", - "dev-tools/smoke/held-admission-qualification.sh", - "dev-tools/smoke/held_admission_qualification.py", - "dev-tools/smoke/run-owned-compose.sh", - "dev-tools/certs/ensure-dev-certs.sh", - ".env.sample", - "docker/docker-compose.yml", - "docker/docker-compose.override.yml", - "docker/docker-compose.smoke-images.override.yml", - "docker/docker-compose.pr-local-minio.override.yml", - "docker/docker-compose.grpc-mtls.override.yml", -) -classifier_fingerprints = re.search(r"const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});", script) -if classifier_fingerprints is None: - raise SystemExit("Smoke Gate must fingerprint the canonical PLAY classifier files") -classifiers = json.loads(classifier_fingerprints[1]) -if set(classifiers) != set(classifier_paths): - raise SystemExit("Smoke Gate PLAY classifier fingerprint paths must match the canonical classifier, qualification, cleanup, and configuration inputs") -classifier_definitions = {} -for path in classifier_paths: - classifier_bytes = (root / path).read_bytes() - expected = hashlib.sha256(classifier_bytes).hexdigest() - if classifiers[path] != expected: - raise SystemExit( - f"Smoke Gate PLAY classifier fingerprint is stale: after reviewing {path}, update " - f"canonicalPlayClassifierSha256 in smoke.yml to {expected} for that path and rerun this contract." - ) - classifier_definitions[path] = { - "type": "file", "path": path, "encoding": "base64", - "content": base64.b64encode(classifier_bytes).decode("ascii"), "size": len(classifier_bytes), - } -Path(sys.argv[2] + ".classifiers.json").write_text(json.dumps(classifier_definitions)) -producer_job = producer["jobs"]["pr-local-smoke"] -if producer["jobs"]["image-meta"]["outputs"].get("canonical_play_transition") != "${{ steps.meta.outputs.canonical_play_transition }}": - raise SystemExit("Typed-refresh PLAY marker authority must come from verified image metadata") -cancelled_inventory = re.search( - r"const preExecutionCancelledJobNames = new Set\(\[([\s\S]*?)\]\);", script -) -if cancelled_inventory is None: - raise SystemExit("Smoke Gate must declare its bounded pre-execution cancellation inventory") -producer_job_names = [job["name"] for job in producer["jobs"].values()] -Path(sys.argv[2] + ".cancelled-job-names.json").write_text(json.dumps(producer_job_names)) -if producer_job["name"] != "PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }})": - raise SystemExit("Native producer name must affirm runtime smoke scope") -steps = producer_job["steps"] -smoke_step = next(step for step in steps if step.get("id") == "runtime-smoke") -cleanup_step = next(step for step in steps if step.get("id") == "runtime-cleanup") -guard = steps[-1] -if smoke_step.get("continue-on-error") != "true": - raise SystemExit("Probe failure must reach the exact transition terminal guard") -if any(step.get("continue-on-error") not in (None, "false") for step in (cleanup_step, guard)): - raise SystemExit("Cleanup and terminal enforcement cannot ignore failures") -for name in ("Export fixed-tag preview image artifact", "Upload preview image artifact", "Summarize secure PR runtime artifact"): - artifact = next(step for step in steps if step.get("name") == name) - if artifact.get("if") != "${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }}": - raise SystemExit("Failed probe must never export, upload or summarize publishable images") -if smoke_step["run"] != "bash ./dev-tools/verify-smoke-images.sh --keep-running": - raise SystemExit("Native smoke outcome must belong to the canonical smoke invocation") -if guard["if"] != "${{ always() }}" or guard["name"] != "Require successful runtime smoke and authenticated cleanup": - raise SystemExit("Producer must finish with its mandatory always terminal guard") -if guard["env"] != { - "RUNTIME_SMOKE_REQUIRED": "${{ needs.image-meta.outputs.runtime_smoke_required }}", - "RUNTIME_SMOKE_OUTCOME": "${{ steps.runtime-smoke.outcome }}", - "RUNTIME_CLEANUP_OUTCOME": "${{ steps.runtime-cleanup.outcome }}", - "KNOWN_PLAY_EXCEPTION_OUTCOME": "${{ steps.canonical-play-transition.outcome }}", -}: - raise SystemExit("Terminal guard must consume native Actions outcomes, never command-written outputs") -Path(sys.argv[2] + ".guard").write_text(guard["with"]["script"]) -marker = next(step for step in steps if step.get("name") == "Known canonical transition PLAY failure with successful authenticated cleanup") -for clause in ( - "always()", "github.event_name == 'pull_request'", "github.repository == 'benhook1013/FireMUD'", - "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", "needs.image-meta.outputs.runtime_smoke_required == 'true'", - "github.event_name == 'repository_dispatch'", "github.event.action == 'pr-runtime-base-refresh'", - "needs.image-meta.outputs.canonical_play_transition == 'true'", - "steps.runtime-smoke.outcome == 'failure'", "steps.runtime-cleanup.outcome == 'success'", - "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", -): - if clause not in marker["if"]: - raise SystemExit(f"Temporary PLAY marker lacks fail-closed clause: {clause}") -Path(sys.argv[2] + ".marker").write_text(marker["if"]) -Path(sys.argv[2] + ".producer").write_bytes((root / ".github/workflows/runtime-images.yml").read_bytes()) -Path(sys.argv[2]).write_text(script) -PY - -node - "$smoke_clock_fixture" <<'NODE' -const assert = require("node:assert/strict"); -const script = require("node:fs").readFileSync(process.argv[2], "utf8"); -const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); -const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; -const cancellationInventoryBody = script.match(/const preExecutionCancelledJobNames = new Set\(\[([\s\S]*?)\]\);/)[1]; -const cancellationInventory = new Function(`return [${cancellationInventoryBody}];`)(); -const canonicalCancellationInventory = JSON.parse(require("node:fs").readFileSync(process.argv[2] + ".cancelled-job-names.json", "utf8")); -assert.equal(cancellationInventory.length, 13); -assert.deepEqual([...cancellationInventory].sort(), canonicalCancellationInventory.sort(), - "bounded cancellation inventory must match all canonical runtime workflow job names"); -const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, - payload: { pull_request: { number: 42, head: { sha: head, repo: {full_name: "example/firemud"}}, - base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; -const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); -async function scenario(outcome, completedAtMinutes, selectionCase = "single") { - let now = 1000; - const start = now; - const failures = []; - const listRuns = async () => {}, listJobs = async () => {}; - const cancelledSource = runId => ({id: runId, workflow_id: 7, run_attempt: 1, event: "pull_request", - status: "completed", conclusion: "cancelled", path: ".github/workflows/runtime-images.yml", - repository: {full_name: "example/firemud"}, head_repository: {full_name: "example/firemud"}, - head_sha: head, display_title: title}); - const cancellationJobs = runId => { - if (selectionCase === "cancelled-empty-inventory") return []; - const names = selectionCase === "cancelled-partial-inventory" ? cancellationInventory.slice(1) : cancellationInventory; - return names.map((name, index) => ({id: runId * 100 + index + 1, run_id: runId, - name, - status: "completed", conclusion: selectionCase === "cancelled-unknown-outcome" && index === 0 - ? "failure" : index % 2 === 0 ? "cancelled" : "skipped", - steps: selectionCase === "cancelled-executed" && index === 0 ? [{name: "executed"}] : []})); - }; - const github = { rest: { - pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, - repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, - actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, - getWorkflow: async () => ({data: {id: 7, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), - getWorkflowRun: async ({run_id}) => ({data: {id: run_id, - run_attempt: selectionCase === "cancelled-changed-attempt" ? 2 : 1, - status: "completed", conclusion: "cancelled"}}) }, - }, request: async (route, input) => { - assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); - assert.equal(input.attempt_number, 1); - return {data: cancelledSource(input.run_id)}; - }, paginate: async (method, input) => { - if (method === listJobs) { - return [{ id: input.run_id + 100, run_id: input.run_id, name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", - steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; - } - assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); - return cancellationJobs(input.run_id); - } }; - github.paginate.iterator = async function* (method, input) { - assert.equal(method, listRuns); - assert.equal(input.workflow_id, "runtime-images.yml"); - if (input.event === "repository_dispatch") { yield { data: [] }; return; } - assert.equal(input.head_sha, head); - const complete = now - start >= completedAtMinutes * 60 * 1000; - const makeRun = (id, createdAt, status, conclusion) => ({id, workflow_id: 7, run_attempt: 1, - event: "pull_request", head_sha: head, display_title: title, created_at: createdAt, - pull_requests: [{number: 42, head: {sha: head}}], status, conclusion}); - const active = makeRun(42, "2026-09-01T00:00:00Z", complete ? "completed" : "in_progress", complete ? outcome : null); - const cancelled = makeRun(43, "2026-09-01T00:00:00Z", "completed", "cancelled"); - if (selectionCase === "duplicate" || selectionCase === "cancelled-higher-id") { - yield { data: selectionCase === "duplicate" ? [ - {...active, status: "completed", conclusion: "cancelled"}, {...active, id: 43}, - ] : [cancelled, active] }; - return; - } - if (selectionCase === "newer-failure-over-success") { - yield {data: [ - makeRun(42, "2026-09-01T00:00:00Z", "completed", "success"), - makeRun(43, "2026-09-01T00:00:01Z", "completed", "failure"), - ]}; - return; - } - if (selectionCase === "newer-pending-over-success") { - yield {data: [ - makeRun(42, "2026-09-01T00:00:00Z", "completed", "success"), - makeRun(43, "2026-09-01T00:00:01Z", complete ? "completed" : "in_progress", complete ? outcome : null), - ]}; - return; - } - if (["cancelled-executed", "cancelled-partial-inventory", "cancelled-empty-inventory", - "cancelled-unknown-outcome", "cancelled-changed-attempt", "cancelled-older-success"].includes(selectionCase)) { - yield {data: [ - makeRun(42, "2026-09-01T00:00:00Z", "completed", "success"), - makeRun(43, "2026-09-01T00:00:01Z", "completed", "cancelled"), - ]}; - return; - } - if (selectionCase === "wrong-tuple-event") { - yield { data: [ - {...active, id: 99, event: "push", status: "completed", conclusion: "failure"}, - {...active, id: 98, head_sha: "f".repeat(40), status: "completed", conclusion: "failure"}, - active, - ] }; - return; - } - yield { data: [makeRun(42, "2026-09-01T00:00:00Z", - complete ? "completed" : "in_progress", complete ? outcome : null)] }; - }; - const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; - const clock = { now: () => now, parse: Date.parse }; - const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; - await execute(github, context, core, clock, sleep); - return { failures, minutes: (now - start) / 60000 }; -} -(async () => { - const success = await scenario("success", 30); - assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); - assert.equal(success.minutes, 30); - const failed = await scenario("failure", 30); - assert.equal(failed.failures.length, 1); - assert.match(failed.failures[0], /did not complete successfully/); - assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); - const replacement = await scenario("success", 1, "duplicate"); - assert.deepEqual(replacement.failures, [], "newer same-time exact run must replace older cancelled run despite API order"); - assert.equal(replacement.minutes, 1, "newer in-progress run must be tracked until it succeeds"); - const oppositeIdOrdering = await scenario("success", 0, "cancelled-higher-id"); - assert.deepEqual(oppositeIdOrdering.failures, [], "pre-execution cancellation must not hide a same-time lower-ID active run"); - const newerPending = await scenario("success", 1, "newer-pending-over-success"); - assert.deepEqual(newerPending.failures, [], "newer pending run must remain authoritative over older success until it completes"); - assert.equal(newerPending.minutes, 1); - const newerFailure = await scenario("failure", 0, "newer-failure-over-success"); - assert.equal(newerFailure.failures.length, 1); - assert.match(newerFailure.failures[0], /did not complete successfully/, - "newer exact failure must remain authoritative over older success"); - for (const kind of ["cancelled-executed", "cancelled-partial-inventory", "cancelled-empty-inventory", - "cancelled-unknown-outcome", "cancelled-changed-attempt"]) { - const unsafeCancellation = await scenario("success", 0, kind); - assert.equal(unsafeCancellation.failures.length, 1, `${kind} cannot be excluded to reveal older success`); - assert.ok(unsafeCancellation.minutes <= 5.25, `${kind} remains bounded while replacement is absent`); - } - const olderSuccess = await scenario("success", 0, "cancelled-older-success"); - assert.deepEqual(olderSuccess.failures, [], "only a complete no-step cancellation may be excluded from authority"); - const ignoredDistractors = await scenario("success", 0, "wrong-tuple-event"); - assert.deepEqual(ignoredDistractors.failures, [], "wrong-event and wrong-head runs must not displace the exact run"); - const cancelled = await scenario("cancelled", 0); - assert.equal(cancelled.failures.length, 1); - assert.match(cancelled.failures[0], /cancelled/i); - assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); - const deadline = await scenario("success", Infinity); - assert.equal(deadline.failures.length, 1); - assert.match(deadline.failures[0], /Timed out waiting for the exact/); - assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); - console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); -})().catch(error => { console.error(error); process.exitCode = 1; }); -NODE - -node - "$smoke_clock_fixture" "$ROOT_DIR/.github/workflows/runtime-images.yml" <<'NODE' -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const script = fs.readFileSync(process.argv[2], "utf8"); -const definition = fs.readFileSync(process.argv[3]); -const guard = new Function("process", "core", fs.readFileSync(process.argv[2] + ".guard", "utf8")); -for (const smoke of ["success", "failure", "skipped", "cancelled", "unknown", ""]) { - for (const cleanup of ["success", "failure", "skipped", "cancelled", "unknown", ""]) { - const failures = []; - guard({env: {RUNTIME_SMOKE_REQUIRED: "true", RUNTIME_SMOKE_OUTCOME: smoke, RUNTIME_CLEANUP_OUTCOME: cleanup}}, - {setFailed: message => failures.push(message)}); - assert.equal(failures.length === 0, smoke === "success" && cleanup === "success"); - } -} -for (const required of ["false", "", "unknown"]) { - const failures = []; - guard({env: {RUNTIME_SMOKE_REQUIRED: required}}, {setFailed: message => failures.push(message)}); - assert.equal(failures.length === 0, required === "false"); -} -for (const smoke of ["success", "failure", "skipped", "cancelled", ""]) { - for (const cleanup of ["success", "failure", "skipped", "cancelled", ""]) { - for (const marker of ["success", "failure", "skipped", ""]) { - const failures = [], warnings = []; - guard({env: {RUNTIME_SMOKE_REQUIRED: "true", RUNTIME_SMOKE_OUTCOME: smoke, - RUNTIME_CLEANUP_OUTCOME: cleanup, KNOWN_PLAY_EXCEPTION_OUTCOME: marker}}, - {setFailed: message => failures.push(message), warning: message => warnings.push(message)}); - const exception = smoke === "failure" && marker === "success" && cleanup === "success"; - assert.equal(failures.length === 0, cleanup === "success" && (smoke === "success" || exception)); - assert.equal(warnings.length, Number(exception)); - } - } -} -const execute = new Function("github", "context", "core", "Date", "setTimeout", "require", `return (async () => {\n${script}\n})()`); -const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40), defaultSha = "d".repeat(40); -const repository = "example/firemud"; -const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; -async function scenario(kind, event = "pull_request") { - let now = 1000, snapshots = 0, reads = 0; - const failures = [], refs = []; - const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { - repository: {default_branch: "develop"}, - pull_request: {number: 42, head: {sha: head, repo: {full_name: repository}}, - base: {ref: "develop", sha: base}, created_at: "2026-09-01T00:00:00Z"}, - }}; - const source = {id: 42, workflow_id: 7, run_attempt: 1, repository: {full_name: repository}, - created_at: "2026-09-01T00:00:00Z", - head_repository: {full_name: repository}, path: ".github/workflows/runtime-images.yml", - event, head_sha: event === "pull_request" ? head : defaultSha, head_branch: "develop", display_title: title, - status: "completed", conclusion: "success", pull_requests: []}; - const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, - check_run_url: `https://api.github.com/repos/${repository}/check-runs/100`, - name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", - steps: [{name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", conclusion: "skipped"}]}; - if (kind === "marker-missing") job.steps = []; - if (kind === "marker-success") job.steps[0].conclusion = "success"; - if (kind.startsWith("legacy")) job.name = "PR Full-Stack Smoke"; - if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; - if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; - if (kind === "legacy-positive") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]; - const sourceMutations = { - "wrong-repository": {repository: {full_name: "other/repo"}}, - "wrong-workflow": {workflow_id: 8}, "wrong-path": {path: ".github/workflows/fake.yml"}, - "wrong-event": {event: "push"}, "wrong-head": {head_sha: "e".repeat(40)}, - "wrong-head-repository": {head_repository: {full_name: "other/repo"}}, - "wrong-title": {display_title: title + " unrelated"}, "wrong-source-attempt": {run_attempt: 2}, - "wrong-dispatch-branch": {head_branch: "feature"}, - }; - const listRuns = async () => {}, listJobs = async () => {}; - const github = {rest: { - pulls: {get: async () => { - reads += 1; - return {data: {state: "open", head: {sha: head}, base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: base}, merge_commit_sha: merge}}; - }}, - repos: { - getCommit: async ({ref}) => ({data: {sha: ref, parents: [{sha: kind === "bad-parents" ? defaultSha : base}, {sha: head}]}}), - getContent: async ({ref, path}) => { - refs.push(ref); - assert.equal(path, source.path); - if (kind === "unavailable-definition") throw Object.assign(new Error("definition unavailable"), {status: 404}); - const bytes = kind === "changed-definition" ? Buffer.concat([definition, Buffer.from("\n# altered")]) : definition; - return {data: {type: "file", path, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}; - }, - }, - actions: { - listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, - getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), - getWorkflowRun: async () => ({data: {...source, run_attempt: kind === "newer-attempt" ? 2 : 1}}), - }, - }, request: async (route, input) => { - assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); - assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); - return {data: {...source, ...(sourceMutations[kind] || {})}}; - }, paginate: async (method, input) => { - if (method === listJobs) { snapshots += 1; return kind === "duplicate-jobs" ? [job, {...job, id: 101}] : [job]; } - assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); - assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); - const mutations = { - "wrong-job": {id: 101}, "wrong-job-run": {run_id: 43}, "wrong-job-attempt": {run_attempt: 2}, - "wrong-job-head": {head_sha: defaultSha}, "wrong-check-url": {check_run_url: "https://example.com/check"}, - "failed-job": {conclusion: "failure"}, "pending-job": {status: "in_progress", conclusion: null}, - }; - return kind === "duplicate-attempt-jobs" ? [job, {...job, id: 101}] : [{...job, ...(mutations[kind] || {})}]; - }}; - github.paginate.iterator = async function* (method, input) { - assert.equal(method, listRuns); - if (event === "repository_dispatch" && input.event === "pull_request") { - yield {data: [{...source, event: "pull_request", head_sha: head, conclusion: "cancelled"}]}; return; - } - yield {data: [source]}; - }; - const clock = {now: () => now, parse: Date.parse}; - await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, - clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots}; -} -(async () => { - for (const event of ["pull_request", "repository_dispatch"]) { - const success = await scenario("success", event); - assert.deepEqual(success.failures, []); - assert.deepEqual(success.refs, [event === "pull_request" ? merge : defaultSha], "immutable definition must come from actual source event revision"); - } - assert.deepEqual((await scenario("legacy-positive")).failures, []); - for (const kind of ["marker-missing", "marker-success", "legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", - "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", - "changed-definition", "unavailable-definition", "wrong-job", "wrong-job-run", "wrong-job-attempt", "wrong-job-head", - "wrong-check-url", "failed-job", "pending-job", "duplicate-jobs", "duplicate-attempt-jobs", "newer-attempt", "bad-parents"]) { - assert.equal((await scenario(kind)).failures.length, 1, `${kind} must not supply successful proof`); - } - assert.equal((await scenario("wrong-dispatch-branch", "repository_dispatch")).failures.length, 1); - const stale = await scenario("stale-final"); - assert.deepEqual(stale.failures, [], "obsolete gate exits without publishing proof for changed base ref"); - console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); -})().catch(error => {console.error(error); process.exitCode = 1;}); -NODE cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash @@ -2044,7 +2325,7 @@ assert "PRESERVATION_MODE" not in action["runs"]["steps"][-1]["env"] assert action["outputs"]["assessment"]["value"] == "${{ steps.preserve.outputs.assessment }}" assert workflow["on"]["workflow_run"]["types"] == ["completed"] assert set(workflow["on"]["workflow_run"]["workflows"]) == { - "CI โ€” Validation", "Security Gate", "CodeQL Analysis", "License Gate", "PR Smoke Gate", + "CI โ€” Validation", "Security Gate", "CodeQL Analysis", "License Gate", "Build Runtime Images", } assert workflow["concurrency"] == { "group": "required-gate-resolution-${{ github.event.workflow_run.workflow_id }}-${{ github.event.workflow_run.head_sha }}", @@ -3265,7 +3546,7 @@ callers = ( ("security.yml", "security-gate", "Security Gate", "Security Gate"), ("codeql.yml", "codeql-gate", "CodeQL Gate", "CodeQL Analysis"), ("license-scan.yml", "license-gate", "License Gate", "License Gate"), - ("smoke.yml", "smoke-gate", "Smoke Gate", "PR Smoke Gate"), + ("runtime-images.yml", "smoke-gate", "Smoke Gate", "Build Runtime Images"), ) for filename, job_id, gate, workflow_name in callers: data = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) @@ -3595,287 +3876,3 @@ done echo "Required-gate status producer contract checks passed" -# Exercise the temporary failed-producer verifier separately: passing producer -# proof above is unchanged and remains the only runtime qualification path. -node - "$smoke_clock_fixture" "$ROOT_DIR/.github/workflows/smoke.yml" <<'NODE' -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const script = fs.readFileSync(process.argv[2], "utf8"); -const icons = [...fs.readFileSync(process.argv[3], "utf8").matchAll(/const statusIcon = \(value\) => \{[\s\S]*?\n\s*\};/g)]; -assert.equal(icons.length, 2); -for (const [declaration] of icons) { - const statusIcon = new Function(`${declaration}; return statusIcon;`)(); - assert.equal(statusIcon("failure (known temporary PLAY exception)"), "โŒ"); - assert.equal(statusIcon("failure"), "โŒ"); - assert.equal(statusIcon("success"), "โœ…"); - assert.equal(statusIcon("cancelled"), "โšช"); - assert.equal(statusIcon("skipped"), "โญ๏ธ"); -} -const bytes = fs.readFileSync(process.argv[2] + ".producer"); -const start = script.indexOf("function isSuccessfulRuntimeWorkflowDefinition("); -const end = script.indexOf("// Commit objects", start); -const fn = script.slice(start, end); -const workflowPath = ".github/workflows/runtime-images.yml"; -const repositoryName = "benhook1013/FireMUD"; -const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; -const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); -const preMergeRefreshBytes = Buffer.concat([bytes, Buffer.from("\n# Current default trusted refresh definition\n")]); -const canonicalPreMergeTrustedRefreshRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256") - .update(preMergeRefreshBytes).digest("hex"); -const previousRefreshBytes = Buffer.concat([bytes, Buffer.from("\n# Previous trusted refresh definition\n")]); -const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256") - .update(previousRefreshBytes).digest("hex"); -// Separate test authority lets the same verifier exercise both immutable modes. -const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); -const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); -const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".classifiers.json", "utf8")); -const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); -const workflowSha = "d".repeat(40); -const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; -const run = {id: 99, run_attempt: 2, event: "pull_request"}; -const failures = ["Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup"]; -const step = (name, conclusion) => ({name, conclusion, status: "completed"}); -const source = {...run, status: "completed", conclusion: "success", path: workflowPath, - repository: {full_name: repositoryName}, workflow_id: 7, head_repository: {full_name: repositoryName}, head_sha: headSha, - display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${baseSha} head-${headSha} merge-${mergeSha} mode-required`}; -const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: canonicalSmokeJobName, - status: "completed", conclusion: "success", check_run_url: `https://api.github.com/repos/${repositoryName}/check-runs/123`, - steps: [...failures.map(name => step(name, "success")), step("Stop smoke stack", "success"), - step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), - step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; -async function verify(mutate = () => {}, event = "pull_request", knownPlay = true) { - const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, - eventHeadRepository: repositoryName, - currentPullRequest: {state: "open", head: {sha: headSha, repo: {full_name: repositoryName}}, - base: {ref: "develop", repo: {full_name: repositoryName}}, merge_commit_sha: mergeSha, - labels: [{name: "canonical-play-transition"}]}, - currentBase: {ref: "refs/heads/develop", object: {sha: baseSha}}, - definitions: {...classifierDefinitions, - [workflowPath]: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}}); - if (event === "repository_dispatch") { - data.run.event = data.source.event = data.latest.event = event; - data.source.head_branch = data.latest.head_branch = "develop"; - data.source.head_sha = data.latest.head_sha = workflowSha; - data.candidate.head_sha = data.jobs[0].head_sha = workflowSha; - } - if (!knownPlay) { - data.candidate.steps.find(step => step.name === - "Known canonical transition PLAY failure with successful authenticated cleanup").conclusion = "skipped"; - } - mutate(data); - const contentRequests = []; - const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, - rest: {actions: {getWorkflow: async () => ({data: {id: 7, path: workflowPath, name: "Build Runtime Images"}}), - getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, - git: {getRef: async ({ref}) => {assert.equal(ref, `heads/${data.identity.baseRef}`); return {data: data.currentBase};}}, - repos: {getContent: async ({owner, repo, path, ref}) => { - assert.equal(`${owner}/${repo}`, repositoryName); - assert.equal(ref, path === workflowPath && event === "repository_dispatch" ? workflowSha : mergeSha, - "workflow attestation must use its executed revision; classifier attestation must use the verified merge"); - contentRequests.push(path); - if (!data.definitions[path]) throw Object.assign(new Error("definition unavailable"), {status: 404}); - return {data: data.definitions[path]}; - }}}}; - const verifier = knownPlay ? "verifyKnownPlayFailure" : "verifyCanonicalSmokeProducer"; - const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", - "canonicalRuntimeWorkflowSha256", "canonicalPreMergeTrustedRefreshRuntimeWorkflowSha256", - "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", - `${fn}; return ${verifier}(data.run, data.candidate, data.identity);`)( - github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, - canonicalPreMergeTrustedRefreshRuntimeWorkflowSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, - data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, - value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), - {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, - "benhook1013", "FireMUD", require, data); - if (accepted) assert.deepEqual(contentRequests, knownPlay ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); - return accepted; -} -// Proof errors in a successful exception attempt must fail closed. -const failedStart = script.indexOf('// A continued probe'); -const failedEnd = script.indexOf('if (fullSmokeJob?.conclusion !== "success")', failedStart); -const failedBranch = script.slice(failedStart, failedEnd); -class TerminalGitHubRequestError extends Error {} -async function failedProof(error, event = "pull_request") { - const warnings = [], failures = [], outputs = []; - const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), - setOutput: (...value) => outputs.push(value)}; - const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", - "verifyKnownPlayFailure", "TerminalGitHubRequestError", "core", - `return (async () => { smokeGatePolling: while (true) { ${failedBranch} break; } })();`); - await execute(candidate, {...source, event}, canonicalSmokeJobName, identity, - async () => {throw error;}, TerminalGitHubRequestError, core); - assert.deepEqual(failures, ["Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."]); - assert.equal(warnings.length, 1); - assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); - assert.deepEqual(outputs, []); -} -// Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. -const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); -const legacyFailedEnd = script.indexOf("const latestIdentity", legacyFailedStart); -const legacyFailedBranch = script.slice(legacyFailedStart, legacyFailedEnd); -async function failedLegacyProof(stage, error, event = "pull_request") { - const warnings = [], failures = [], outputs = []; - const github = {paginate: async () => { - if (stage === "jobs") throw error; - return stage === "malformed-jobs" ? {} : [candidate]; - }}; - const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), - setOutput: (...value) => outputs.push(value)}; - const execute = new Function("matching", "repositoryName", "github", "owner", "repo", - "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", - "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", - `return (async () => { smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); - await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, - identity, (_label, call) => call(), async () => {throw error;}, async () => false, - TerminalGitHubRequestError, core); - assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); - assert.equal(warnings.length, 1); - assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); - assert.deepEqual(outputs, []); -} -const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); -const markerValues = { - "github.event_name": "pull_request", "github.repository": repositoryName, - "github.event.action": "pr-runtime-base-refresh", - "github.event.pull_request.labels.*.name": ["canonical-play-transition"], - "needs.image-meta.outputs.canonical_play_transition": "false", - "needs.image-meta.outputs.runtime_smoke_required": "true", - "steps.runtime-smoke.outcome": "failure", "steps.runtime-smoke.outputs.known_play_failure": "direct-backend-play-entitlement-unavailable-after-login", - "steps.runtime-cleanup.outcome": "success", -}; -function markerAccepted(overrides = {}) { - let expression = markerExpression.replace("always()", "true") - .replace("contains(", "includes("); - for (const [key, value] of Object.entries({...markerValues, ...overrides})) { - expression = expression.replaceAll(key, JSON.stringify(value)); - } - return new Function("includes", `return (${expression});`)((values, value) => values.includes(value)); -} -(async () => { - for (const event of ["pull_request", "repository_dispatch"]) { - for (const stage of ["jobs", "proof", "malformed-jobs"]) { - await failedLegacyProof(stage, Object.assign(new Error("unavailable"), {status: 404}), event); - } - } - await failedLegacyProof("proof", null); - for (const event of ["pull_request", "repository_dispatch"]) { - await failedProof(Object.assign(new Error("unavailable"), {status: 404}), event); - await failedProof(null, event); - } - for (const stage of ["jobs", "proof"]) { - const terminal = new TerminalGitHubRequestError("permission denied"); - await assert.rejects(failedLegacyProof(stage, terminal), error => error === terminal); - await assert.rejects(failedProof(terminal), error => error === terminal); - } - assert.equal(markerAccepted(), true); - const refreshMarker = {"github.event_name": "repository_dispatch", - "github.event.pull_request.labels.*.name": [], "needs.image-meta.outputs.canonical_play_transition": "true"}; - assert.equal(markerAccepted(refreshMarker), true); - for (const overrides of [ - {"github.event.action": "other"}, {"needs.image-meta.outputs.canonical_play_transition": "false"}, - {"needs.image-meta.outputs.canonical_play_transition": ""}, {"steps.runtime-cleanup.outcome": "failure"}, - {"steps.runtime-smoke.outputs.known_play_failure": ""}, {"steps.runtime-smoke.outcome": "success"}, - {"needs.image-meta.outputs.runtime_smoke_required": "false"}, {"github.repository": "attacker/FireMUD"}, - ]) assert.equal(markerAccepted({...refreshMarker, ...overrides}), false); - for (const overrides of [ - {"steps.runtime-smoke.outputs.known_play_failure": ""}, - {"steps.runtime-smoke.outputs.known_play_failure": "malformed"}, - {"steps.runtime-smoke.outcome": "success"}, - {"steps.runtime-cleanup.outcome": "failure"}, - {"steps.runtime-cleanup.outcome": "skipped"}, - {"needs.image-meta.outputs.runtime_smoke_required": "false"}, - {"github.event.pull_request.labels.*.name": []}, - {"github.repository": "attacker/FireMUD"}, - {"github.event_name": "repository_dispatch"}, - {"github.event_name": "workflow_run"}, - ]) assert.equal(markerAccepted(overrides), false); - assert.equal(await verify(), true); - for (const event of ["pull_request", "repository_dispatch"]) { - assert.equal(await verify(d => { - d.legacyDefinition = true; - d.source.conclusion = d.latest.conclusion = d.candidate.conclusion = "failure"; - for (const step of d.candidate.steps) if (failures.includes(step.name)) step.conclusion = "failure"; - }, event), true, "exact old fail-red default-branch producer remains a diagnostic exception only"); - } - assert.equal(await verify(() => {}, "repository_dispatch"), true); - const usePreMergeRefresh = data => Object.assign(data.definitions[workflowPath], { - content: preMergeRefreshBytes.toString("base64"), size: preMergeRefreshBytes.length, - }); - assert.equal(await verify(usePreMergeRefresh, "repository_dispatch", false), true, - "normal trusted refresh accepts the immutable pre-merge default producer"); - const usePreviousRefresh = data => Object.assign(data.definitions[workflowPath], { - content: previousRefreshBytes.toString("base64"), size: previousRefreshBytes.length, - }); - for (const knownPlay of [true, false]) { - assert.equal(await verify(usePreviousRefresh, "repository_dispatch", knownPlay), true, - "trusted refresh may retain the previous successful producer proof"); - assert.equal(await verify(usePreviousRefresh, "pull_request", knownPlay), false, - "the previous successful definition cannot attest a PR producer"); - } - for (const path of Object.keys(classifierDefinitions)) { - assert.equal(await verify(d => { - const altered = Buffer.concat([Buffer.from(d.definitions[path].content, "base64"), Buffer.from("\n# altered classifier\n")]); - d.definitions[path].content = altered.toString("base64"); - d.definitions[path].size = altered.length; - }), false, `altered classifier bytes must fail closed: ${path}`); - for (const change of [ - {type: "dir"}, {path: "other-classifier"}, {encoding: "none"}, {content: null}, {size: 0}, - ]) assert.equal(await verify(d => {Object.assign(d.definitions[path], change);}), false, `${path}: ${JSON.stringify(change)}`); - await assert.rejects(verify(d => {delete d.definitions[path];}), /definition unavailable/); - } - for (const stackPr of [3405, 3409, 3407, 3408, 3410]) { - assert.equal(await verify(d => {d.pr = String(stackPr); d.source.display_title = d.source.display_title.replace("pr-3390", `pr-${stackPr}`);}), true); - } - for (const mutate of [ - d => {d.pr = "3391";}, - d => {d.consumerRepository = "attacker/FireMUD";}, - d => {d.currentPullRequest.labels = [];}, - d => {d.currentPullRequest.labels = [{name: "other"}];}, - d => {d.currentPullRequest.state = "closed";}, - d => {d.currentPullRequest.head.sha = "e".repeat(40);}, - d => {d.currentPullRequest.head.repo.full_name = "attacker/FireMUD";}, - d => {d.currentPullRequest.base.repo.full_name = "attacker/FireMUD";}, - d => {d.eventHeadRepository = "fork-owner/FireMUD"; d.source.head_repository.full_name = d.eventHeadRepository;}, - d => {d.currentPullRequest.base.ref = "main";}, - d => {d.identity.baseSha = "d".repeat(40);}, - d => {d.identity.headSha = "d".repeat(40);}, - d => {d.identity.mergeSha = "d".repeat(40);}, - d => {d.run.event = "workflow_dispatch";}, - d => {d.source.event = "workflow_run";}, - d => {d.source.run_attempt = 1;}, - d => {d.latest.run_attempt = 3; assert.equal(d.source.run_attempt, 2);}, - d => {d.latest.conclusion = "failure"; assert.equal(d.source.conclusion, "success");}, - d => {d.source.path = ".github/workflows/spoof.yml";}, - d => {d.source.repository.full_name = "attacker/FireMUD";}, - d => {d.definitions[workflowPath].content = Buffer.from("spoof").toString("base64"); d.definitions[workflowPath].size = 5;}, - d => {d.jobs.push({...d.candidate, id: 124});}, - d => {d.jobs.push({id: 2, status: "completed", conclusion: "failure"});}, - d => {d.jobs[0].steps.push(step("Unrelated failure", "failure"));}, - d => {d.jobs[0].steps.find(s => s.name === "Stop smoke stack").conclusion = "failure";}, - d => {d.jobs[0].steps.find(s => s.name.startsWith("Known canonical transition")).conclusion = "skipped";}, - d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Known canonical transition"));}, - d => {d.jobs[0].steps.find(s => s.name.startsWith("Export fixed")).conclusion = "success";}, - d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Export fixed"));}, - d => {d.source.conclusion = "failure";}, - d => {d.jobs[0].steps.find(s => s.name === "Run credential-free full-stack smoke").conclusion = "failure";}, - d => {d.jobs[0].steps.find(s => s.name === "Require successful runtime smoke and authenticated cleanup").conclusion = "failure";}, - d => {d.jobs = [];}, - d => {d.jobs[0].steps = [];}, - d => {delete d.jobs[0].steps;}, - ]) { - for (const event of ["pull_request", "repository_dispatch"]) { - assert.equal(await verify(mutate, event), false, `${event}: ${mutate.toString()}`); - } - } - for (const mutate of [ - d => {d.source.head_branch = "feature/untrusted";}, - d => {d.source.head_sha = "invalid";}, - d => {d.source.event = "pull_request";}, - d => {d.currentPullRequest.merge_commit_sha = "e".repeat(40);}, - d => {d.currentBase.object.sha = "e".repeat(40);}, - d => {d.currentBase.ref = "refs/heads/main";}, - d => {delete d.currentBase.object;}, - ]) assert.equal(await verify(mutate, "repository_dispatch"), false, mutate.toString()); - console.log("Canonical PLAY transition exception positive and negative contracts passed."); -})().catch(error => {console.error(error); process.exitCode = 1;}); -NODE diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh old mode 100644 new mode 100755 index b47d12f249..42cc780571 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -318,8 +318,6 @@ required_condition="github.event.action != 'edited' || github.event.changes.base ci_path="$ROOT_DIR/.github/workflows/ci.yml" runtime_images_path="$ROOT_DIR/.github/workflows/runtime-images.yml" pr_image_publisher_path="$ROOT_DIR/.github/workflows/publish-pr-runtime-images.yml" -smoke_path="$ROOT_DIR/.github/workflows/smoke.yml" -image_wait_path="$ROOT_DIR/dev-tools/hosted/shared/wait-for-runtime-images.sh" preview_path="$ROOT_DIR/.github/workflows/preview.yml" trusted_preview_path="$ROOT_DIR/.github/workflows/hosted-identity-request.yml" preview_reconciler_path="$ROOT_DIR/.github/workflows/preview-reconciler.yml" @@ -330,7 +328,7 @@ node --test "$preview_comment_test_path" security_path="$ROOT_DIR/.github/workflows/security.yml" -for path in "$ci_path" "$security_path" "$smoke_path"; do +for path in "$ci_path" "$security_path" "$runtime_images_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done @@ -519,7 +517,6 @@ root = Path(sys.argv[1]) expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" for filename, jobs in { "security.yml": ("security-summary",), - "smoke.yml": ("smoke-summary-pending", "smoke-summary"), }.items(): workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) for job in jobs: @@ -551,19 +548,8 @@ PYTHON # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. assert_job_contains security.yml security-summary "name: \${{ github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Security Summary)' || 'Security Summary' }}" -assert_job_contains smoke.yml smoke-summary "name: \${{ github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Summary)' || 'Smoke Summary' }}" # A metadata-only edit must retain the required gate name. Its preservation # action verifies prior proof before reporting success for the unchanged tuple. -assert_job_contains smoke.yml smoke-gate 'name: Smoke Gate' -assert_job_contains smoke.yml smoke-summary-pending 'name: Smoke Summary (Pending)' -assert_job_contains smoke.yml smoke-summary-pending 'tracked-by-smoke-gate' -assert_job_contains smoke.yml smoke-summary 'needs: [changes, smoke-gate, smoke-summary-pending]' -# shellcheck disable=SC2016 # This assertion intentionally matches a literal GitHub expression. -assert_job_contains smoke.yml smoke-summary 'SMOKE_GATE_RESULT: ${{ needs.smoke-gate.result }}' -if grep -Eq '^ smoke-lite:' "$smoke_path"; then - echo "smoke.yml must not restore the redundant smoke-lite job" >&2 - exit 1 -fi for job in \ changes \ @@ -588,63 +574,23 @@ for job in \ assert_job_condition ci.yml "$job" "$required_condition" done -for job in changes smoke-summary-pending smoke-summary; do - assert_job_condition smoke.yml "$job" "$required_condition" -done -assert_job_contains smoke.yml smoke-summary-pending 'const smokeGateStatus = fullEnabled ? "pending" : "not-required";' -assert_job_contains smoke.yml smoke-summary-pending 'Full-stack smoke runs in Build Runtime Images and is tracked by Smoke Gate' -assert_job_contains smoke.yml smoke-summary-pending 'firemud-smoke-summary' -assert_job_contains smoke.yml smoke-summary-pending 'comment.user?.login === "github-actions[bot]"' -assert_job_contains smoke.yml smoke-summary-pending 'github.paginate(' -assert_job_contains smoke.yml smoke-summary-pending 'comment.created_at || ""' -assert_job_contains smoke.yml smoke-summary-pending 'candidateTimestamp < oldestTimestamp' -assert_job_contains smoke.yml smoke-summary-pending 'const seenCommentIds = new Set();' -assert_job_contains smoke.yml smoke-summary-pending 'String(comment.id) === String(existing?.id)' -assert_job_excludes smoke.yml smoke-summary-pending 'comment.updated_at' -assert_job_contains smoke.yml smoke-summary 'const smokeGateStatus =' -assert_job_contains smoke.yml smoke-summary 'firemud-smoke-summary' -assert_job_contains smoke.yml smoke-summary 'comment.user?.login === "github-actions[bot]"' -assert_job_contains smoke.yml smoke-summary 'github.paginate(' -assert_job_contains smoke.yml smoke-summary 'comment.created_at || ""' -assert_job_contains smoke.yml smoke-summary 'candidateTimestamp < oldestTimestamp' -assert_job_contains smoke.yml smoke-summary 'const seenCommentIds = new Set();' -assert_job_contains smoke.yml smoke-summary 'String(comment.id) === String(existing?.id)' -assert_job_excludes smoke.yml smoke-summary 'comment.updated_at' -assert_job_contains smoke.yml smoke-gate 'pull-requests: read' -assert_job_contains smoke.yml smoke-gate 'github.rest.pulls.get' -assert_job_contains smoke.yml smoke-gate 'pullRequest.state !== "open"' -assert_job_contains smoke.yml smoke-gate 'pullRequest.head.sha !== headSha' -assert_job_contains smoke.yml smoke-gate 'pullRequest.base.ref !== baseRef' -assert_job_contains smoke.yml smoke-gate 'github.rest.repos.getCommit' -assert_job_contains smoke.yml smoke-gate 'ref: `heads/${baseRef}`' -assert_job_contains smoke.yml smoke-gate 'const currentMergeSha = currentPullRequest.merge_commit_sha;' -assert_job_contains smoke.yml smoke-gate 'parents.length === 2' -assert_job_contains smoke.yml smoke-gate 'parents[0]?.sha === eventBaseSha' -assert_job_contains smoke.yml smoke-gate 'parents[1]?.sha === headSha' -assert_job_contains smoke.yml smoke-gate 'currentParents.length !== 2' -assert_job_contains smoke.yml smoke-gate 'currentParents[0]?.sha !== currentBaseSha' -assert_job_contains smoke.yml smoke-gate 'currentParents[1]?.sha !== headSha' -assert_job_contains smoke.yml smoke-gate 'sourceEvent: "pull_request"' -assert_job_contains smoke.yml smoke-gate 'run.event !== sourceEvent' -assert_job_contains smoke.yml smoke-gate 'github.rest.git.getRef' -assert_job_contains smoke.yml smoke-gate 'currentIdentity.sourceEvent === "pull_request"' -assert_job_contains smoke.yml smoke-gate 'job.name === "PR Full-Stack Smoke"' -assert_job_contains smoke.yml smoke-gate 'step.name === "Run credential-free full-stack smoke"' -assert_job_contains smoke.yml smoke-gate 'Stopping stale smoke gate before accepting full-stack proof' -assert_job_contains smoke.yml smoke-gate 'continue smokeGatePolling' -assert_job_excludes smoke.yml smoke-gate 'github.rest.repos.createDispatchEvent' - -# Every PR base receives the stable Smoke Gate; runtime path filtering is -# retained by the producer rather than filtering the required gate itself. -python3 - "$smoke_path" "$runtime_images_path" <<'PYTHON' +assert_job_condition runtime-images.yml changes "$required_condition" + +# Every PR base runs the Smoke Gate. Change detection skips the build jobs +# inside the run instead of a paths filter that would leave the gate absent. +python3 - "$runtime_images_path" <<'PYTHON' import sys from pathlib import Path import yaml -smoke, runtime = [yaml.load(Path(path).read_text(), Loader=yaml.BaseLoader) for path in sys.argv[1:]] -assert set(smoke["on"]["pull_request"]) == {"types"} -assert set(runtime["on"]["pull_request"]) == {"types", "paths"} +runtime = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +assert set(runtime["on"]["pull_request"]) == {"types"} assert "branches" not in runtime["on"]["workflow_run"] +gate = runtime["jobs"]["smoke-gate"] +assert gate["name"] == "Smoke Gate" and gate["if"] == "${{ always() && github.event_name == 'pull_request' }}" +assert set(gate["needs"]) == {"changes", "image-meta", "pr-local-smoke", "pr-controller-smoke"} +assert "needs.changes.outputs.run_smoke_full == 'true'" in runtime["jobs"]["image-meta"]["if"] +assert "github.rest.repos.createDispatchEvent" not in str(gate) PYTHON # Reproduce the metadata-edit sequence structurally: the edit has its own @@ -652,19 +598,18 @@ PYTHON # dispatch-capable step exists in Smoke Gate. The original event tuple remains # valid for merge gating while trusted image publication and preview continue # to require current-base provenance. -python3 - "$smoke_path" "$runtime_images_path" <<'PY' +python3 - "$runtime_images_path" <<'PY' from pathlib import Path import re import sys import yaml -smoke_path, runtime_path = map(Path, sys.argv[1:]) -smoke = yaml.load(smoke_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) +runtime_path = Path(sys.argv[1]) runtime = yaml.load(runtime_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) -if smoke["jobs"]["smoke-gate"].get("name") != "Smoke Gate": - raise SystemExit("metadata-only smoke must retain its required gate context") +if runtime["jobs"]["smoke-gate"].get("name") != "Smoke Gate": + raise SystemExit("metadata-only edits must retain the required Smoke Gate context") runtime_jobs = runtime["jobs"] metadata_guard = "github.event.action != 'edited' || github.event.changes.base.ref != null" @@ -674,19 +619,27 @@ for job_name in ("image-meta", "pr-local-smoke", "pr-controller-smoke"): raise SystemExit(f"{job_name} can run for a metadata-only edited event") concurrency_group = runtime["concurrency"]["group"] -if "&& 'metadata' || 'required'" not in concurrency_group: +if "&& format('metadata-{0}', github.run_id) || 'required'" not in concurrency_group: raise SystemExit("metadata-only runtime events can cancel substantive runtime builds") dispatch_condition = runtime_jobs["dispatch-pr-base-refreshes"].get("if", "") if "github.event_name == 'workflow_run'" not in dispatch_condition: raise SystemExit("runtime refresh dispatch is not isolated from pull-request metadata events") -# Distinct verified PR tuples must not evict one another; pull_request and -# typed refresh runs for the same tuple must share a group. A dispatch missing +# Each PR run has its own workflow group; the PR build jobs cancel the older +# build per PR. Typed refreshes group by their exact tuple; a dispatch missing # any tuple field gets a unique run namespace. -pull_request_selector = "format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)" +pull_request_selector = "format('pr-{0}-run-{1}', github.event.pull_request.number, github.run_id)" if pull_request_selector not in concurrency_group: - raise SystemExit("pull_request runtime concurrency must use its exact PR, base, head, and test-merge identity") + raise SystemExit("pull_request runtime concurrency must be per PR run") +for job_name in ("pr-local-smoke", "pr-controller-smoke"): + # GitHub orders group cancellation by arrival, so a delayed older run could + # cancel the current one: smoke jobs have no cancelling group, and a + # superseded comparison skips smoke instead. + if "concurrency" in runtime_jobs[job_name]: + raise SystemExit(f"{job_name} must not join a cancelling concurrency group") + if "needs.image-meta.outputs.head_current == 'true'" not in runtime_jobs[job_name]["if"]: + raise SystemExit(f"{job_name} must skip a superseded PR comparison") dispatch_fields = ("pr_number", "base_sha", "head_sha", "merge_sha") for field in dispatch_fields: if f"github.event.client_payload.{field} != ''" not in concurrency_group: @@ -699,8 +652,9 @@ if "format('repository-dispatch-run-{0}', github.run_id)" not in concurrency_gro if "github.sha" in concurrency_group.split("github.event_name == 'repository_dispatch'", 1)[-1].split("github.event_name == 'workflow_run'", 1)[0]: raise SystemExit("repository_dispatch concurrency must not use the default-branch github.sha") # Execute the workflow-level selector before its dispatcher can classify a CI -# callback. A title/body CI completion must not evict substantive reconciliation. -assert runtime["concurrency"]["cancel-in-progress"] == "true" +# callback. GitHub rejects queue: max with a cancelling run, so the workflow group never cancels. +assert runtime["concurrency"]["cancel-in-progress"] == "false" +assert runtime["concurrency"]["queue"] == "max", "pending protected publications must not replace each other" def callback_group(branch, source_id, source_attempt, source_event="pull_request", head="a" * 40): values = { @@ -711,6 +665,7 @@ def callback_group(branch, source_id, source_attempt, source_event="pull_request "github.event.workflow_run.run_attempt": source_attempt, "github.event.workflow_run.head_branch": branch, "github.event.workflow_run.head_sha": head, + "github.event.workflow_run.conclusion": "success", "github.ref": "refs/heads/develop", "github.run_id": 9000 + source_id, } @@ -740,9 +695,12 @@ for branch in ("main", "develop", "feature/parent"): assert callback_group(branch, 7001, 1) == substantive, "duplicate completion callbacks retain their exact source-attempt group" assert callback_group(branch, 7003, 1, "push") not in (substantive, metadata), "PR callback must not cancel branch publication" +# One protected commit serializes selection, smoke and publication across +# callbacks, reruns and both protected branches; another commit is separate. for branch in ("main", "develop"): - assert callback_group(branch, 7101, 1, "push") == callback_group(branch, 7102, 2, "push", "b" * 40), "protected push publication must retain branch serialization" -assert callback_group("main", 7101, 1, "push") != callback_group("develop", 7102, 1, "push"), "protected publication branches must remain separate" + assert callback_group(branch, 7101, 1, "push") == callback_group(branch, 7102, 2, "push"), "protected push publication must serialize one commit" + assert callback_group(branch, 7101, 1, "push") != callback_group(branch, 7102, 1, "push", "b" * 40), "a different protected commit needs a distinct group" +assert callback_group("main", 7101, 1, "push") == callback_group("develop", 7102, 1, "push"), "both protected branches must serialize the same commit" PY @@ -856,7 +814,7 @@ const tupleFor = (number, headLetter, mergeLetter, base = baseSha) => ({ mergeSha: sha(mergeLetter), }); const titleFor = (tuple) => - `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + `Build Runtime Images pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; const producer = (tuple, event, status, conclusion = null, overrides = {}) => ({ id: Number(tuple.prNumber) * 100 + (event === "pull_request" ? 1 : 2), name: "Build Runtime Images", @@ -1199,357 +1157,9 @@ async function runDispatcher({ assert.equal(runtimeDispatches(featureResult).length, 1, "feature and dependency-bot artifact refresh is independent of preview eligibility"); assert.equal(previewDispatches(featureResult).length, expectedPreviews, "preview reconciliation retains canonical priority/bot/label policy"); } - for (const [event, status] of [ - ["pull_request", "queued"], - ["pull_request", "in_progress"], - ["repository_dispatch", "queued"], - ["repository_dispatch", "in_progress"], - ]) { - const result = await runDispatcher({ - tuples: [tuple], - inventories: { [event]: [producer(tuple, event, status)] }, - }); - assert.equal(result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, - `${event} ${status} exact producer must suppress duplicate runtime dispatch`); - assert.equal(result.dispatches.filter((item) => item.event_type === "preview-deploy").length, 1, - "runtime deduplication must retain preview reconciliation"); - assert.equal(result.inventoryCalls.length, 2, "complete initial inventories require one query per event kind"); - assert(result.inventoryCalls.every((request) => - request.workflow_id === "runtime-images.yml" && - request.per_page === 100 && - request.page === 1 && - typeof request.created === "string" && - !Number.isNaN(Date.parse(request.created.replace(/\.\.\*$/, "")) ) - ), "the shared inventory must query only one bounded recent page per event"); - } - - for (const event of ["pull_request", "repository_dispatch"]) { - const completedSuccess = await runDispatcher({ - tuples: [tuple], - inventories: { [event]: [producer(tuple, event, "completed", "success")] }, - }); - assert.equal(completedSuccess.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - `${event} completed source success must preserve recovery dispatch for missing or expired publication`); - } - - for (const validRef of [ - "main", - "refs/heads/feature]/test", - "refs/heads/feature/@/test", - "refs/heads/feature./test", - ]) { - const refSuffixedPath = await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { - path: `.github/workflows/runtime-images.yml@${validRef}`, - })] }, - }); - assert.equal(refSuffixedPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, - `the exact owning workflow path with valid Git ref ${validRef} must remain eligible`); - } - for (const invalidRef of ["@", "refs/heads/trailing.", "refs/heads/feature[/test"]) { - const invalidRefPath = await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { - path: `.github/workflows/runtime-images.yml@${invalidRef}`, - })] }, - }); - assert.equal(invalidRefPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - `an invalid Git ref ${invalidRef} must not suppress the required dispatch`); - } - const wrongWorkflowPath = await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { - path: ".github/workflows/other.yml@refs/heads/develop", - })] }, - }); - assert.equal(wrongWorkflowPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "an unrelated workflow path must not suppress the required dispatch"); - assert(wrongWorkflowPath.warnings.some((message) => message.includes("falling back to the required refresh dispatch")), - "an exact-tuple producer with an unrelated workflow path must emit a fallback warning"); - - for (const [status, conclusion] of [ - ["completed", "failure"], - ["completed", "cancelled"], - ]) { - const result = await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", status, conclusion)] }, - }); - assert.equal(result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - `${conclusion} producer must allow an exact-tuple retry`); - } - - const orderedProducerInventory = async (older, newer, newerConclusion = null) => runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [ - producer(tuple, "pull_request", older[0], older[1], { - id: 10101, - created_at: "2026-01-01T00:00:00Z", - }), - producer(tuple, "pull_request", newer[0], newerConclusion, { - id: 10102, - created_at: "2026-01-02T00:00:00Z", - }), - ] }, - }); - for (const conclusion of ["failure", "cancelled"]) { - const newestFailure = await orderedProducerInventory( - ["completed", "success"], ["completed", conclusion], conclusion - ); - assert.equal(newestFailure.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - `newer ${conclusion} producer must allow refresh despite an older success`); - } - for (const [olderStatus, olderConclusion, newestStatus, newestConclusion, suppress] of [ - ["completed", "failure", "in_progress", null, true], - ["completed", "success", "in_progress", null, true], - ["completed", "failure", "completed", "success", false], - ]) { - const newestUsable = await orderedProducerInventory( - [olderStatus, olderConclusion], [newestStatus, newestConclusion], newestConclusion - ); - assert.equal(newestUsable.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, - suppress ? 0 : 1, - `newer ${newestStatus}/${newestConclusion} producer must determine whether runtime recovery dispatches`); - } - const ambiguousNewest = await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [ - producer(tuple, "pull_request", "completed", "success", { id: 10103 }), - producer(tuple, "pull_request", "completed", "failure", { id: 10104 }), - ] }, - }); - assert.equal(ambiguousNewest.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "ambiguous equal-time exact producers must fall back to the required refresh dispatch"); - assert(ambiguousNewest.warnings.some((message) => message.includes("ambiguous created_at timestamp")), - "ambiguous producer ordering must emit an explicit fallback diagnostic"); - - const staleTuple = tupleFor(101, "a", "c", sha("d")); - const stale = await runDispatcher({ - tuples: [tuple], - inventories: { repository_dispatch: [producer(staleTuple, "repository_dispatch", "completed", "success")] }, - }); - assert.equal(stale.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "stale base tuple must not suppress a current runtime refresh"); - - const changedBaseTuple = tupleFor(101, "a", "c", sha("e")); - const changedBase = await runDispatcher({ - tuples: [changedBaseTuple], - inventories: { pull_request: [producer(tuple, "pull_request", "completed", "success")] }, - }); - assert.equal(changedBase.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "a changed base requires a fresh exact tuple producer"); - - const sibling = tupleFor(102, "f", "d"); - const independent = await runDispatcher({ - tuples: [tuple, sibling], - inventories: { - pull_request: [null, { id: "malformed-unrelated-record", display_title: "historical unrelated record" }, - producer(tuple, "pull_request", "in_progress")], - repository_dispatch: [], - }, - }); - const independentRefreshNumbers = independent.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") - .map((item) => item.client_payload.pr_number) - .sort(); - assert.deepEqual(independentRefreshNumbers, ["102"], - "unrelated malformed history must not block an independent sibling refresh or prevent reuse of the valid active producer"); - assert.equal(independent.inventoryCalls.length, 2, "multiple PRs must reuse one shared inventory"); - - const partialSibling = tupleFor(103, "7", "8"); - const recentRuns = runsDescending("pull_request", "2026-01-02T00:00:00Z"); - recentRuns[0] = producer(tuple, "pull_request", "in_progress", null, { - created_at: "2026-01-02T00:00:00Z", - }); - const recentRefinedRuns = [producer(tuple, "pull_request", "in_progress", null, { - created_at: "2026-01-02T00:00:00Z", - })]; - assertCompleteRefinementPreservesEligibleInitialRuns(recentRuns, "2026-01-02T00:00:00Z", recentRefinedRuns, - "truncated positive refinement"); - const truncatedPositive = await runDispatcher({ - tuples: [tuple, partialSibling], - inventories: { - pull_request: { - total_count: 101, - runs: recentRuns, - refined: recentRefinedRuns, - refinedTotalCount: 1, - }, - repository_dispatch: [], - }, - }); - const truncatedRefreshNumbers = truncatedPositive.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") - .map((item) => item.client_payload.pr_number) - .sort(); - assert.deepEqual(truncatedRefreshNumbers, ["103"], - "complete refinement must prove the exact candidate while an unmatched sibling uses required dispatch"); - assert.equal(truncatedPositive.inventoryCalls.length, 4, - "truncated inventory must use at most one cached refinement pair for all siblings"); - assert(truncatedPositive.inventoryCalls.slice(2).every((request) => - request.created === "2026-01-02T00:00:00Z..*" - ), "the refinement pair must use the inclusive exact lower bound of returned in-flight candidates"); - - const refinedSiblings = [tupleFor(107, "5", "6"), tupleFor(108, "7", "9")]; - const siblingPage = runsDescending("pull_request", "2026-01-04T00:00:00Z"); - siblingPage[0] = producer(refinedSiblings[0], "pull_request", "in_progress", null, { - created_at: "2026-01-04T00:00:00Z", - }); - siblingPage[1] = producer(refinedSiblings[1], "pull_request", "queued", null, { - created_at: "2026-01-03T23:59:59Z", - }); - assertCompleteRefinementPreservesEligibleInitialRuns(siblingPage, "2026-01-03T23:59:59Z", siblingPage.slice(0, 2), - "shared sibling refinement"); - const refinedSiblingReuse = await runDispatcher({ - tuples: refinedSiblings, - inventories: { - pull_request: { - total_count: 101, - runs: siblingPage, - refined: siblingPage.slice(0, 2), - refinedTotalCount: 2, - }, - repository_dispatch: [], - }, - }); - assert.equal(refinedSiblingReuse.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, - "the shared refined inventory must cover each initially observed in-flight sibling"); - assert.equal(refinedSiblingReuse.inventoryCalls.length, 4, - "all sibling decisions must reuse one refinement pair rather than scan per PR"); - assert(refinedSiblingReuse.inventoryCalls.slice(2).every((request) => - request.created === "2026-01-03T23:59:59Z..*" - ), "the shared sibling refinement must start at the earliest returned in-flight timestamp"); - - const truncatedRefinementTuple = tupleFor(109, "a", "e"); - const truncatedRefinementPage = runsDescending("pull_request", "2026-01-05T00:03:00Z"); - truncatedRefinementPage[0] = producer(truncatedRefinementTuple, "pull_request", "in_progress", null, { - created_at: "2026-01-05T00:00:00Z", - }); - const truncatedRefinement = await runDispatcher({ - tuples: [truncatedRefinementTuple], - inventories: { - pull_request: { - total_count: 101, - runs: truncatedRefinementPage, - refined: truncatedRefinementPage, - refinedTotalCount: 101, - }, - repository_dispatch: [], - }, - }); - assert.equal(truncatedRefinement.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "a still-truncated refinement must use baseline dispatch"); - assert(truncatedRefinement.warnings.some((message) => message.includes("falling back to the required refresh dispatch")), - "a truncated refinement must report its required-dispatch fallback"); - assert.equal(truncatedRefinement.inventoryCalls.length, 4, - "a failed refinement must stop after the single bounded shared refinement pair"); - - const completedTruncatedTuple = tupleFor(110, "b", "f"); - const completedTruncatedPage = runsDescending("pull_request", "2026-01-06T00:00:00Z"); - completedTruncatedPage[0] = producer(completedTruncatedTuple, "pull_request", "completed", "success", { - created_at: "2026-01-06T00:00:00Z", - }); - const completedTruncated = await runDispatcher({ - tuples: [completedTruncatedTuple], - inventories: { - pull_request: { total_count: 101, runs: completedTruncatedPage }, - repository_dispatch: [], - }, - }); - assert.equal(completedTruncated.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "completed source results must preserve required recovery dispatch"); - assert.equal(completedTruncated.inventoryCalls.length, 2, - "completed-only truncated inventories need no refinement because they never suppress dispatch"); - - const hiddenNewerFailureTuple = tupleFor(105, "1", "2"); - const crossEventHiddenNewer = await runDispatcher({ - tuples: [hiddenNewerFailureTuple], - inventories: { - pull_request: [producer(hiddenNewerFailureTuple, "pull_request", "in_progress", null, { - created_at: "2026-01-01T10:00:00Z", - })], - // The initial dispatch page omits this newer exact terminal producer; bounded refinement must reveal it. - repository_dispatch: { - total_count: 101, - runs: runsDescending("repository_dispatch", "2026-01-01T09:00:00Z"), - refined: [producer(hiddenNewerFailureTuple, "repository_dispatch", "completed", "failure", { - created_at: "2026-01-01T10:30:00Z", - })], - refinedTotalCount: 1, - }, - }, - }); - assert.equal(crossEventHiddenNewer.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "refinement must reveal the newer cross-event terminal producer and preserve required dispatch"); - assert.equal(crossEventHiddenNewer.inventoryCalls.length, 4, - "one refinement pair must cover both event types when another event could contain a newer terminal run"); - - const safeOlderOmittedTuple = tupleFor(106, "3", "4"); - const safelyOlderOmitted = await runDispatcher({ - tuples: [safeOlderOmittedTuple], - inventories: { - pull_request: [producer(safeOlderOmittedTuple, "pull_request", "in_progress", null, { - created_at: "2026-01-03T10:00:00Z", - })], - repository_dispatch: { - total_count: 101, - runs: runsDescending("repository_dispatch", "2026-01-02T10:00:00Z"), - refined: [], - refinedTotalCount: 0, - }, - }, - }); - assert.equal(safelyOlderOmitted.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, - "complete refinement from the candidate creation time proves apparently older omissions cannot mask it"); - assert.equal(safelyOlderOmitted.inventoryCalls.length, 4, - "complete refinement must stay within the one additional shared pair"); - - const validSibling = tupleFor(104, "9", "0"); - const relevantMalformed = await runDispatcher({ - tuples: [tuple, validSibling], - inventories: { - pull_request: [ - producer(tuple, "pull_request", "in_progress", null, { repository: { full_name: "other/repo" } }), - producer(validSibling, "pull_request", "in_progress"), - ], - repository_dispatch: [], - }, - }); - const relevantMalformedRefreshNumbers = relevantMalformed.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") - .map((item) => item.client_payload.pr_number) - .sort(); - assert.deepEqual(relevantMalformedRefreshNumbers, ["101"], - "relevant malformed evidence must fall back for its own tuple while a valid active sibling producer remains reusable"); - - for (const uncertain of [ - await runDispatcher({ tuples: [tuple], inventories: { pull_request: { total_count: 101, runs: [] } } }), - await runDispatcher({ tuples: [tuple], inventories: { pull_request: { total_count: 1, runs: [] } } }), - await runDispatcher({ tuples: [tuple], apiFailure: "pull_request" }), - await runDispatcher({ tuples: [tuple], inventories: { pull_request: { malformed: true } } }), - await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { - repository: { full_name: "other/repo" }, - })] }, - }), - await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "completed", "success", { - created_at: "not-a-workflow-run-timestamp", - })] }, - }), - ]) { - assert.equal(uncertain.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "incomplete, unavailable, or relevant malformed evidence must fall back to required dispatch"); - assert.equal(uncertain.dispatches.filter((item) => item.event_type === "preview-deploy").length, 1, - "inventory uncertainty must not block independent preview reconciliation"); - assert(uncertain.warnings.some((message) => message.includes("falling back to the required refresh dispatch")), - "inventory uncertainty must produce a concrete fallback diagnostic"); - } - - process.stdout.write("runtime refresh deduplication fixtures passed\n"); + // Duplicate refreshes collapse in the receiver concurrency group, which + // also skips the build when the pr-merge tags already exist. + process.stdout.write("runtime refresh dispatch fixtures passed\n"); })().catch((error) => { process.stderr.write(`${error.stack || error}\n`); process.exitCode = 1; @@ -1559,10 +1169,10 @@ NODE require_contains "$runtime_images_path" 'types: [opened, synchronize, reopened, edited]' require_contains "$runtime_images_path" 'types: [pr-runtime-base-refresh]' require_contains "$runtime_images_path" 'repository_dispatch:' -require_contains "$runtime_images_path" "&& 'metadata' || 'required' }}" -require_contains "$runtime_images_path" ' cancel-in-progress: true' +require_contains "$runtime_images_path" "&& format('metadata-{0}', github.run_id) || 'required' }}" +require_contains "$runtime_images_path" ' cancel-in-progress: false' require_contains "$runtime_images_path" 'run-name: Build Runtime Images ' -require_contains "$runtime_images_path" "format('secure-pr-artifact pr-{0}" +require_contains "$runtime_images_path" "format('pr-{0}" require_contains "$runtime_images_path" 'github.event.pull_request.base.sha' require_contains "$runtime_images_path" 'github.event.pull_request.head.sha' require_contains "$runtime_images_path" 'github.event.client_payload.base_sha' @@ -1574,7 +1184,7 @@ require_contains "$runtime_images_path" 'Runtime PR refresh must run from the re require_contains "$runtime_images_path" 'Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref.' require_contains "$runtime_images_path" 'Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple.' require_contains "$runtime_images_path" 'Runtime PR refresh merge commit does not have the exact current base/head parents.' -require_contains "$runtime_images_path" "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." +require_contains "$runtime_images_path" "No PR test merge has the event's exact base/head parents; refusing a stale PR artifact." require_contains "$runtime_images_path" 'GH_TOKEN: ${{ github.token }}' require_contains "$runtime_images_path" "format('trusted-branch branch-{0} sha-{1}'" require_contains "$runtime_images_path" "format('base-refresh-only branch-{0} sha-{1} ci-{2}'" @@ -1587,22 +1197,15 @@ assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'contents: wri assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'github.rest.git.getRef' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'github.rest.pulls.list' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'github.rest.repos.getCommit' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'github.rest.actions.listWorkflowRuns' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'actions: read' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'runtimeRunPageSize = 100' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'runtimeRunLookbackMilliseconds' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'falling back to the required refresh dispatch' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'Skipping duplicate PR runtime refresh' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'currentBaseRef !== baseBranch' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'parents.length !== 2' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'parents[0] !== baseSha' assert_job_excludes runtime-images.yml dispatch-pr-base-refreshes '.base.sha' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'event_type: "pr-runtime-base-refresh"' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'pr_number: tuple.prNumber' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'base_sha: tuple.baseSha' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'head_sha: tuple.headSha' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'merge_sha: tuple.mergeSha' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'event_type: "preview-deploy"' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'action: "deploy"' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'preview_domain: "preview.firedevops.net"' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes '".github/actions/load-workflow-tool-versions/"' @@ -1613,24 +1216,11 @@ assert_job_contains runtime-images.yml pr-local-smoke 'github.event_name == '\'' assert_job_contains runtime-images.yml pr-local-smoke 'BASE_SHA="${{ needs.image-meta.outputs.base_sha }}"' assert_job_contains runtime-images.yml pr-local-smoke 'MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}"' assert_job_contains runtime-images.yml pr-controller-smoke 'github.event_name == '\''repository_dispatch'\''' -require_contains "$image_wait_path" 'display_title = run.get("display_title", "")' -require_contains "$image_wait_path" 'display_title.startswith("Build Runtime Images trusted-branch ")' -require_contains "$image_wait_path" 'and f"sha-{head_sha}" in tokens' -require_contains "$image_wait_path" 'and "branch-develop" in tokens' -require_contains "$image_wait_path" 'and f"base-{base_sha}" in tokens' -require_contains "$image_wait_path" 'and f"merge-{merge_sha}" in tokens' -require_contains "$image_wait_path" 'run.get("event") == "workflow_run"' -require_contains "$image_wait_path" 'gh api --paginate --slurp' -require_contains "$image_wait_path" 'GitHub API poll failed while %s; retrying within the existing wait deadline.' -# shellcheck disable=SC2016 # These assertions intentionally match literal shell source. -require_contains "$image_wait_path" 'if ! workflow_payload="$(' -# shellcheck disable=SC2016 # These assertions intentionally match literal shell source. -require_contains "$image_wait_path" 'if ! event_payload="$(' if grep -Eq '^concurrency:' "$preview_path"; then echo "Preview workflow must not cancel an active lifecycle from workflow-level concurrency" >&2 exit 1 fi -assert_job_contains preview.yml preview-plan "group: preview-plan-\${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }}" +assert_job_contains preview.yml preview-plan "group: preview-readonly-plan-\${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }}" assert_job_contains preview.yml preview-plan 'cancel-in-progress: true' assert_job_excludes preview.yml preview-plan 'Publish preview lifecycle state' assert_job_excludes preview.yml preview-plan 'firemud-preview-summary' @@ -1658,7 +1248,7 @@ require_contains "$preview_path" 'run-name: ${{ github.event_name == ' require_contains "$preview_path" "format('Preview dispatch pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha || 'unknown', github.event.client_payload.head_sha, github.event.client_payload.merge_sha || 'unknown')" require_contains "$preview_path" 'contents: read' require_contains "$preview_path" 'pull-requests: read' -require_contains "$preview_path" 'pull_request_target:' +require_contains "$preview_path" ' pull_request:' require_contains "$preview_path" 'types: [preview-deploy, preview-destroy]' require_contains "$preview_path" ' - opened' require_contains "$preview_path" ' - synchronize' @@ -1682,7 +1272,7 @@ if grep -Eq '^ - closed$' "$preview_path"; then fi require_contains "$preview_path" 'Check out trusted default branch for preview plan' require_contains "$preview_path" 'ref: ${{ github.event.repository.default_branch }}' -require_contains "$preview_path" "github.event_name == 'pull_request_target'" +require_contains "$preview_path" "github.event_name == 'pull_request'" require_contains "$preview_path" "github.event_name == 'repository_dispatch'" require_contains "$preview_path" 'github.event.pull_request.head.repo.full_name == github.repository' require_contains "$preview_path" 'github.event.pull_request.base.repo.full_name == github.repository' @@ -1712,7 +1302,7 @@ from pathlib import Path workflow_path = Path(sys.argv[1]) workflow = workflow_path.read_text(encoding="utf-8") predicate_start = workflow.index( - ' if [[ "$EVENT_NAME" == pull_request_target && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] ||' + ' if [[ "$EVENT_NAME" == pull_request && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] ||' ) predicate_end = workflow.index( '\n if [[ "$ACTION" != deploy ]]; then', @@ -1792,7 +1382,7 @@ assert_job_excludes preview.yml preview-destroy-intent "github.event_name == 'pu # The trusted default-branch workflow owns all runtime and identity mutations. require_contains "$trusted_preview_path" "github.event.workflow_run.head_repository.full_name == github.repository" -require_contains "$trusted_preview_path" "github.event.workflow_run.event == 'pull_request_target' || github.event.workflow_run.event == 'repository_dispatch'" +require_contains "$trusted_preview_path" "github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch'" require_contains "$trusted_preview_path" "github.event_name == 'pull_request_target' && github.event.action == 'closed'" require_contains "$trusted_preview_path" 'require_source_field head-branch "$DEFAULT_BRANCH"' require_contains "$trusted_preview_path" 'preview-(render|intent)-pr-' @@ -1818,7 +1408,7 @@ require_contains "$trusted_preview_path" '--cleanup "$PR_NUMBER" "$EXPECTED_HEAD require_contains "$trusted_preview_path" "needs.validate-target.outputs.retire_identity == 'true'" for job in prepare-runtime deploy-runtime destroy-runtime retire-identity; do assert_job_contains hosted-identity-request.yml "$job" 'runs-on:' - assert_job_contains hosted-identity-request.yml "$job" 'self-hosted' + assert_job_contains hosted-identity-request.yml "$job" 'runs-on: ubuntu-latest' assert_job_contains hosted-identity-request.yml "$job" 'environment: trusted-hosted-cluster' done require_contains "$preview_reconciler_path" 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' @@ -2004,18 +1594,6 @@ if "