diff --git a/.github/actions/preserve-required-gate/action.yml b/.github/actions/preserve-required-gate/action.yml deleted file mode 100644 index d4de614d06..0000000000 --- a/.github/actions/preserve-required-gate/action.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Preserve Required Gate -description: Preserve a successful required check context for metadata-only pull request edits. -inputs: - gate-name: - description: Required check name to preserve. - required: true - workflow-name: - description: Exact workflow display name that owns the required gate. - required: true - workflow-file: - description: Workflow filename used to resolve the owning workflow identity. - required: true - workflow-path: - description: Exact workflow path returned by the Actions API. - required: true -outputs: - assessment: - description: Successful proof or dependency-deferred assessment; invalid proof fails the action. - value: ${{ steps.preserve.outputs.assessment }} -runs: - using: composite - steps: - - name: Set up canonical GitHub CLI - uses: ./.github/actions/setup-gh - - name: Assess prior required gate - id: preserve - shell: bash - env: - GH_TOKEN: ${{ github.token }} - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - REQUIRED_GATE_NAME: ${{ inputs.gate-name }} - EXPECTED_WORKFLOW_NAME: ${{ inputs.workflow-name }} - EXPECTED_WORKFLOW_FILE: ${{ inputs.workflow-file }} - EXPECTED_WORKFLOW_PATH: ${{ inputs.workflow-path }} - run: bash "$GITHUB_ACTION_PATH/assess-required-gate.sh" diff --git a/.github/actions/preserve-required-gate/assess-required-gate.sh b/.github/actions/preserve-required-gate/assess-required-gate.sh deleted file mode 100644 index f76d200da7..0000000000 --- a/.github/actions/preserve-required-gate/assess-required-gate.sh +++ /dev/null @@ -1,641 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if [[ "${GITHUB_EVENT_NAME:-}" != "pull_request" ]]; then - echo "Required-gate preservation requires pull_request context; refusing to preserve." >&2 - exit 1 -fi -for required_variable in GH_TOKEN BASE_SHA HEAD_SHA PR_NUMBER REQUIRED_GATE_NAME EXPECTED_WORKFLOW_NAME EXPECTED_WORKFLOW_FILE EXPECTED_WORKFLOW_PATH GITHUB_REPOSITORY GITHUB_RUN_ID; do - if [[ -z "${!required_variable:-}" ]]; then - echo "Required-gate preservation is missing ${required_variable}; refusing to preserve." >&2 - exit 1 - fi -done -is_github_sha() { - [[ "$1" =~ ^[0-9A-Fa-f]{40}$ ]] -} -if ! is_github_sha "${BASE_SHA}"; then - echo "Required-gate preservation requires a valid pull request base SHA; refusing to preserve." >&2 - exit 1 -fi -if ! is_github_sha "${HEAD_SHA}"; then - echo "Required-gate preservation requires a valid pull request head SHA; refusing to preserve." >&2 - exit 1 -fi -if [[ ! "${PR_NUMBER}" =~ ^[1-9][0-9]*$ ]]; then - echo "Required-gate preservation requires a valid pull request number; refusing to preserve." >&2 - exit 1 -fi -if [[ ! "${EXPECTED_WORKFLOW_FILE}" =~ ^[A-Za-z0-9._-]+\.(yml|yaml)$ || - ! "${EXPECTED_WORKFLOW_PATH}" =~ ^\.github/workflows/[A-Za-z0-9._-]+\.(yml|yaml)$ || - "${EXPECTED_WORKFLOW_PATH}" != ".github/workflows/${EXPECTED_WORKFLOW_FILE}" ]]; then - echo "Required-gate preservation received invalid workflow or job identity; refusing to preserve." >&2 - exit 1 -fi -expected_display_title="${EXPECTED_WORKFLOW_NAME} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" -report_assessment() { - if [[ -n "${GITHUB_OUTPUT:-}" ]]; then - printf 'assessment=%s\n' "$1" >>"${GITHUB_OUTPUT}" - else - echo "One-assessment preservation requires GITHUB_OUTPUT; refusing to preserve." >&2 - exit 1 - fi -} -defer_dependency() { - echo "Required-gate proof is not yet conclusive; deferring without polling." >&2 - report_assessment dependency-deferred - exit 0 -} -is_retryable_gh_failure() { - local exit_status="$1" - local error_text="${2,,}" - if [[ "$error_text" =~ http[[:space:]]+5[0-9]{2} ]]; then - return 0 - fi - if [[ "$error_text" =~ http[[:space:]]+(403|429) ]] && - [[ "$error_text" =~ (rate[[:space:]-]*limit|abuse) ]]; then - return 0 - fi - if [[ "$exit_status" -ne 0 ]] && - [[ "$error_text" =~ (could[[:space:]]not[[:space:]]resolve|failed[[:space:]]to[[:space:]](connect|make[[:space:]]request)|error[[:space:]]connecting|unable[[:space:]]to[[:space:]]connect|connection[[:space:]](reset|refused|timed|closed)|network[[:space:]]is[[:space:]]unreachable|timed[[:space:]]out|timeout|temporary[[:space:]]failure|tls|eof) ]]; then - return 0 - fi - return 1 -} - -is_github_timestamp() { - [[ "$1" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] -} - -recover_validation_job_from_attempt() { - local attempt attempt_snapshot cache_key expected_branch expected_head_repository - attempt_recovered_job_json='' - [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/ci.yml" && - "${EXPECTED_WORKFLOW_NAME}" == "CI — Validation" && - "${REQUIRED_GATE_NAME}" == "Validation Gate" ]] || return 1 - attempt="$(jq -er '.run_attempt | select(type == "number" and . > 0 and . == floor)' <<<"${job_json}")" || return 1 - cache_key="${workflow_run_id}:${attempt}:${job_id}:${check_run_id}" - if [[ -n "${attempt_snapshot_cache[${cache_key}]:-}" ]]; then - attempt_recovered_job_json="$(jq -cer '.job' <<<"${attempt_snapshot_cache[${cache_key}]}")" || return 1 - return 0 - fi - if (( attempt_recovery_reads >= attempt_recovery_read_limit )); then - echo "Exact-attempt historical sparse-candidate recovery exhausted its ${attempt_recovery_read_limit}-snapshot budget; refusing to assess." >&2 - return 3 - fi - attempt_recovery_reads=$((attempt_recovery_reads + 1)) - expected_branch="$(jq -er '.head_branch | select(type == "string" and length > 0)' <<<"${workflow_run_json}")" || return 1 - expected_head_repository="$(jq -er '.head_repository.full_name | select(type == "string" and length > 0)' <<<"${workflow_run_json}")" || return 1 - attempt_snapshot="$(bash "$(dirname "${BASH_SOURCE[0]}")/validate-exact-attempt-gate.sh" \ - "${workflow_run_id}" "${attempt}" "${job_id}" "${check_run_id}" \ - "${REQUIRED_GATE_NAME}" "${expected_workflow_id}" "${EXPECTED_WORKFLOW_NAME}" \ - "${EXPECTED_WORKFLOW_PATH}" "${expected_display_title}" "${PR_NUMBER}" \ - "${BASE_SHA}" "${HEAD_SHA}" "${expected_branch}" "${GITHUB_REPOSITORY}" \ - "${expected_head_repository}" "${check_status}" "${conclusion}" \ - "${details_url}" "${started_at}" "${completed_at}" false)" || return 1 - attempt_snapshot_cache["${cache_key}"]="${attempt_snapshot}" - attempt_recovered_job_json="$(jq -cer '.job' <<<"${attempt_snapshot}")" || return 1 - return 0 -} - -api_error_file="$(mktemp)" -trap 'rm -f "$api_error_file"' EXIT -expected_workflow_id="" -declare -A workflow_run_cache=() -declare -A job_cache=() -declare -A attempt_snapshot_cache=() -attempt_recovery_reads=0 -attempt_recovery_read_limit=3 -attempt_recovered_job_json='' - -# Recognize only the observed pre-execution Validation cancellation shape. A -# cancelled workflow may still contain genuine failures; its conclusion alone -# never suppresses a failed gate. Return 0 only for independently bound proof. -validation_cancelled_before_checks() { - local attempt run_snapshot jobs_snapshot check_snapshot native_job check_id - attempt="$(jq -er '.run_attempt | select(type == "number" and . > 0 and . == floor)' <<<"${job_json}")" || return 1 - run_snapshot="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${workflow_run_id}/attempts/${attempt}")" || return 1 - jq -e --argjson original "${workflow_run_json}" --argjson attempt "${attempt}" ' - . as $run | .run_attempt == $attempt and .status == "completed" and .conclusion == "cancelled" and - all(["id", "workflow_id", "name", "path", "head_sha", "display_title", "repository", "event"][]; - . as $key | $run[$key] == $original[$key]) - ' <<<"${run_snapshot}" >/dev/null || return 1 - jobs_snapshot="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${workflow_run_id}/attempts/${attempt}/jobs" \ - -f per_page=100 --paginate --slurp)" || return 1 - jq -e --argjson run "${workflow_run_id}" --argjson attempt "${attempt}" \ - --arg head "${HEAD_SHA}" --arg repo "${GITHUB_REPOSITORY}" --argjson gate "${job_json}" ' - ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", - ("Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})"), - ("Build and Test (account-service / $" + "{{ matrix.partition }})"), - ("Build and Test (world-management-service / $" + "{{ matrix.partition }})"), - ("Build and Test (game-session-service / $" + "{{ matrix.partition }})"), "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", - "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", - "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", - "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", "Account Coverage Aggregate", - "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] as $historical_names - | [$gate.steps[] | select(.name == "Declare dev tool contract split")] as $split_markers - | (if ($split_markers | length) == 1 - then [($historical_names + ["Dev Tool Validation Contracts"])] - else [$historical_names, ($historical_names + ["Dev Tool Validation Contracts"])] end) as $inventories - | .[0] as $snapshot - | type == "array" and length == 1 and ($snapshot.jobs | type) == "array" and - ($split_markers | length) <= 1 and - any($inventories[]; . as $names | - $snapshot.total_count == ($names | length) and - ($snapshot.jobs | length) == ($names | length) and - ([$snapshot.jobs[].id] | unique | length) == ($names | length) and - ([$snapshot.jobs[].name] | sort) == ($names | sort)) and - all(.[0].jobs[]; (.id | type) == "number" and .id > 0 and .id == (.id | floor) and - .run_id == $run and .run_attempt == $attempt and .head_sha == $head and .status == "completed" and - (.check_run_url | type) == "string" and - (.check_run_url | startswith("https://api.github.com/repos/" + $repo + "/check-runs/")) and - (.check_run_url | split("/check-runs/") | last | test("^[1-9][0-9]*$")) and - if .name == "Validation Gate" then - . == $gate and .conclusion == "failure" and (.steps | type) == "array" and - ([.steps[] | select(.name == "Enforce validation success" and .status == "completed" and .conclusion == "failure")] | length) == 1 and - ([.steps[] | select(.name == "Preserve successful required gate on metadata-only edit" and .status == "completed" and .conclusion == "skipped")] | length) == 1 and - all(.steps[]; .status == "completed" and - (if .name == "Enforce validation success" then .conclusion == "failure" - else (.conclusion == "success" or .conclusion == "skipped") end)) - elif (.name == "Account Coverage Aggregate" or .name == "Game Session Coverage Aggregate" or .name == "World Coverage Aggregate") then - (.conclusion == "cancelled" or .conclusion == "skipped") and .steps == [] - else .conclusion == "cancelled" and .steps == [] end) - ' <<<"${jobs_snapshot}" >/dev/null || return 1 - while IFS= read -r native_job; do - check_id="$(jq -er '.check_run_url | capture("/check-runs/(?[1-9][0-9]*)$").id' <<<"${native_job}")" || return 1 - check_snapshot="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/check-runs/${check_id}")" || return 1 - jq -e --argjson job "${native_job}" --argjson id "${check_id}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and - .head_sha == $job.head_sha and .name == $job.name and .status == $job.status and - .conclusion == $job.conclusion and .details_url == $job.html_url - ' <<<"${check_snapshot}" >/dev/null || return 1 - done < <(jq -c '.[0].jobs[]' <<<"${jobs_snapshot}") -} - -# A metadata-only run emits this same gate name. Its preservation step -# identifies the recursive run; substantive gates skip that step and -# remain authoritative, including failures. -: >"${api_error_file}" -if [[ -z "${expected_workflow_id}" ]]; then - set +e - workflow_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/actions/workflows/${EXPECTED_WORKFLOW_FILE}" \ - 2>"${api_error_file}")" - workflow_status=$? - set -e - if [[ "${workflow_status}" -ne 0 ]]; then - api_error="$(<"${api_error_file}")" - if ! is_retryable_gh_failure "${workflow_status}" "${api_error}"; then - echo "Permanent GitHub API/configuration failure while resolving the expected ${EXPECTED_WORKFLOW_PATH}; refusing to preserve." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 - fi - echo "GitHub API failure while resolving the expected workflow identity; refusing to preserve." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 - fi - set +e - expected_workflow_id="$(jq -r \ - --arg expected_name "${EXPECTED_WORKFLOW_NAME}" \ - --arg expected_path "${EXPECTED_WORKFLOW_PATH}" \ - 'if (.id | type) == "number" and - .name == $expected_name and - .path == $expected_path - then (.id | tostring) else "__missing__" end' \ - <<<"${workflow_json}" 2>>"${api_error_file}")" - workflow_query_status=$? - set -e - if [[ "${workflow_query_status}" -ne 0 || - ! "${expected_workflow_id}" =~ ^[0-9]+$ ]]; then - echo "GitHub API returned malformed expected workflow identity; refusing to preserve." >&2 - exit 1 - fi -fi -set +e -check_runs_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/check-runs" \ - -f check_name="${REQUIRED_GATE_NAME}" \ - -f filter=all \ - -f per_page=100 \ - --paginate \ - --slurp \ - 2>"${api_error_file}")" -api_status=$? -set -e -if [[ "${api_status}" -ne 0 ]]; then - api_error="$(<"${api_error_file}")" - if ! is_retryable_gh_failure "${api_status}" "${api_error}"; then - echo "Permanent GitHub API/configuration failure while checking the prior ${REQUIRED_GATE_NAME}; refusing to retry." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 - fi - echo "GitHub API failure while checking prior required-gate evidence; refusing to preserve." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 -fi - -set +e -jq -e ' - if type != "array" or length == 0 then false - elif any(.[]; type != "object" or (.check_runs | type) != "array") then false - else - .[0].total_count as $total - | all(.[]; (.total_count | type) == "number" and .total_count >= 0 and - .total_count == (.total_count | floor) and .total_count == $total) - and ([.[].check_runs[]] | length) == $total - and all(.[].check_runs[]; type == "object" and (.id | type) == "number" and - .id > 0 and .id == (.id | floor)) - and ([.[].check_runs[].id] | unique | length) == $total - end -' <<<"${check_runs_json}" >/dev/null 2>>"${api_error_file}" -check_runs_shape_status=$? -set -e -if [[ "${check_runs_shape_status}" -ne 0 ]]; then - echo "GitHub API returned malformed or incomplete check-run data for the prior ${REQUIRED_GATE_NAME}; refusing to preserve." >&2 - exit 1 -fi - -set +e -candidate_rows="$(jq -r --arg run_id "${GITHUB_RUN_ID}" ' - [.[].check_runs[]? - | select(((.details_url // "") | contains("/actions/runs/\($run_id)/") | not)) - ] as $candidates - | $candidates[] - | [ - (.app.slug // "__missing__"), - (.name // "__missing__"), - (.details_url // "__missing__"), - (if (.id | type) == "number" then (.id | tostring) else "__missing__" end), - (.status // "__missing__"), - (.conclusion // "__null__"), - (.completed_at // "__null__"), - (.started_at // "__null__") - ] - | @tsv' <<<"${check_runs_json}" 2>>"${api_error_file}")" -query_status=$? -set -e -if [[ "${query_status}" -ne 0 ]]; then - echo "GitHub API returned malformed check-run data for the prior ${REQUIRED_GATE_NAME}; refusing to preserve." >&2 - exit 1 -fi - -authoritative_rows=() -pending_rows=() -job_lookup_retryable=false -retry_reason="" -retry_error_text="" -candidate_ambiguous=false -while IFS=$'\t' read -r app_slug check_name details_url check_run_id check_status conclusion completed_at started_at; do - if [[ -z "${app_slug}${check_name}${details_url}${check_run_id}${check_status}${conclusion}${completed_at}${started_at}" ]]; then - continue - fi - if [[ "${app_slug}" != "github-actions" || - "${check_name}" == "__missing__" || - "${check_name}" != "${REQUIRED_GATE_NAME}" || - "${details_url}" == "__missing__" || - "${check_run_id}" == "__missing__" || - "${check_status}" == "__missing__" || - ! "${check_run_id}" =~ ^[0-9]+$ ]]; then - candidate_ambiguous=true - continue - fi - [[ "${conclusion}" == "__null__" ]] && conclusion="" - [[ "${completed_at}" == "__null__" ]] && completed_at="" - [[ "${started_at}" == "__null__" ]] && started_at="" - if [[ ! "${details_url}" =~ /actions/runs/([0-9]+)/job/([0-9]+)([?#].*)?$ ]]; then - candidate_ambiguous=true - continue - fi - workflow_run_id="${BASH_REMATCH[1]}" - job_id="${BASH_REMATCH[2]}" - - workflow_run_json="${workflow_run_cache[${workflow_run_id}]:-}" - if [[ -z "${workflow_run_json}" ]]; then - : >"${api_error_file}" - set +e - workflow_run_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/actions/runs/${workflow_run_id}" \ - 2>"${api_error_file}")" - workflow_run_status=$? - set -e - if [[ "${workflow_run_status}" -ne 0 ]]; then - workflow_run_error="$(<"${api_error_file}")" - if is_retryable_gh_failure "${workflow_run_status}" "${workflow_run_error}"; then - job_lookup_retryable=true - retry_reason="workflow-run API lookup" - retry_error_text="${workflow_run_error}" - break - fi - echo "Permanent GitHub API/configuration failure while identifying prior ${REQUIRED_GATE_NAME} workflow run; refusing to preserve." >&2 - [[ -z "${workflow_run_error}" ]] || printf '%s\n' "${workflow_run_error}" >&2 - exit 1 - fi - workflow_run_cache["${workflow_run_id}"]="${workflow_run_json}" - fi - set +e - workflow_run_identity_state="$(jq -r \ - --arg expected_id "${workflow_run_id}" \ - --arg expected_workflow_id "${expected_workflow_id}" \ - --arg expected_name "${EXPECTED_WORKFLOW_NAME}" \ - --arg expected_path "${EXPECTED_WORKFLOW_PATH}" \ - --arg expected_head "${HEAD_SHA}" \ - --arg expected_base "${BASE_SHA}" \ - --arg expected_repository "${GITHUB_REPOSITORY}" \ - --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 - | 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.path == $expected_path or - ( - ($run.path | startswith($expected_path + "@")) and - (($run.path | ltrimstr($expected_path + "@")) | test("^.+$")) - ) - ) and - $run.head_sha == $expected_head and - $run.repository.full_name == $expected_repository and - $run.event == "pull_request" and - (($run.pull_requests // null) | type) == "array" and - ( - (($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) - ) - then - if ($run.display_title // null) == $expected_display_title then - "current" - elif (($run.pull_requests | length) > 0) and - $title.name == $expected_name and $title.pr == $expected_pr and - any($run.pull_requests[]; - ((.number // null) | tostring) == $expected_pr and - (.base.sha // "") == $title.base and - (.head.sha // "") == $title.head and - ((.base.sha // "") != $expected_base or (.head.sha // "") != $expected_head)) - then - "stale" - else - "invalid" - end - else "invalid" end' \ - <<<"${workflow_run_json}" 2>>"${api_error_file}")" - workflow_run_query_status=$? - set -e - if [[ "${workflow_run_query_status}" -ne 0 || - ( "${workflow_run_identity_state}" != "current" && - "${workflow_run_identity_state}" != "stale" ) ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${workflow_run_identity_state}" == "stale" ]]; then - continue - fi - job_json="${job_cache[${job_id}]:-}" - job_is_pending=false - job_was_fetched=false - case "${check_status}" in - queued|in_progress|requested|waiting|pending) job_is_pending=true ;; - esac - if [[ -z "${job_json}" || "${job_is_pending}" == "true" ]]; then - : >"${api_error_file}" - set +e - job_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/actions/jobs/${job_id}" \ - 2>"${api_error_file}")" - job_status=$? - job_was_fetched=true - set -e - if [[ "${job_status}" -ne 0 ]]; then - job_error="$(<"${api_error_file}")" - if is_retryable_gh_failure "${job_status}" "${job_error}"; then - job_lookup_retryable=true - retry_reason="job API lookup" - retry_error_text="${job_error}" - break - fi - echo "Permanent GitHub API/configuration failure while identifying a prior ${REQUIRED_GATE_NAME} run; refusing to preserve." >&2 - [[ -z "${job_error}" ]] || printf '%s\n' "${job_error}" >&2 - exit 1 - fi - fi - - set +e - job_identity_ok="$(jq -r \ - --arg expected_job_id "${job_id}" \ - --arg expected_run_id "${workflow_run_id}" \ - --arg expected_gate_name "${REQUIRED_GATE_NAME}" \ - --arg expected_workflow_name "${EXPECTED_WORKFLOW_NAME}" \ - --arg expected_display_title "${expected_display_title}" \ - --arg expected_head "${HEAD_SHA}" \ - --arg expected_check_run_id "${check_run_id}" \ - 'if (.id | type) == "number" and - (.run_id | type) == "number" and - .id == ($expected_job_id | tonumber) and - .run_id == ($expected_run_id | tonumber) and - .name == $expected_gate_name and - (.workflow_name == $expected_workflow_name or - .workflow_name == $expected_display_title) and - .head_sha == $expected_head and - ((.check_run_url // "") | endswith("/check-runs/\($expected_check_run_id)")) - then "true" else "false" end' \ - <<<"${job_json}" 2>>"${api_error_file}")" - job_identity_query_status=$? - set -e - if [[ "${job_identity_query_status}" -ne 0 || - "${job_identity_ok}" != "true" ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${job_was_fetched}" == "true" ]]; then - job_cache["${job_id}"]="${job_json}" - fi - set +e - preserve_step_conclusion="$(jq -r ' - [.steps[]? - | select(.name == "Preserve successful required gate on metadata-only edit") - | (.conclusion // "") - ] - | if length == 1 then .[0] else "unknown" end - ' <<<"${job_json}" 2>>"${api_error_file}")" - job_query_status=$? - set -e - if [[ "${job_query_status}" -ne 0 ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/ci.yml" && - "${EXPECTED_WORKFLOW_NAME}" == "CI — Validation" && - "${REQUIRED_GATE_NAME}" == "Validation Gate" && - "${check_status}" == "completed" && - ( "${preserve_step_conclusion}" == "unknown" || -z "${preserve_step_conclusion}" ) ]]; then - case "${conclusion}" in - cancelled|skipped|stale) ;; - *) - preserve_step_state="$(jq -r ' - if (.steps // null) == null then "absent" - elif (.steps | type) != "array" or any(.steps[]; type != "object" or (.name | type) != "string") then "invalid" - else - [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $matches - | if ($matches | length) == 0 then "absent" - elif ($matches | length) == 1 then "present" - else "invalid" end - end - ' <<<"${job_json}" 2>>"${api_error_file}")" || { - candidate_ambiguous=true - continue - } - if [[ "${preserve_step_state}" == "invalid" ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${preserve_step_state}" == "absent" ]]; then - if recover_validation_job_from_attempt; then - job_json="${attempt_recovered_job_json}" - job_cache["${job_id}"]="${job_json}" - preserve_step_state="$(jq -r ' - if (.steps | type) != "array" or any(.steps[]; type != "object" or (.name | type) != "string") then "invalid" - else - [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $matches - | if ($matches | length) == 0 then "absent" - elif ($matches | length) == 1 then "present" - else "invalid" end - end - ' <<<"${job_json}" 2>>"${api_error_file}")" || { - candidate_ambiguous=true - continue - } - if [[ "${preserve_step_state}" == "invalid" ]]; then - candidate_ambiguous=true - continue - fi - preserve_step_conclusion="$(jq -r ' - [.steps[]? - | select(.name == "Preserve successful required gate on metadata-only edit") - | (.conclusion // "") - ] - | if length == 1 then .[0] else "unknown" end - ' <<<"${job_json}" 2>>"${api_error_file}")" || { - candidate_ambiguous=true - continue - } - else - recovery_status=$? - if [[ "${recovery_status}" -eq 3 ]]; then exit 1; fi - fi - fi - ;; - esac - fi - if [[ "${preserve_step_conclusion}" == "unknown" || - -z "${preserve_step_conclusion}" ]]; then - if [[ "${check_status}" == "completed" ]]; then - case "${conclusion}" in - cancelled|skipped|stale) continue ;; - esac - # An unresolved completed snapshot may hide substantive failure. - candidate_ambiguous=true - continue - elif [[ "${job_is_pending}" == "true" ]]; then - : # A nonterminal job may not have reached its preservation step yet. - else - candidate_ambiguous=true - continue - fi - elif [[ "${preserve_step_conclusion}" != "skipped" ]]; then - case "${preserve_step_conclusion}" in - success|failure|neutral|cancelled|timed_out|action_required|stale) - continue - ;; - *) candidate_ambiguous=true; continue ;; - esac - fi - - # Failed cancelled aggregates require complete proof before being treated as - # missing validation. Unavailable or different evidence retains failure. - if [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/ci.yml" && - "${EXPECTED_WORKFLOW_NAME}" == "CI — Validation" && "${REQUIRED_GATE_NAME}" == "Validation Gate" && - "${check_status}" == completed && "${conclusion}" == failure ]]; then - if validation_cancelled_before_checks; then - echo "Cancelled Validation aggregate has no executed prerequisite checks; original proof remains missing." >&2 - continue - fi - fi - - case "${check_status}" in - completed) - case "${conclusion}" in - success|failure|neutral|cancelled|skipped|timed_out|action_required|stale) ;; - *) candidate_ambiguous=true; continue ;; - esac - if [[ -n "${conclusion}" && -n "${completed_at}" && - -n "${started_at}" ]] && - is_github_timestamp "${completed_at}" && - is_github_timestamp "${started_at}"; then - if [[ "${conclusion}" != "cancelled" && - "${conclusion}" != "skipped" && - "${conclusion}" != "stale" ]]; then - authoritative_rows+=("${completed_at}"$'\t'"${workflow_run_id}"$'\t'"${check_run_id}"$'\t'"${job_id}"$'\tcompleted\t'"${conclusion}") - fi - else - candidate_ambiguous=true - fi - ;; - queued|in_progress|requested|waiting|pending) - if [[ -z "${conclusion}" && -z "${completed_at}" ]] && - { [[ -z "${started_at}" ]] || is_github_timestamp "${started_at}"; }; then - started_at="${started_at:-9999-12-31T23:59:59Z}" - pending_rows+=("${started_at}"$'\t'"${workflow_run_id}"$'\t'"${check_run_id}"$'\t'"${job_id}"$'\tpending\t'"${check_status}"$'\t'"${preserve_step_conclusion}") - else - candidate_ambiguous=true - fi - ;; - *) candidate_ambiguous=true ;; - esac -done <<<"${candidate_rows}" - -if [[ "${job_lookup_retryable}" == "true" ]]; then - echo "Required-gate assessment could not resolve ${retry_reason}; refusing to preserve." >&2 - [[ -z "${retry_error_text}" ]] || printf '%s\n' "${retry_error_text}" >&2 - exit 1 -fi -if [[ "${candidate_ambiguous}" == "true" ]]; then - echo "Ambiguous prior ${REQUIRED_GATE_NAME} run metadata; refusing to preserve." >&2 - exit 1 -fi - -prior_status="" -prior_conclusion="" -if ((${#authoritative_rows[@]} > 0)); then - prior_row="$(printf '%s\n' "${authoritative_rows[@]}" | LC_ALL=C sort -t $'\t' -k1,1 -k2,2n -k3,3n -k4,4n | tail -n 1)" -elif ((${#pending_rows[@]} > 0)); then - prior_row="$(printf '%s\n' "${pending_rows[@]}" | LC_ALL=C sort -t $'\t' -k1,1 -k2,2n -k3,3n -k4,4n | tail -n 1)" -else - prior_row=$'none\tnone\tnone\tnone\tnone\t' -fi -IFS=$'\t' read -r _prior_sort _prior_run _prior_check _prior_job prior_status prior_conclusion _prior_preserve_step <<< "${prior_row}" -if [ "${prior_status}" = "completed" ]; then - if [ "${prior_conclusion}" = "success" ]; then - # Opt-in provenance exposes the already selected source; it changes neither - # ordering nor candidate eligibility, and ordinary action output stays stable. - if [[ "${REQUIRED_GATE_INCLUDE_SOURCE:-false}" == true ]]; then - source_attempt="$(jq -er '.run_attempt | select(type == "number" and . > 0 and . == floor)' \ - <<<"${job_cache[${_prior_job}]}")" || exit 1 - printf 'source_run_id=%s\nsource_job_id=%s\nsource_check_run_id=%s\nsource_run_attempt=%s\n' \ - "${_prior_run}" "${_prior_job}" "${_prior_check}" "${source_attempt}" >>"${GITHUB_OUTPUT}" - fi - report_assessment success - exit 0 - fi - echo "Prior ${REQUIRED_GATE_NAME} for unchanged head ${HEAD_SHA} concluded ${prior_conclusion:-unknown}." >&2 - exit 1 -fi -if [[ "${prior_status}" == none || "${prior_status}" == pending ]]; then - defer_dependency -fi -echo "Unexpected prior ${REQUIRED_GATE_NAME} selection state ${prior_status:-unknown}; refusing to preserve." >&2 -exit 1 diff --git a/.github/actions/preserve-required-gate/resolve-deferred-gate.sh b/.github/actions/preserve-required-gate/resolve-deferred-gate.sh deleted file mode 100644 index 1c5aaeef35..0000000000 --- a/.github/actions/preserve-required-gate/resolve-deferred-gate.sh +++ /dev/null @@ -1,641 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -fail_closed() { - echo "$*" >&2 - exit 1 -} -resolution_phase="${1:-admit}" -case "${resolution_phase}" in - preflight|admit|reconcile) ;; - *) fail_closed "Unsupported resolver phase." ;; -esac -report_eligible() { - if [[ "${resolution_phase}" == preflight ]]; then - [[ -n "${GITHUB_OUTPUT:-}" ]] || fail_closed "Preflight requires GITHUB_OUTPUT." - printf 'eligible=%s\n' "$1" >>"${GITHUB_OUTPUT}" - elif [[ "$1" == false && -n "${GITHUB_OUTPUT:-}" ]]; then - # Successful early no-ops also need an explicit empty confirmation. - printf 'accepted_job_ids=[]\n' >>"${GITHUB_OUTPUT}" - fi -} - -[[ "${GITHUB_EVENT_NAME:-}" == workflow_run ]] || fail_closed "Resolver requires workflow_run context." -for required_variable in GH_TOKEN GITHUB_REPOSITORY GITHUB_EVENT_PATH GITHUB_RUN_ID; do - [[ -n "${!required_variable:-}" ]] || fail_closed "Resolver is missing ${required_variable}." -done -[[ "${resolution_phase}" != admit || -n "${GITHUB_OUTPUT:-}" ]] || - fail_closed "Admission requires GITHUB_OUTPUT for acknowledged job IDs." -source_run_id="$(jq -er '.workflow_run.id | select(type == "number" and . > 0 and . == floor)' "${GITHUB_EVENT_PATH}")" -source_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${source_run_id}")" -workflow_path="$(jq -er '.path | select(type == "string")' <<<"${source_json}")" -workflow_file="${workflow_path%%@*}" -case "${workflow_file}" in - .github/workflows/ci.yml) workflow_name='CI — Validation'; gate_name='Validation Gate' ;; - .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' ;; - *) fail_closed "Source does not own a supported required gate." ;; -esac -workflow_filename="${workflow_file##*/}" -workflow_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_filename}")" -workflow_id="$(jq -er --arg name "${workflow_name}" --arg path "${workflow_file}" ' - select(.name == $name and .path == $path) - | .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})$") - | 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}")" -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 - (.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 || - fail_closed "Source workflow identity is not attributable." -jq -e --argjson id "${source_run_id}" --argjson workflow_id "${workflow_id}" --arg head "${head_sha}" ' - .action == "completed" and .workflow_run.id == $id and - .workflow_run.workflow_id == $workflow_id and .workflow_run.head_sha == $head - and .workflow_run.event == "pull_request"' "${GITHUB_EVENT_PATH}" >/dev/null || - fail_closed "Completion event does not match the source workflow." - -# Resolver reruns retain their ID, and latest job snapshots can hide an older -# ambiguous admission. Neither the current nor historical resolver may rerun -# automatically; explicit recovery must establish a separate safe boundary. -resolver_path='.github/workflows/resolve-required-gates.yml' -resolver_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/resolve-required-gates.yml")" -resolver_id="$(jq -er --arg path "${resolver_path}" ' - select(.name == "Resolve Required Gates" and .path == $path) - | .id | select(type == "number" and . > 0 and . == floor)' <<<"${resolver_json}")" -current_resolver_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}")" -jq -e --argjson id "${GITHUB_RUN_ID}" --argjson workflow_id "${resolver_id}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg path "${resolver_path}" \ - --arg title "Resolve Required Gates workflow-${workflow_id} head-${head_sha} source-${source_run_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 - (.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." -current_resolver_created="$(jq -er '.created_at' <<<"${current_resolver_json}")" - -current_pr() { - gh api --method GET "/repos/${GITHUB_REPOSITORY}/pulls/${pr_number}" -} -pr_is_current() { - jq -e --arg repository "${GITHUB_REPOSITORY}" --arg head "${head_sha}" \ - --arg base "${base_sha}" --arg branch "${head_branch}" --argjson pr "${pr_number}" \ - --arg base_branch "${base_branch:-}" --arg head_repository "${head_repository:-}" ' - .number == $pr and .state == "open" and .base.repo.full_name == $repository and - .base.sha == $base and .head.sha == $head and .head.ref == $branch and - (.base.ref | type) == "string" and (.base.ref | length) > 0 and - (.head.repo.full_name | type) == "string" and (.head.repo.full_name | length) > 0 and - ($base_branch == "" or .base.ref == $base_branch) and - ($head_repository == "" or .head.repo.full_name == $head_repository)' <<<"$1" >/dev/null -} -pr_json="$(current_pr)" -if ! pr_is_current "${pr_json}"; then - echo "Source tuple is obsolete; no gate is rerun." - report_eligible false - exit 0 -fi -head_repository="$(jq -er '.head.repo.full_name' <<<"${pr_json}")" -base_branch="$(jq -er '.base.ref' <<<"${pr_json}")" - -# Supplementary statuses may withhold native proof but never replace it. -# This phase does not enter the legacy targeted-rerun admission protocol. -if [[ "${resolution_phase}" == reconcile ]]; then - latest_barrier() { - local inventory='[]' page rows prefix found - # GitHub returns newest first; stop at the first exact context, regardless - # of its actor. Exhaust history only to establish absence, never ownership. - for page in {1..10}; do - rows="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/statuses/${head_sha}" -f per_page=100 -f page="${page}")" || return 1 - prefix="$(jq -ce --arg context "${gate_name}" ' - if type != "array" or length > 100 then error("invalid status page") else . end - | (map(if type == "object" then .context == $context else false end) | index(true)) as $index - | {found: ($index != null), rows: (if $index == null then . else .[0:($index + 1)] end)}' <<<"${rows}")" || return 1 - found="$(jq -r .found <<<"${prefix}")" - inventory="$(jq -cs '.[0] + .[1].rows' <(printf '%s\n' "${inventory}") <(printf '%s\n' "${prefix}"))" || return 1 - jq -e --arg url "https://api.github.com/repos/${GITHUB_REPOSITORY}/statuses/${head_sha}" ' - all(.[]; type == "object" and (.context | type) == "string" and (.context | length) > 0 and - (.id | type) == "number" and .id > 0 and (.id | floor) == .id and .url == $url) and - ([.[].id] | unique | length) == length' <<<"${inventory}" >/dev/null || return 1 - if [[ "${found}" == true ]]; then jq -c '.[-1]' <<<"${inventory}"; return 0; fi - if [[ "$(jq length <<<"${rows}")" -lt 100 ]]; then printf 'null\n'; return 0; fi - done - return 1 # Budget exhaustion cannot establish absence. - } - barrier="$(latest_barrier)" || fail_closed "Supplementary status inventory is unavailable or ambiguous." - if [[ "${barrier}" == null ]]; then exit 0; fi - if ! jq -e '(.state == "pending" or .state == "failure" or .state == "error") and .creator.id == 41898282 and - .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - (.id | type == "number" and . > 0 and . == floor)' <<<"${barrier}" >/dev/null; then - exit 0 # Foreign or already terminal statuses are not ours to modify. - fi - target_url="$(jq -er '.target_url' <<<"${barrier}")" - url_prefix="https://github.com/${GITHUB_REPOSITORY}/actions/runs/" - [[ "${target_url}" == "${url_prefix}"* ]] || exit 0 - target_suffix="${target_url#"${url_prefix}"}" - [[ "${target_suffix}" =~ ^([1-9][0-9]*)/attempts/([1-9][0-9]*)$ ]] || exit 0 - bridge_run_id="${BASH_REMATCH[1]}" - bridge_attempt="${BASH_REMATCH[2]}" - bridge_native() { - local target jobs check check_id historical_title - 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})$") - | 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}" \ - --arg head_repo "${head_repository}" --arg head "${head_sha}" --arg branch "${head_branch}" \ - --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 - (.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 - ((.status == "queued" or .status == "in_progress" or .status == "waiting" or - .status == "pending" or .status == "requested") and .conclusion == null)) and - (.pull_requests | type == "array") and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr))' <<<"${target}" >/dev/null || return 1 - jobs="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${bridge_run_id}/attempts/${bridge_attempt}/jobs" \ - -f per_page=100 --paginate --slurp)" || return 1 - jobs="$(jq -ce --arg name "${gate_name}" --arg head "${head_sha}" --argjson run "${bridge_run_id}" ' - if type != "array" or length == 0 or any(.[]; type != "object" or (.jobs | type) != "array") - then error("malformed jobs") else . end - | .[0].total_count as $total - | if ($total | type) != "number" or $total < 0 or ($total | floor) != $total or - any(.[]; .total_count != $total) or ([.[].jobs[]] | length) != $total or - ([.[].jobs[].id] | unique | length) != $total then error("incomplete jobs") else . end - | [.[].jobs[] | select(.name == $name)] - | if length != 1 then error("ambiguous gate") else .[0] end - | select(.run_id == $run and .head_sha == $head) - | select((.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "queued" or .status == "in_progress" or .status == "waiting" or - .status == "pending" or .status == "requested") and .conclusion == null)) -' <<<"${jobs}")" || return 1 - check_id="$(jq -er '.check_run_url | capture("/check-runs/(?[1-9][0-9]*)$").id' <<<"${jobs}")" || return 1 - check="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/check-runs/${check_id}")" || return 1 - jq -e --argjson id "${check_id}" --arg head "${head_sha}" --arg name "${gate_name}" \ - --argjson job "${jobs}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and - .head_sha == $head and .name == $name and .status == $job.status and - .conclusion == $job.conclusion' <<<"${check}" >/dev/null || return 1 - # Keep the full native snapshot for the immediate pre-POST comparison. - jq -cn --argjson run "${target}" --argjson job "${jobs}" --argjson check "${check}" \ - '{run: $run, job: $job, check: $check}' - } - native="$(bridge_native)" || fail_closed "Supplementary barrier lacks bound native metadata evidence." - # Historical metadata proves ownership, including an acknowledged publication - # followed by cancellation/failure. It never supplies current-base proof. - jq -e '[.job.steps[]? | select(.name == "Publish pending required gate status" and - ((.status == "in_progress" and .conclusion == null) or - (.status == "completed" and (.conclusion == "success" or .conclusion == "failure" or - .conclusion == "cancelled" or .conclusion == "timed_out" or .conclusion == "action_required"))))] - | length == 1' <<<"${native}" >/dev/null || - fail_closed "Supplementary barrier lacks attributable publication ownership." - assessment_output="$(mktemp)" - trap 'rm -f "$assessment_output"' EXIT - terminal_state=failure - selected_native='' - # Exclude the historical metadata barrier, not the completion callback's - # original run. The selector still applies its exact CURRENT base/head tuple. - if GITHUB_EVENT_NAME=pull_request GITHUB_RUN_ID="${bridge_run_id}" \ - BASE_SHA="${base_sha}" HEAD_SHA="${head_sha}" PR_NUMBER="${pr_number}" \ - REQUIRED_GATE_NAME="${gate_name}" EXPECTED_WORKFLOW_NAME="${workflow_name}" \ - EXPECTED_WORKFLOW_FILE="${workflow_filename}" EXPECTED_WORKFLOW_PATH="${workflow_file}" \ - REQUIRED_GATE_INCLUDE_SOURCE=true GITHUB_OUTPUT="${assessment_output}" \ - bash "$(dirname "${BASH_SOURCE[0]}")/assess-required-gate.sh"; then - if [[ "$(<"${assessment_output}")" == assessment=dependency-deferred ]]; then exit 0; fi - selected="$(jq -Rsc ' - split("\n") | map(select(length > 0) | split("=")) - | if length != 5 or any(.[]; length != 2) or (map(.[0]) | unique | length) != 5 - then error("ambiguous source provenance") else map({key: .[0], value: .[1]}) | from_entries end - | select(.assessment == "success") - | select((keys | sort) == (["assessment", "source_run_id", "source_job_id", "source_check_run_id", "source_run_attempt"] | sort)) - | select([.source_run_id, .source_job_id, .source_check_run_id, .source_run_attempt] - | all(.[]; test("^[1-9][0-9]*$")))' "${assessment_output}")" || - fail_closed "Selected source provenance is unavailable." - [[ -n "${selected}" ]] || fail_closed "Selected source provenance is malformed." - selected_run="$(jq -r .source_run_id <<<"${selected}")" - selected_job="$(jq -r .source_job_id <<<"${selected}")" - selected_check="$(jq -r .source_check_run_id <<<"${selected}")" - selected_attempt="$(jq -r .source_run_attempt <<<"${selected}")" - selected_source_title="${workflow_name} pr-${pr_number} base-${base_sha} head-${head_sha}" - selected_source_native() { - local run job check preserve_step_state recovered - run="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${selected_run}/attempts/${selected_attempt}")" || return 1 - jq -e --argjson id "${selected_run}" --argjson attempt "${selected_attempt}" --argjson workflow "${workflow_id}" \ - --arg repo "${GITHUB_REPOSITORY}" --arg head_repo "${head_repository}" --arg head "${head_sha}" \ - --arg branch "${head_branch}" --arg title "${selected_source_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 - (.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 - job="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/jobs/${selected_job}")" || return 1 - jq -e --argjson id "${selected_job}" --argjson run "${selected_run}" --argjson attempt "${selected_attempt}" \ - --arg name "${gate_name}" --arg head "${head_sha}" \ - --arg url "https://api.github.com/repos/${GITHUB_REPOSITORY}/check-runs/${selected_check}" ' - .id == $id and .run_id == $run and .run_attempt == $attempt and .head_sha == $head and - .name == $name and .status == "completed" and .conclusion == "success" and .check_run_url == $url' \ - <<<"${job}" >/dev/null || return 1 - preserve_step_state="$(jq -er ' - if .steps == null then "absent" - elif (.steps | type) != "array" or any(.steps[]; type != "object" or (.name | type) != "string") then - error("malformed selected job steps") - else - [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $matches - | if ($matches | length) == 0 then "absent" - elif ($matches | length) > 1 then "duplicate" - elif $matches[0].status == "completed" and $matches[0].conclusion == "skipped" then "skipped" - else "conflict" end - end - ' <<<"${job}")" || return 1 - if [[ "${preserve_step_state}" == absent ]]; then - [[ "${workflow_file}" == ".github/workflows/ci.yml" && - "${workflow_name}" == "CI — Validation" && "${gate_name}" == "Validation Gate" ]] || return 1 - recovered="$(bash "$(dirname "${BASH_SOURCE[0]}")/validate-exact-attempt-gate.sh" \ - "${selected_run}" "${selected_attempt}" "${selected_job}" "${selected_check}" \ - "${gate_name}" "${workflow_id}" "${workflow_name}" "${workflow_file}" \ - "${selected_source_title}" "${pr_number}" "${base_sha}" "${head_sha}" \ - "${head_branch}" "${GITHUB_REPOSITORY}" "${head_repository}" \ - completed success "" "" "" true)" || return 1 - printf '%s\n' "${recovered}" - return 0 - fi - [[ "${preserve_step_state}" == skipped ]] || return 1 - check="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/check-runs/${selected_check}")" || return 1 - jq -e --argjson id "${selected_check}" --arg head "${head_sha}" --arg name "${gate_name}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and .head_sha == $head and - .name == $name and .status == "completed" and .conclusion == "success"' <<<"${check}" >/dev/null || return 1 - jq -cnS --argjson run "${run}" --argjson job "${job}" --argjson check "${check}" \ - '{run: $run, jobs: null, job: $job, check: $check}' - } - selected_native="$(selected_source_native)" || fail_closed "Selected current-base source lacks independent native proof." - terminal_state=success - fi - pr_json="$(current_pr)" - pr_is_current "${pr_json}" || exit 0 - fresh_native="$(bridge_native)" || fail_closed "Native supplementary evidence changed or became unavailable." - [[ "${fresh_native}" == "${native}" ]] || exit 0 - if [[ "${terminal_state}" == success ]]; then - fresh_selected="$(selected_source_native)" || fail_closed "Selected current-base native proof became unavailable." - [[ "${fresh_selected}" == "${selected_native}" ]] || exit 0 - fi - fresh_barrier="$(latest_barrier)" || fail_closed "Latest supplementary status became unavailable." - [[ "${fresh_barrier}" == "${barrier}" ]] || exit 0 - # Commit Status writes have no conditional-update primitive. Do not replay an - # unacknowledged POST; later callbacks re-read the latest native/API evidence. - gh api --method POST "/repos/${GITHUB_REPOSITORY}/statuses/${head_sha}" \ - -f state="${terminal_state}" -f context="${gate_name}" -f target_url="${target_url}" \ - -f description="Metadata gate original proof: ${terminal_state}" >/dev/null || - fail_closed "Supplementary status POST was rejected or ambiguous." - exit 0 -fi - -# A capped exact-head query bounds both target discovery and the native history -# window. Resolver completions cannot predate their source creation. Twenty -# retained sources is the source-discovery limit. Resolver history uses -# separate bounded pagination; partial evidence always requires recovery. -evidence_limit=20 -source_listing_read_limit=3 -source_listing_attempt=0 -source_listing_result='' -while (( source_listing_attempt < source_listing_read_limit )); do - source_listing_attempt=$((source_listing_attempt + 1)) - run_pages="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_filename}/runs" \ - -f event=pull_request -f head_sha="${head_sha}" -f per_page="${evidence_limit}")" - if ! source_listing_result="$(jq -cer --argjson limit "${evidence_limit}" --argjson source "${source_run_id}" \ - --argjson workflow_id "${workflow_id}" --arg repository "${GITHUB_REPOSITORY}" --arg head "${head_sha}" ' - def listed_count: - if type != "object" then null - elif (.workflow_runs | type) == "array" then (.workflow_runs | length) else null end; - def source_present: - if type != "object" then false - elif (.workflow_runs | type) == "array" then - any(.workflow_runs[]; if type == "object" then .id == $source else false end) - else false end; - def outcome($classification): { - classification: $classification, - total_count: (if type == "object" then (.total_count // null) else null end), - returned_rows: listed_count, - source_present: source_present - }; - if type != "object" then outcome("malformed-response") - elif (.workflow_runs | type) != "array" then outcome("malformed-workflow-runs") - elif (.total_count | type) != "number" or .total_count < 0 or .total_count != (.total_count | floor) then - outcome("malformed-total-count") - elif .total_count > $limit then outcome("overflow-total-count") - elif any(.workflow_runs[]; type != "object") then outcome("malformed-row") - elif any(.workflow_runs[]; - (.id | type) != "number" or .id <= 0 or .id != (.id | floor)) then outcome("malformed-row-id") - elif any(.workflow_runs[]; (.repository | type) != "object") then outcome("malformed-row-repository") - elif any(.workflow_runs[]; - .workflow_id != $workflow_id or .repository.full_name != $repository or - .head_sha != $head or .event != "pull_request") then outcome("identity-mismatch") - elif any(.workflow_runs[]; - (.created_at | type) != "string" or - (try (.created_at | fromdateiso8601 | type == "number") catch false | not)) then - outcome("malformed-created-at") - elif ([.workflow_runs[].id] | unique | length) != (.workflow_runs | length) then - outcome("duplicate-row-id") - elif (.workflow_runs | length) > .total_count then outcome("malformed-row-count") - elif (.workflow_runs | length) < .total_count then outcome("incomplete-row-count") - elif (source_present | not) then outcome("incomplete-missing-source") - else outcome("complete") end' <<<"${run_pages}")"; then - fail_closed "Exact-head source listing response is not valid JSON." - fi - source_listing_classification="$(jq -er '.classification' <<<"${source_listing_result}")" - case "${source_listing_classification}" in - complete) - break - ;; - incomplete-row-count|incomplete-missing-source) - source_listing_diagnostics="$(jq -er '[.classification, (.total_count // "unknown"), (.returned_rows // "unknown"), .source_present] | @tsv' \ - <<<"${source_listing_result}")" - if (( source_listing_attempt == source_listing_read_limit )); then - fail_closed "Exact-head source coverage remains incomplete after ${source_listing_attempt} reads: classification=${source_listing_classification}, total_count=$(jq -r '.total_count // "unknown"' <<<"${source_listing_result}"), returned_rows=$(jq -r '.returned_rows // "unknown"' <<<"${source_listing_result}"), source_present=$(jq -r '.source_present' <<<"${source_listing_result}"), limit=${evidence_limit}." - fi - echo "Exact-head source listing is incomplete (read ${source_listing_attempt}/${source_listing_read_limit}): ${source_listing_diagnostics}; limit=${evidence_limit}." >&2 - if (( source_listing_attempt == 1 )); then sleep 1; else sleep 2; fi - ;; - *) - fail_closed "Exact-head source coverage rejected: classification=${source_listing_classification}, total_count=$(jq -r '.total_count // "unknown"' <<<"${source_listing_result}"), returned_rows=$(jq -r '.returned_rows // "unknown"' <<<"${source_listing_result}"), source_present=$(jq -r '.source_present' <<<"${source_listing_result}"), limit=${evidence_limit}." - ;; - esac -done -target_ids="$(jq -er '.workflow_runs[].id' <<<"${run_pages}")" - -# Native resolver job/step evidence carries the conservative recovery boundary -# across invocations. A failed or incomplete admission may have sent a POST; -# subsequent callbacks must not guess from a still-visible target attempt 1. -assert_no_ambiguous_admission() { - local resolver_pages resolver_page history_total history_page history_page_count expected_page_records - local prior_ids prior_id prior_json prior_jobs prior_head equal_time_waiting - local prior_admitted_ids prior_admitted_id - # The REST search ceiling is 1,000 records. Fetch explicit pages so neither - # an oversized response nor pagination can start an unbounded history scan. - resolver_pages='[]' - history_total=0 - history_page_count=1 - for (( history_page=1; history_page<=history_page_count; history_page++ )); do - resolver_page="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/resolve-required-gates.yml/runs" \ - -f event=workflow_run -f created=">=${history_start}" -f per_page=100 -f page="${history_page}")" - jq -e '(.workflow_runs | type) == "array" and - (.total_count | type) == "number" and .total_count > 0 and - .total_count == (.total_count | floor) and .total_count <= 1000' \ - <<<"${resolver_page}" >/dev/null || - fail_closed "Resolver history is malformed or exceeds the 1,000-record API ceiling." - if (( history_page == 1 )); then - history_total="$(jq -er '.total_count' <<<"${resolver_page}")" - history_page_count=$(( (history_total + 99) / 100 )) - fi - expected_page_records=$(( history_total - (history_page - 1) * 100 )) - if (( expected_page_records > 100 )); then expected_page_records=100; fi - jq -e --argjson total "${history_total}" --argjson count "${expected_page_records}" ' - .total_count == $total and (.workflow_runs | length) == $count' \ - <<<"${resolver_page}" >/dev/null || - fail_closed "Resolver history page coverage or total count is inconsistent." - resolver_pages="$(printf '%s\n%s\n' "${resolver_pages}" "${resolver_page}" | \ - jq -cs '.[0] + .[1].workflow_runs')" - done - prior_ids="$(jq -r --argjson workflow_id "${resolver_id}" --argjson current "${GITHUB_RUN_ID}" \ - --argjson total "${history_total}" --arg created "${history_start}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg path "${resolver_path}" \ - --arg prefix "Resolve Required Gates workflow-${workflow_id} head-${head_sha} source-" ' - if length != $total or ([.[].id] | unique | length) != $total or - (any(.[]; .id == $current) | not) then error("incomplete or duplicate resolver history") else . end - | if any(.[]; - (.id | type) != "number" or .id <= 0 or .id != (.id | floor) or - .workflow_id != $workflow_id or .repository.full_name != $repository or .event != "workflow_run" or - (.display_title | type) != "string" or - (try ((.created_at | fromdateiso8601) >= ($created | fromdateiso8601)) catch false | not)) - then error("unattributable resolver history") else . end - | [.[] - | select(.workflow_id == $workflow_id and .id != $current and - .repository.full_name == $repository and .event == "workflow_run" and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - (.display_title | startswith($prefix)) and - (.display_title | ltrimstr($prefix) | test("^[1-9][0-9]*$"))) - | .id | select(type == "number" and . > 0 and . == floor)] | unique | .[]' <<<"${resolver_pages}")" - while IFS= read -r prior_id; do - [[ -n "${prior_id}" ]] || continue - prior_json="$(jq -cer --argjson id "${prior_id}" '.[] | select(.id == $id)' <<<"${resolver_pages}")" - jq -e '.run_attempt == 1' <<<"${prior_json}" >/dev/null || - fail_closed "Matching resolver history contains a rerun or unknown attempt; explicit recovery is required." - prior_head="$(jq -er '.head_sha | select(type == "string" and test("^[0-9A-Fa-f]{40}$"))' <<<"${prior_json}")" - # Under this exact workflow/head concurrency group, a later first-attempt - # callback still pending or queued cannot have reached admission. Require - # native creation ordering; listener revision movement cannot start it. - # Missing steps in any - # other state remain potentially admitting evidence, never a clean no-op. - if jq -e --arg created "${current_resolver_created}" ' - (.status == "pending" or .status == "queued") and .conclusion == null and - (try ((.created_at | fromdateiso8601) > ($created | fromdateiso8601)) catch false)' \ - <<<"${prior_json}" >/dev/null; then - continue - fi - # Native creation timestamps have second precision. A tied callback needs - # explicit first-attempt job evidence that nothing started, without guessing - # order from run IDs or ignoring arbitrary missing admission steps. - equal_time_waiting=false - if jq -e --arg created "${current_resolver_created}" ' - (.status == "pending" or .status == "queued") and .conclusion == null and - (try ((.created_at | fromdateiso8601) == ($created | fromdateiso8601)) catch false)' \ - <<<"${prior_json}" >/dev/null; then - equal_time_waiting=true - fi - prior_jobs="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${prior_id}/attempts/1/jobs" \ - -f per_page="${evidence_limit}")" - jq -e --argjson limit "${evidence_limit}" ' - (.jobs | type) == "array" and (.total_count | type) == "number" and - .total_count >= 0 and .total_count <= $limit and - .total_count == (.total_count | floor) and (.jobs | length) == .total_count and - ([.jobs[].id] | unique | length) == .total_count' <<<"${prior_jobs}" >/dev/null || - fail_closed "Prior resolver job coverage is malformed or incomplete." - # Concurrency may evict a pending callback before allocating any job. Only - # an attributable cancelled first attempt with complete explicit zero-job - # coverage proves it never reached admission; missing jobs are not proof. - if jq -e '.status == "completed" and .conclusion == "cancelled"' <<<"${prior_json}" >/dev/null && - jq -e '.total_count == 0 and .jobs == []' <<<"${prior_jobs}" >/dev/null; then - continue - fi - prior_admitted_ids="$(jq -ce --argjson prior_id "${prior_id}" --argjson limit "${evidence_limit}" \ - --arg head "${prior_head}" --argjson equal_time_waiting "${equal_time_waiting}" ' - [.jobs[] | select(.name == "Resolve deferred metadata gate")] - | if length != 1 then error("missing resolver job") else .[0] end - | if (.id | type) != "number" or .id <= 0 or .id != (.id | floor) or - .run_id != $prior_id or .head_sha != $head then error("unattributable resolver job") else . end - | if $equal_time_waiting then - if .status == "queued" and .conclusion == null and - has("started_at") and .started_at == null and - has("completed_at") and .completed_at == null and - (.steps | type) == "array" and - all(.steps[]; .status == "queued" and has("conclusion") and .conclusion == null) - then [] else error("waiting resolver job may have started") end - elif .conclusion == "skipped" then [] - else - [.steps[]? | select(.name == "Admit deferred gate reruns")] as $admission - | if ($admission | length) != 1 or $admission[0].status != "completed" then - error("missing or incomplete admission") - elif $admission[0].conclusion == "skipped" then [] - elif $admission[0].conclusion == "success" then - "Confirm admitted deferred gate jobs " as $prefix - | [.steps[]? | select((.name | type) == "string" and (.name | startswith($prefix)))] as $confirmation - | if ($confirmation | length) != 1 or $confirmation[0].status != "completed" or - $confirmation[0].conclusion != "success" then error("unconfirmed admission") else . end - | $confirmation[0].name | ltrimstr($prefix) as $encoded - | $encoded | fromjson - | if type != "array" then error("malformed admitted job IDs") else . end - | if length > $limit or (unique | length) != length or tojson != $encoded or - (all(.[]; type == "number" and . > 0 and . == floor) | not) then - error("malformed admitted job IDs") else . end - else error("ambiguous admission") end - end' <<<"${prior_jobs}")" || - fail_closed "Prior matching resolver admission is ambiguous or failed; explicit recovery is required." - while IFS= read -r prior_admitted_id; do - previously_admitted_jobs["${prior_admitted_id}"]=true - done < <(jq -r '.[]' <<<"${prior_admitted_ids}") - done <<<"${prior_ids}" -} -declare -A previously_admitted_jobs=() -# Return a gate job identity only from a completed first attempt with the distinct -# deferred failure, created no later than this resolver. This keeps every -# admitting resolver inside the retained target's history window even when an -# older source expires. Per-attempt lookup avoids mistaking old jobs for a current -# attempt; any human rerun also consumes the automatic allowance. -deferred_job_identity() { - local target_run_id="$1" target_json jobs_json - target_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${target_run_id}")" || return 1 - if ! jq -e --argjson id "${target_run_id}" --argjson workflow_id "${workflow_id}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg head_repository "${head_repository}" \ - --arg head "${head_sha}" --arg branch "${head_branch}" --arg title "${source_title}" \ - --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 - (.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 - .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 - (.pull_requests | type) == "array" and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr))' \ - <<<"${target_json}" >/dev/null; then - return 0 - fi - jobs_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${target_run_id}/attempts/1/jobs" \ - -f per_page=100 --paginate --slurp)" || return 1 - jq -er --arg name "${gate_name}" --arg head "${head_sha}" --argjson run_id "${target_run_id}" \ - --arg created "$(jq -er .created_at <<<"${target_json}")" ' - if type != "array" or length == 0 then error("malformed or incomplete target jobs") - elif any(.[]; type != "object" or (.jobs | type) != "array") then error("malformed or incomplete target jobs") - else - .[0].total_count as $total - | if all(.[]; (.total_count | type) == "number" and .total_count >= 0 and - .total_count == (.total_count | floor) and .total_count == $total) - and ([.[].jobs[]] | length) == $total - and all(.[].jobs[]; type == "object" and (.id | type) == "number" and - .id > 0 and .id == (.id | floor)) - and ([.[].jobs[].id] | unique | length) == $total - then . else error("malformed or incomplete target jobs") end - end - | [.[].jobs[] | select(.name == $name)] - | if length != 1 then empty else .[0] end - | select(.run_id == $run_id and .head_sha == $head and .status == "completed" and .conclusion == "failure") - | select([.steps[]? | select(.name == "Preserve successful required gate on metadata-only edit" and - .status == "completed" and .conclusion == "success")] | length == 1) - | select([.steps[]? | select(.name == "Report dependency-deferred required gate" and - .status == "completed" and .conclusion == "failure")] | length == 1) - | select(.id | type == "number" and . > 0 and . == floor) - | [.id, $created] | @tsv' <<<"${jobs_json}" || { - local jq_status=$? - # jq exits 4 for an empty selection: an ordinary failure is not deferred. - [[ "${jq_status}" == 4 ]] || return "${jq_status}" - } -} - -# Freeze eligible native run/job identities before choosing the history floor. -# Later eligibility changes cannot introduce a target outside this covered set. -declare -A candidate_identities=() -candidate_ids=() -candidate_created=() -while IFS= read -r target_run_id; do - [[ -n "${target_run_id}" ]] || continue - identity="$(deferred_job_identity "${target_run_id}")" - [[ -n "${identity}" ]] || continue - candidate_ids+=("${target_run_id}") - candidate_identities["${target_run_id}"]="${identity}" - candidate_created+=("${identity#*$'\t'}") -done <<<"${target_ids}" -if (( ${#candidate_ids[@]} == 0 )); then - report_eligible false - exit 0 -fi -history_start="$(jq -nr --args '$ARGS.positional | min_by(fromdateiso8601)' "${candidate_created[@]}")" -if [[ "${resolution_phase}" == admit ]]; then - assert_no_ambiguous_admission -fi - -assessment_output="$(mktemp)" -trap 'rm -f "$assessment_output"' EXIT -eligible=false -admitted_job_ids=() -for target_run_id in "${candidate_ids[@]}"; do - identity="${candidate_identities["${target_run_id}"]}" - job_id="${identity%%$'\t'*}" - [[ "${previously_admitted_jobs["${job_id}"]:-}" != true ]] || continue - : >"${assessment_output}" - # The child assesses an already-validated target pull_request context. It - # shares the action's exact source selection and cannot write remote state. - if ! GITHUB_EVENT_NAME=pull_request GITHUB_RUN_ID="${target_run_id}" \ - BASE_SHA="${base_sha}" HEAD_SHA="${head_sha}" PR_NUMBER="${pr_number}" \ - REQUIRED_GATE_NAME="${gate_name}" EXPECTED_WORKFLOW_NAME="${workflow_name}" \ - EXPECTED_WORKFLOW_FILE="${workflow_filename}" EXPECTED_WORKFLOW_PATH="${workflow_file}" \ - GITHUB_OUTPUT="${assessment_output}" \ - bash "$(dirname "${BASH_SOURCE[0]}")/assess-required-gate.sh"; then - fail_closed "Original proof is inconclusive or failed; no gate is rerun." - fi - [[ "$(<"${assessment_output}")" == 'assessment=success' ]] || continue - pr_json="$(current_pr)" - pr_is_current "${pr_json}" || continue - # Immediate re-read under workflow-level serialization. This suppresses - # duplicates practically; the API does not document conditional POSTs. - fresh_identity="$(deferred_job_identity "${target_run_id}")" - [[ "${fresh_identity}" == "${identity}" ]] || continue - eligible=true - [[ "${resolution_phase}" != preflight ]] || continue - if ! gh api --method POST "/repos/${GITHUB_REPOSITORY}/actions/jobs/${job_id}/rerun" >/dev/null; then - fail_closed "Targeted rerun outcome is ambiguous or rejected; do not replay the POST. Explicit recovery is required." - fi - admitted_job_ids+=("${job_id}") - previously_admitted_jobs["${job_id}"]=true - echo "Admitted one targeted rerun of deferred gate job ${job_id} in run ${target_run_id}." -done -if [[ "${resolution_phase}" == preflight ]]; then - report_eligible "${eligible}" -else - # Publish only after all POSTs were acknowledged. Partial/ambiguous execution - # has no successful confirmation step and blocks subsequent automation. - admitted_ids_json="$(jq -cn --args '$ARGS.positional | map(tonumber)' "${admitted_job_ids[@]}")" - jq -e --argjson limit "${evidence_limit}" ' - type == "array" and length <= $limit and (unique | length) == length and - all(.[]; type == "number" and . > 0 and . == floor)' <<<"${admitted_ids_json}" >/dev/null || - fail_closed "Acknowledged job IDs are not a bounded attributable set." - printf 'accepted_job_ids=%s\n' "${admitted_ids_json}" >>"${GITHUB_OUTPUT}" -fi diff --git a/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh b/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh deleted file mode 100644 index b68cd0889c..0000000000 --- a/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if [[ "$#" -ne 21 ]]; then - echo "Malformed or unbound exact-attempt evidence: expected 21 identity arguments." >&2 - exit 2 -fi -run_id="$1" -attempt="$2" -job_id="$3" -check_id="$4" -gate_name="$5" -workflow_id="$6" -workflow_name="$7" -workflow_path="$8" -display_title="$9" -pr_number="${10}" -base_sha="${11}" -head_sha="${12}" -head_branch="${13}" -repository="${14}" -head_repository="${15}" -expected_status="${16}" -expected_conclusion="${17}" -expected_details_url="${18}" -expected_started_at="${19}" -expected_completed_at="${20}" -require_skipped="${21}" - -fail_evidence() { - echo "Malformed or unbound exact-attempt evidence: $1" >&2 - exit 2 -} -fail_api() { - echo "GitHub API error while reading exact-attempt $1." >&2 - exit 1 -} -for identity in "$run_id" "$attempt" "$job_id" "$check_id" "$workflow_id" "$pr_number"; do - [[ "$identity" =~ ^[1-9][0-9]*$ ]] || fail_evidence "non-positive native identity" -done -for sha in "$base_sha" "$head_sha"; do - [[ "$sha" =~ ^[0-9A-Fa-f]{40}$ ]] || fail_evidence "invalid PR tuple SHA" -done -[[ "$expected_status" == completed && "$require_skipped" =~ ^(true|false)$ ]] || - fail_evidence "unsupported selected gate state" -[[ -n "$gate_name" && -n "$workflow_name" && -n "$workflow_path" && -n "$display_title" && - -n "$head_branch" && -n "$repository" && -n "$head_repository" ]] || fail_evidence "incomplete expected source tuple" - -if ! attempt_run="$(gh api --method GET "/repos/${repository}/actions/runs/${run_id}/attempts/${attempt}" 2>/dev/null)"; then - fail_api "workflow run" -fi -jq -e --argjson id "$run_id" --argjson attempt "$attempt" --argjson workflow "$workflow_id" \ - --arg repo "$repository" --arg head_repo "$head_repository" --arg name "$workflow_name" \ - --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 - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .display_title == $title 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 - ((.pull_requests | length) == 0 or - (any(.pull_requests[]; .number == $pr) and - all(.pull_requests[] | select(.number == $pr); - ((.base.sha // $base) == $base and (.head.sha // $head) == $head))) ) -' <<<"$attempt_run" >/dev/null || fail_evidence "workflow attempt identity or PR tuple differs" - -if ! attempt_jobs="$(gh api --method GET "/repos/${repository}/actions/runs/${run_id}/attempts/${attempt}/jobs" \ - -f per_page=100 2>/dev/null)"; then - fail_api "complete workflow job snapshot" -fi -attempt_job="$(jq -cer --argjson run "$run_id" --argjson attempt "$attempt" --argjson job "$job_id" \ - --argjson check "$check_id" --arg repo "$repository" --arg head "$head_sha" \ - --arg name "$workflow_name" --arg title "$display_title" --arg branch "$head_branch" --arg gate "$gate_name" \ - --arg status "$expected_status" --arg conclusion "$expected_conclusion" \ - --arg details "$expected_details_url" --arg started "$expected_started_at" \ - --arg completed "$expected_completed_at" --argjson require_skipped "$([[ "$require_skipped" == true ]] && echo true || echo false)" ' - if type != "object" or (.jobs | type) != "array" then error("malformed attempt jobs") else . end - | .total_count as $total | .jobs as $jobs - | if ($total | type) != "number" or $total < 1 or $total > 100 or $total != ($total | floor) or - ($jobs | length) != $total or - 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 - ((.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 - error("incomplete or unbound attempt jobs") - else - [$jobs[] | select(.name == $gate)] as $gate_jobs - | [$jobs[] | select(.id == $job)] as $matches - | if ($gate_jobs | length) != 1 or ($matches | length) != 1 or $gate_jobs[0].id != $job then - error("attempt gate identity is not unique") - else $matches[0] end - | . as $selected - | ($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 - .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 - .status != $status or (.conclusion // "") != $conclusion or - ($details != "" and $html != $details) or - ($started != "" and (.started_at // "") != $started) or - ($completed != "" and (.completed_at // "") != $completed) or - (.steps | type) != "array" then - error("attempt gate identity differs") - else . end - | [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $preserve - | if ($preserve | length) > 1 or - ($require_skipped and (($preserve | length) != 1 or $preserve[0].status != "completed" or $preserve[0].conclusion != "skipped")) then - error("attempt preservation-step evidence differs") - else . end - end - ' <<<"$attempt_jobs")" || fail_evidence "complete structured workflow jobs or selected gate differ" - -if ! check="$(gh api --method GET "/repos/${repository}/check-runs/${check_id}" 2>/dev/null)"; then - fail_api "selected native CheckRun" -fi -jq -e --argjson id "$check_id" --argjson job "$attempt_job" --arg head "$head_sha" \ - --arg name "$gate_name" --arg status "$expected_status" --arg conclusion "$expected_conclusion" \ - --arg details "$expected_details_url" --arg started "$expected_started_at" --arg completed "$expected_completed_at" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and - .head_sha == $head and .name == $name and .status == $status and - (.conclusion // "") == $conclusion and .details_url == $job.html_url and - (.started_at // "") == ($job.started_at // "") and - (.completed_at // "") == ($job.completed_at // "") and - ($details == "" or .details_url == $details) and - ($started == "" or (.started_at // "") == $started) and - ($completed == "" or (.completed_at // "") == $completed) -' <<<"$check" >/dev/null || fail_evidence "selected native CheckRun differs from its exact-attempt gate job" - -jq -cnS --argjson run "$attempt_run" --argjson jobs "$attempt_jobs" \ - --argjson job "$attempt_job" --argjson check "$check" \ - '{run: $run, jobs: ($jobs.jobs | sort_by(.id)), job: $job, check: $check}' diff --git a/.github/actions/publish-required-gate-status/action.yml b/.github/actions/publish-required-gate-status/action.yml deleted file mode 100644 index b0593dd494..0000000000 --- a/.github/actions/publish-required-gate-status/action.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Publish Required Gate Status -description: Publish an attributable supplementary metadata gate status after canonical assessment. -inputs: - assessment: - description: Canonical preservation assessment. - required: true - gate-name: - description: Exact required gate context. - required: true - workflow-name: - description: Exact owning workflow name. - required: true - workflow-file: - description: Owning workflow filename. - required: true - workflow-path: - description: Exact owning workflow path. - required: true -outputs: - publication: - description: pending-acknowledged, success-acknowledged, or unchanged. - value: ${{ steps.publish.outputs.publication }} -runs: - using: composite - steps: - - name: Set up canonical GitHub CLI - uses: ./.github/actions/setup-gh - - name: Publish supplementary required gate status - id: publish - shell: bash - env: - GH_TOKEN: ${{ github.token }} - ASSESSMENT: ${{ inputs.assessment }} - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - REQUIRED_GATE_NAME: ${{ inputs.gate-name }} - EXPECTED_WORKFLOW_NAME: ${{ inputs.workflow-name }} - EXPECTED_WORKFLOW_FILE: ${{ inputs.workflow-file }} - EXPECTED_WORKFLOW_PATH: ${{ inputs.workflow-path }} - run: bash "$GITHUB_ACTION_PATH/publish-required-gate-status.sh" 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 deleted file mode 100644 index ae09f293a3..0000000000 --- a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -fail_closed() { echo "$*" >&2; exit 1; } -report() { printf 'publication=%s\n' "$1" >>"${GITHUB_OUTPUT}"; } -unchanged() { report unchanged; exit 0; } -for variable in GH_TOKEN GITHUB_REPOSITORY GITHUB_EVENT_NAME GITHUB_EVENT_PATH GITHUB_RUN_ID GITHUB_RUN_ATTEMPT GITHUB_OUTPUT BASE_SHA HEAD_SHA PR_NUMBER ASSESSMENT REQUIRED_GATE_NAME EXPECTED_WORKFLOW_NAME EXPECTED_WORKFLOW_FILE EXPECTED_WORKFLOW_PATH; do - [[ -n "${!variable:-}" ]] || fail_closed "Status publisher is missing ${variable}." -done -[[ "${GITHUB_EVENT_NAME}" == pull_request && "${BASE_SHA}" =~ ^[0-9a-fA-F]{40}$ && - "${HEAD_SHA}" =~ ^[0-9a-fA-F]{40}$ && "${PR_NUMBER}" =~ ^[1-9][0-9]*$ && - "${GITHUB_RUN_ID}" =~ ^[1-9][0-9]*$ && "${GITHUB_RUN_ATTEMPT}" =~ ^[1-9][0-9]*$ && - "${GITHUB_REPOSITORY}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || - fail_closed "Status publisher requires an exact pull-request identity." -case "${ASSESSMENT}" in success|dependency-deferred) ;; *) fail_closed "Invalid canonical assessment." ;; esac -case "${EXPECTED_WORKFLOW_FILE}" in - ci.yml) workflow_name='CI — Validation'; gate_name='Validation Gate' ;; - 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' ;; - *) fail_closed "Unsupported required gate workflow." ;; -esac -[[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/${EXPECTED_WORKFLOW_FILE}" && - "${EXPECTED_WORKFLOW_NAME}" == "${workflow_name}" && "${REQUIRED_GATE_NAME}" == "${gate_name}" ]] || - fail_closed "Required gate and owning workflow disagree." -api_root="/repos/${GITHUB_REPOSITORY}" -api_url="https://api.github.com/repos/${GITHUB_REPOSITORY}" -run_url="https://github.com/${GITHUB_REPOSITORY}/actions/runs/" -current_target="${run_url}${GITHUB_RUN_ID}/attempts/${GITHUB_RUN_ATTEMPT}" -current_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" -jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson pr "${PR_NUMBER}" --arg base "${BASE_SHA}" --arg head "${HEAD_SHA}" ' - .action == "edited" and .repository.full_name == $repo and .number == $pr and - .changes.base.ref == null and .pull_request.number == $pr and - .pull_request.base.repo.full_name == $repo and .pull_request.base.sha == $base and - .pull_request.head.sha == $head' "${GITHUB_EVENT_PATH}" >/dev/null || - fail_closed "Status publication requires the bound metadata-only event." -head_branch="$(jq -er '.pull_request.head.ref | select(type == "string" and length > 0)' "${GITHUB_EVENT_PATH}")" -head_repository="$(jq -er '.pull_request.head.repo.full_name | select(type == "string" and length > 0)' "${GITHUB_EVENT_PATH}")" -base_branch="$(jq -er '.pull_request.base.ref | select(type == "string" and length > 0)' "${GITHUB_EVENT_PATH}")" -workflow="$(gh api --method GET "${api_root}/actions/workflows/${EXPECTED_WORKFLOW_FILE}")" -workflow_id="$(jq -er --arg name "${workflow_name}" --arg path "${EXPECTED_WORKFLOW_PATH}" ' - select(.name == $name and .path == $path) | .id | select(type == "number" and . > 0 and . == floor)' <<<"${workflow}")" -current_pr() { gh api --method GET "${api_root}/pulls/${PR_NUMBER}"; } -pr_matches() { - jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson pr "${PR_NUMBER}" --arg head "${HEAD_SHA}" \ - --arg base "${BASE_SHA}" --arg branch "${head_branch}" --arg head_repo "${head_repository}" --arg base_ref "${base_branch}" ' - .number == $pr and .state == "open" and .base.repo.full_name == $repo and - .base.sha == $base and .base.ref == $base_ref and .head.sha == $head and - .head.ref == $branch and .head.repo.full_name == $head_repo' <<<"$1" >/dev/null -} -# Rich status records retain creator evidence missing from the combined projection. -latest_status() { - local inventory='[]' page rows prefix found - # GitHub returns newest first; stop at the first exact context, regardless - # of its actor. Exhaust history only to establish absence, never ownership. - for page in {1..10}; do - rows="$(gh api --method GET "${api_root}/statuses/${HEAD_SHA}" -f per_page=100 -f page="${page}")" || return 1 - prefix="$(jq -ce --arg context "${gate_name}" ' - if type != "array" or length > 100 then error("invalid status page") else . end - | (map(if type == "object" then .context == $context else false end) | index(true)) as $index - | {found: ($index != null), rows: (if $index == null then . else .[0:($index + 1)] end)}' <<<"${rows}")" || return 1 - found="$(jq -r .found <<<"${prefix}")" - inventory="$(jq -cs '.[0] + .[1].rows' <(printf '%s\n' "${inventory}") <(printf '%s\n' "${prefix}"))" || return 1 - jq -e --arg url "https://api.github.com/repos/${GITHUB_REPOSITORY}/statuses/${HEAD_SHA}" ' - all(.[]; type == "object" and (.context | type) == "string" and (.context | length) > 0 and - (.id | type) == "number" and .id > 0 and (.id | floor) == .id and .url == $url) and - ([.[].id] | unique | length) == length' <<<"${inventory}" >/dev/null || return 1 - if [[ "${found}" == true ]]; then jq -c '.[-1]' <<<"${inventory}"; return 0; fi - if [[ "$(jq length <<<"${rows}")" -lt 100 ]]; then printf 'null\n'; return 0; fi - done - return 1 # Budget exhaustion cannot establish absence. -} -# This proves ownership, not original source success. Old base SHA and failed or -# cancelled publisher steps identify provenance only and cannot grant proof. -native_identity() { - local run_id="$1" attempt="$2" current="$3" require_current_base="${4:-false}" run title title_base jobs check check_id - if [[ "${current}" == true ]]; then - run="$(gh api --method GET "${api_root}/actions/runs/${run_id}")" || return 1 - else - run="$(gh api --method GET "${api_root}/actions/runs/${run_id}/attempts/${attempt}")" || return 1 - 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})$") - | 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}" \ - --arg repo "${GITHUB_REPOSITORY}" --arg head_repo "${head_repository}" --arg branch "${head_branch}" \ - --arg head "${HEAD_SHA}" --arg title "${title}" --arg name "${workflow_name}" --arg path "${EXPECTED_WORKFLOW_PATH}" \ - --argjson pr "${PR_NUMBER}" --argjson current "${current}" --argjson current_number "${current_run_number}" \ - --argjson current_run "${GITHUB_RUN_ID}" --argjson current_attempt "${GITHUB_RUN_ATTEMPT}" ' - .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and .event == "pull_request" and - (.run_number | type == "number" and . > 0 and . == floor) and - (if $current then .run_number == $current_number else - .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 - (.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 - (if $current then .status == "in_progress" and .conclusion == null else - (.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "in_progress" or .status == "queued" or .status == "pending" or .status == "waiting" or .status == "requested") and .conclusion == null) end)' <<<"${run}" >/dev/null || return 1 - jobs="$(gh api --method GET "${api_root}/actions/runs/${run_id}/attempts/${attempt}/jobs" -f per_page=100)" || return 1 - jobs="$(jq -ce --arg name "${gate_name}" --arg head "${HEAD_SHA}" --argjson run "${run_id}" --argjson current "${current}" ' - if type != "object" or (.jobs | type) != "array" or (.total_count | type) != "number" or - .total_count < 0 or .total_count > 100 or (.total_count | floor) != .total_count or - (.jobs | length) != .total_count or any(.jobs[]; type != "object" or (.id | type) != "number" or .id <= 0 or (.id | floor) != .id) or - ([.jobs[].id] | unique | length) != .total_count then error("incomplete jobs") else . end - | [.jobs[] | select(.name == $name)] | if length == 1 then .[0] else error("ambiguous native gate") end - | select(.run_id == $run and .head_sha == $head) - | select((.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "in_progress" or .status == "queued" or .status == "pending" or .status == "waiting" or .status == "requested") and .conclusion == null)) - | select([.steps[]? | select(.name == "Publish pending required gate status" and - ((.status == "in_progress" and .conclusion == null) or - (.status == "completed" and (.conclusion == "success" or .conclusion == "failure" or - .conclusion == "cancelled" or .conclusion == "timed_out" or .conclusion == "action_required"))))] | length == 1) - | select(if $current then .status == "in_progress" and .conclusion == null and - ([.steps[]? | select(.name == "Preserve successful required gate on metadata-only edit" and - .status == "completed" and .conclusion == "success")] | length == 1) else true end)' <<<"${jobs}")" || return 1 - check_id="$(jq -er '.check_run_url | capture("/check-runs/(?[1-9][0-9]*)$").id' <<<"${jobs}")" || return 1 - check="$(gh api --method GET "${api_root}/check-runs/${check_id}")" || return 1 - jq -e --argjson id "${check_id}" --arg name "${gate_name}" --arg head "${HEAD_SHA}" --argjson job "${jobs}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and .name == $name and - .head_sha == $head and .status == $job.status and .conclusion == $job.conclusion' <<<"${check}" >/dev/null -} -owned_status() { - local status="$1" require_current_base="${2:-false}" suffix run_id attempt - jq -e --arg url "${api_url}/statuses/${HEAD_SHA}" ' - .creator.id == 41898282 and .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - .url == $url and (.state == "pending" or .state == "success" or .state == "failure" or .state == "error")' <<<"${status}" >/dev/null || return 1 - suffix="$(jq -er '.target_url' <<<"${status}")" || return 1 - [[ "${suffix}" == "${run_url}"* ]] || return 1 - suffix="${suffix#"${run_url}"}" - [[ "${suffix}" =~ ^([1-9][0-9]*)/attempts/([1-9][0-9]*)$ ]] || return 1 - run_id="${BASH_REMATCH[1]}"; attempt="${BASH_REMATCH[2]}" - native_identity "${run_id}" "${attempt}" false "${require_current_base}" -} -acknowledge_existing_pending() { - local status="$1" fresh - [[ "$(jq -r '.state' <<<"${status}")" == pending ]] || return 1 - owned_status "${status}" true || return 1 - native_identity "${GITHUB_RUN_ID}" "${GITHUB_RUN_ATTEMPT}" true || - fail_closed "Current metadata native gate is not attributable." - pr="$(current_pr)" - pr_matches "${pr}" || unchanged - fresh="$(latest_status)" || fail_closed "Latest context became unavailable." - [[ "${fresh}" == "${status}" ]] || unchanged - report pending-acknowledged - exit 0 -} -pr="$(current_pr)" -pr_matches "${pr}" || unchanged -# Validate the running metadata workflow even on a no-write success path. -run="$(gh api --method GET "${api_root}/actions/runs/${GITHUB_RUN_ID}")" -jq -e --arg title "${current_title}" --argjson id "${GITHUB_RUN_ID}" --argjson attempt "${GITHUB_RUN_ATTEMPT}" \ - --argjson workflow "${workflow_id}" --arg repo "${GITHUB_REPOSITORY}" --arg head "${HEAD_SHA}" \ - --arg head_repo "${head_repository}" --arg branch "${head_branch}" --arg name "${workflow_name}" \ - --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 - .head_repository.full_name == $head_repo and .head_branch == $branch and - (.name == $name or .name == $title) 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 - .status == "in_progress" and .conclusion == null' <<<"${run}" >/dev/null || fail_closed "Current metadata run is not attributable." -current_run_number="$(jq -er '.run_number' <<<"${run}")" -latest="$(latest_status)" || fail_closed "Latest context is incomplete or ambiguous." -owned=false -if [[ "${latest}" != null ]]; then - if [[ "${ASSESSMENT}" == dependency-deferred ]] && acknowledge_existing_pending "${latest}"; then :; fi - if owned_status "${latest}"; then owned=true; fi -fi -if [[ "${ASSESSMENT}" == success ]]; then - if [[ "${owned}" != true || "$(jq -r '.state' <<<"${latest}")" == success ]]; then unchanged; fi - assessment_output="$(mktemp)" - trap 'rm -f "$assessment_output"' EXIT - if ! GITHUB_OUTPUT="${assessment_output}" bash "$(dirname "${BASH_SOURCE[0]}")/../preserve-required-gate/assess-required-gate.sh"; then - fail_closed "Refreshed canonical assessment failed; no status is published." - fi - ASSESSMENT="$(sed -n 's/^assessment=//p' "${assessment_output}")" - case "${ASSESSMENT}" in success|dependency-deferred) ;; *) fail_closed "Malformed refreshed assessment." ;; esac -fi -if [[ "${latest}" != null && "${owned}" != true ]]; then unchanged; fi -state=pending -[[ "${ASSESSMENT}" != success ]] || state=success -native_identity "${GITHUB_RUN_ID}" "${GITHUB_RUN_ATTEMPT}" true || fail_closed "Current metadata native gate is not attributable." -pr="$(current_pr)" -pr_matches "${pr}" || unchanged -fresh="$(latest_status)" || fail_closed "Latest context became unavailable." -if [[ "${fresh}" != "${latest}" ]]; then - if [[ "${ASSESSMENT}" == dependency-deferred ]] && acknowledge_existing_pending "${fresh}"; then :; fi - unchanged -fi -# One POST, no retry. Its native REST shape has creator and URL, not sha/app_id. -ack="$(gh api --method POST "${api_root}/statuses/${HEAD_SHA}" -f state="${state}" -f context="${gate_name}" \ - -f target_url="${current_target}" -f description="Metadata gate original proof: ${state}")" || - fail_closed "Status POST was denied or ambiguous; do not replay." -jq -se --arg url "${api_url}/statuses/${HEAD_SHA}" --arg context "${gate_name}" --arg state "${state}" --arg target "${current_target}" ' - if length != 1 then error("ambiguous acknowledgment") else .[0] end - | type == "object" and (.id | type == "number" and . > 0 and . == floor) and .url == $url and - .context == $context and .state == $state and .target_url == $target and - .creator.id == 41898282 and .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - (try (.created_at | fromdateiso8601 | type == "number") catch false) and - (try (.updated_at | fromdateiso8601 | type == "number") catch false)' <<<"${ack}" >/dev/null || - fail_closed "Status POST acknowledgment is malformed or misattributed." -report "${state}-acknowledged" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71a1bc8dda..235ff38efd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1378,15 +1378,10 @@ jobs: # Final gating and PR reporting validation-gate: - name: Validation Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate' }} runs-on: ubuntu-latest timeout-minutes: 95 - 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 the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} env: ACCOUNT_MODULE_AFFECTED: ${{ contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'account-service') }} ACCOUNT_COVERAGE_AGGREGATE: ${{ needs.account-coverage-aggregate.result }} @@ -1395,7 +1390,8 @@ jobs: GAME_SESSION_COVERAGE_AGGREGATE: ${{ needs.game-session-coverage-aggregate.result }} WORLD_COVERAGE_AGGREGATE: ${{ needs.world-coverage-aggregate.result }} needs: [changes, postgres-runtime-upgrade-proof, buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tool-validation-contracts, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, build-and-test-account, build-and-test-game-session, build-and-test-world, account-coverage-aggregate, game-session-coverage-aggregate, world-coverage-aggregate] - if: ${{ always() }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 @@ -1405,62 +1401,7 @@ jobs: - name: Declare dev tool contract split run: ':' - - name: Check out required-gate action - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Explain validation lane - env: - FIREMUD_METADATA_ONLY: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - run: | - if [[ "$FIREMUD_METADATA_ONLY" == "true" ]]; then - printf '## Metadata-only PR edit\n\nHeavy validation jobs are skipped. Required CI is preserved only from qualified source validation for this comparison.\n' >> "$GITHUB_STEP_SUMMARY" - else - printf '## Source validation\n\nThis run executes the applicable source checks for the PR comparison.\n' >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: Validation Gate - workflow-name: CI — Validation - workflow-file: ci.yml - workflow-path: .github/workflows/ci.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: Validation Gate - workflow-name: CI — Validation - workflow-file: ci.yml - workflow-path: .github/workflows/ci.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: Enforce validation success - if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} env: DOCS_CHANGED: ${{ needs.changes.outputs.docs_changed }} FRONTEND_CHANGED: ${{ needs.changes.outputs.frontend_changed }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 34fe4ec60f..6a7bf93c13 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -207,69 +207,20 @@ jobs: uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 codeql-gate: - name: CodeQL Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate' }} runs-on: ubuntu-latest timeout-minutes: 95 - 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 the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} needs: [changes, analyze] - if: ${{ always() && github.event_name == 'pull_request' }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit - - name: Check out required-gate action - if: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: CodeQL Gate - workflow-name: CodeQL Analysis - workflow-file: codeql.yml - workflow-path: .github/workflows/codeql.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: CodeQL Gate - workflow-name: CodeQL Analysis - workflow-file: codeql.yml - workflow-path: .github/workflows/codeql.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: Enforce successful CodeQL analysis - if: ${{ github.event.action != 'edited' || github.event.changes.base.ref != null }} env: CHANGES_RESULT: ${{ needs.changes.result }} SHOULD_RUN: ${{ needs.changes.outputs.should_run }} diff --git a/.github/workflows/license-scan.yml b/.github/workflows/license-scan.yml index 069aadc6ac..e7d2445ef8 100644 --- a/.github/workflows/license-scan.yml +++ b/.github/workflows/license-scan.yml @@ -404,69 +404,20 @@ jobs: fi license-gate: - name: License Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (License Gate)' || 'License Gate' }} needs: [changes, ort-gradle, ort-npm] - if: ${{ always() }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) }} runs-on: ubuntu-latest timeout-minutes: 95 - 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 the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit - - name: Check out required-gate action - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: License Gate - workflow-name: License Gate - workflow-file: license-scan.yml - workflow-path: .github/workflows/license-scan.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: License Gate - workflow-name: License Gate - workflow-file: license-scan.yml - workflow-path: .github/workflows/license-scan.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: Verify ORT results - if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} env: EVENT_NAME: ${{ github.event_name }} CHANGES_RESULT: ${{ needs.changes.result }} diff --git a/.github/workflows/resolve-required-gates.yml b/.github/workflows/resolve-required-gates.yml deleted file mode 100644 index 5b8cc5afad..0000000000 --- a/.github/workflows/resolve-required-gates.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: Resolve Required Gates - -on: - workflow_run: - workflows: ['CI — Validation', Security Gate, CodeQL Analysis, License Gate, PR Smoke Gate] - 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 }} - -permissions: - contents: read - -concurrency: - group: required-gate-resolution-${{ github.event.workflow_run.workflow_id }}-${{ github.event.workflow_run.head_sha }} - cancel-in-progress: false - -jobs: - resolve: - name: Resolve deferred metadata gate - # Admit only attributable pull-request sources through the shared resolver. - if: ${{ github.event.workflow_run.event == 'pull_request' }} - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: read - checks: read - pull-requests: read - statuses: write # Settle only an attributable supplementary status barrier. - actions: write # Only rerun an attributable completed deferred gate job. - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - - name: Check out trusted resolver - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.sha }} - persist-credentials: false - - - name: Set up canonical GitHub CLI - uses: ./.github/actions/setup-gh - - - name: Preflight deferred gate resolution - id: preflight - env: - GH_TOKEN: ${{ github.token }} - run: bash .github/actions/preserve-required-gate/resolve-deferred-gate.sh preflight - - - name: Admit deferred gate reruns - id: admission - if: ${{ steps.preflight.outputs.eligible == 'true' }} - env: - GH_TOKEN: ${{ github.token }} - run: bash .github/actions/preserve-required-gate/resolve-deferred-gate.sh admit - - - name: Confirm admitted deferred gate jobs ${{ steps.admission.outputs.accepted_job_ids }} - if: ${{ steps.admission.outcome == 'success' }} - # Native first-attempt step identity preserves acknowledged IDs even - # while the target run still exposes a stale attempt-one snapshot. - run: ':' - - - name: Reconcile supplementary required gate status - if: ${{ always() }} - env: - GH_TOKEN: ${{ github.token }} - run: bash .github/actions/preserve-required-gate/resolve-deferred-gate.sh reconcile diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index d3d85fa62b..84e92ae7b2 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -840,10 +840,9 @@ jobs: "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} ); + // Metadata-only edits skip their gate under a non-required name. const gates = jobs.filter((job) => job.name === "Validation Gate"); const gate = gates.length === 1 ? gates[0] : null; - const preservation = gate?.steps?.filter((step) => - step.name === "Preserve successful required gate on metadata-only edit") || []; const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || @@ -851,8 +850,7 @@ jobs: ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || - preservation.length !== 1 || preservation[0].status !== "completed" || - preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || + enforcement.length !== 1 || enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); return; diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index b4d74bf5b8..ffd5224113 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -135,69 +135,20 @@ jobs: warning_window_days: 14 security-gate: - name: Security Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Security Gate)' || 'Security Gate' }} runs-on: ubuntu-latest timeout-minutes: 95 - 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 the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} needs: [changes, trivy-scan, secret-compliance] - if: ${{ always() }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit - - name: Check out required-gate action - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: Security Gate - workflow-name: Security Gate - workflow-file: security.yml - workflow-path: .github/workflows/security.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: Security Gate - workflow-name: Security Gate - workflow-file: security.yml - workflow-path: .github/workflows/security.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - 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: Enforce security success - if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} env: CHANGES_RESULT: ${{ needs.changes.result }} LIGHTWEIGHT_ONLY: ${{ needs.changes.outputs.lightweight_only }} diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e17d781603..1a8a1808a4 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -457,16 +457,15 @@ jobs: smoke-gate: outputs: known_play_exception: ${{ steps.track-runtime-smoke.outputs.known_play_exception }} - name: Smoke Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || '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. + contents: read # Read the immutable runtime workflow definition and current base ref. 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' }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} timeout-minutes: 95 steps: - name: Harden runner @@ -477,62 +476,16 @@ jobs: - 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 + if [ "$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' }} + if: ${{ steps.smoke_gate_context.outputs.execute != 'true' }} env: CHANGES_RESULT: ${{ needs.changes.result }} run: | @@ -608,9 +561,9 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; + const canonicalRuntimeWorkflowSha256 = "8f86c8f566e5821f5c35e883d1e02474357c7a42459c520e82d3de4a8a4e8e68"; // Trusted refreshes can still execute the previous successful default-branch definition. - const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; + const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; // 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. diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index b35044a9c2..23dbb56c22 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -126,8 +126,21 @@ jobs: ); }; - const workflowRunFor = async (workflowId) => { + const checkRunWorkflowId = (checkRun) => { + const match = String(checkRun?.details_url || "").match(/\/actions\/runs\/(\d+)(?:\/|$)/); + return match?.[1] || null; + }; + + // Metadata-only edits skip their gate under a non-required name; the + // earlier substantive run for the same title remains the result. + // GitHub leaves a skipped job's name expression unevaluated, so match + // the metadata label inside it. + const workflowRunFor = async (workflowId, gateName, checkRuns) => { const workflowName = workflowId === "codeql.yml" ? "CodeQL Analysis" : "License Gate"; + const metadataRunIds = new Set((Array.isArray(checkRuns) ? checkRuns : []) + .filter((checkRun) => String(checkRun?.name || "").includes(`'PR Metadata Edit (${gateName})'`)) + .map(checkRunWorkflowId) + .filter(Boolean)); const expectedTitle = `${workflowName} pr-${issueNumber} base-${baseSha} head-${headSha}`; const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, { ...context.repo, @@ -137,15 +150,11 @@ jobs: per_page: 100, }); return selectLatestWorkflowRun( - workflowRuns.filter((workflowRun) => workflowRun?.display_title === expectedTitle) + workflowRuns.filter((workflowRun) => + workflowRun?.display_title === expectedTitle && !metadataRunIds.has(String(workflowRun.id))) ); }; - 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), @@ -218,13 +227,14 @@ jobs: return [label, normalizeStatus(selectedCheckRun, checkName, workflowRun)]; }); + const checkRuns = await loadChecks(); const workflowRuns = { - codeql: await workflowRunFor("codeql.yml"), - license: await workflowRunFor("license-scan.yml"), + codeql: await workflowRunFor("codeql.yml", "CodeQL Gate", checkRuns), + license: await workflowRunFor("license-scan.yml", "License Gate", checkRuns), }; // 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 checks = resolveStatuses(checkRuns, workflowRuns); const gateResults = checks.slice(0, gateChecks.length); const detailResults = checks.slice(gateChecks.length); diff --git a/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index 468df29c82..45562f14a2 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -128,7 +128,7 @@ jobs: }; const detector = one("Detect CI-Relevant Changes"); if (detector === "skipped") { - core.info("Skipping metadata-only preservation source"); + core.info("Skipping metadata-only edit source"); return; } const fixedChecks = [ diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 6bf3ae1299..07f170384e 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -22,7 +22,7 @@ This document describes the continuous integration strategy for FireMUD using ** - **Create release PRs automatically** using the `release-please` workflow. - **Propose dependency updates automatically** with Renovate against the `develop` branch across the supported dependency managers. - **Generate database ERD diagrams** as build artifacts after each run. The [`dev-tools/docs/generate-erd.sh`](../../dev-tools/docs/generate-erd.sh) script writes them to `design/erd/`, and the workflow uploads this directory as artifacts. -- **Cancel superseded substantive runs for the same branch** using a concurrency group so CI resources are conserved and deployment jobs do not race for the same environment. Metadata-only title/body edits remain isolated from substantive validation. Required check identities remain stable; metadata edits cannot manufacture proof from a skipped, failed, pending, stale, or ambiguous substantive gate. +- **Cancel superseded substantive runs for the same branch** using a concurrency group so CI resources are conserved and deployment jobs do not race for the same environment. Metadata-only title/body edits skip every job and never replace a required check; see [Required Gates on Metadata Edits](#required-gates-on-metadata-edits). ## Implementation Status @@ -32,35 +32,15 @@ The manual [Game Session factory inventory qualification workflow](../../.github --- -## Required Gate Preservation +## Required Gates on Metadata Edits -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 keep their exact branch-protection names for every substantive pull-request event: open, new commits, reopen, and a base-branch change. Their workflows still listen to `edited`, because GitHub reports a retarget as an `edited` event and cannot filter it by field before starting a run. -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. +A metadata-only edit is an `edited` event whose `changes.base` is absent, such as a title or description change. On that event every job in the five workflows is skipped, and each gate job is skipped under a non-required name. The name expression selects `PR Metadata Edit ()`; GitHub does not evaluate a skipped job's name, so the check run shows the whole expression text instead, which is still not a required name. The edit therefore produces no check run under a required name, so the latest required check run for the head stays the earlier substantive result. A failing or pending gate stays failing or pending, and an edit cannot turn a pull request green. A skipped job under a required name would count as passing, which is why the gate must never skip under its required name. -All five metadata gate producers call the shared publisher after canonical preservation assessment, loading both helpers from the trusted PR base SHA. Their gate jobs hold `statuses: write` and `pull-requests: read` alongside the existing read permissions; no other producer job gains status-write authority. The producer must publish a same-name pending Commit Status on the exact PR head with the exact target URL `https://github.com///actions/runs//attempts/` from GitHub Actions bot user ID `41898282`, login `github-actions[bot]`, type `Bot`, in a dedicated native step named `Publish pending required gate status` (producer step ID `publish-pending-status`). The resolver independently validates the historical metadata ownership and the current original proof. Historical metadata must bind the exact declared PR/head/workflow/run/attempt and a canonical title with its historical base, complete native jobs, dedicated publisher phase, and native Actions app `15368`; empty REST PR associations remain eligible only through canonical title attribution. Historical metadata may still be running, failed or cancelled: it supplies ownership only, never current-base success. For the current open PR/base/head tuple, the unchanged canonical assessor selects original proof while excluding the historical metadata run, not the substantive completion callback's own source. With `REQUIRED_GATE_INCLUDE_SOURCE=true`, opt-in `source_run_id`, `source_job_id`, `source_check_run_id`, and `source_run_attempt` outputs expose that already-selected successful source without changing ordinary output or selection. The resolver independently reads that exact native run/attempt, substantive gate job and app-pinned successful CheckRun before it can publish success. Failed, unavailable or ambiguous current proof cannot become success; pending current proof leaves the barrier blocking. The selector's existing treatment of cancelled/skipped/stale substantive candidates remains unchanged. +Metadata runs use their own concurrency namespace, so an edit cannot cancel or replace an in-progress substantive run. Completion callbacks that read gate results, such as the [runtime-image refresh](#pull-request-runtime-and-preview-chain), the detached Validation Summary and the Static Analysis Summary, ignore metadata runs: they require the required-name gate job, or exclude runs whose gate check name contains the metadata label. -The existing substantive and metadata completion callbacks reconcile both completion orders, including a pending status published after original proof has already completed. The existing trusted resolve job holds `statuses: write` for supplementary reconciliation; producer gate jobs hold it only for the shared metadata publisher. The assessor retains its unchanged selection contract. A fresh attributable current-tuple completion may reconcile a recognized owned pending, failure or error barrier using independently selected current substantive proof. This explicitly supersedes the pending-only terminal-write restriction for source recovery: a same-head retarget/base advancement or legitimate source retry must recover without a new metadata edit. Already successful and foreign barriers remain untouched. Historical base-A success cannot authorize current base-B success, and obsolete base-A callbacks remain no-ops. The resolver re-reads current PR identity, both historical ownership and selected current native proof, and the unchanged latest status immediately before posting. Its replacement fence is the selected latest status identity; it does not require an original run number to exceed a later metadata run, since original completion after metadata publication is ordinary. Replaced, stale or unbound statuses are never overwritten. GitHub provides no conditional Commit Status write: the final read and POST are not atomic, and this boundary is practical race suppression rather than an atomic replacement guarantee. A rejected or ambiguous POST is never retried within that callback; subsequent callbacks assess fresh evidence. No polling, global expiry, new credentials, or independent proof ledger is introduced. - -The [publisher action](../../.github/actions/publish-required-gate-status/action.yml) runs in the dedicated metadata-only step after both successful and dependency-deferred assessments, so a successful assessment can also recover an existing owned barrier. It accepts `assessment`, `gate-name`, `workflow-name`, `workflow-file`, and `workflow-path`, and outputs `pending-acknowledged`, `success-acknowledged`, or `unchanged`. A dependency-deferred assessment publishes the current run's pending barrier only when the latest same-context status is absent or independently recognized as owned. If an owned pending barrier already binds the exact current PR, base, head, workflow, run, and attempt, including one that becomes latest during the publisher's replacement fence, the publisher reports `pending-acknowledged` without duplicating the status only after validating the current metadata native gate and re-reading both the unchanged current PR tuple and unchanged latest status identity; a stale-base, moved, foreign, malformed, missing, failed, or successful status cannot use that durable acknowledgment path. A success assessment leaves absent, foreign, and already successful barriers unchanged. An owned pending/failure/error barrier requires a refreshed canonical assessment for the current base before publishing success; refreshed pending follows the pending policy, and failed or ambiguous assessment prevents publication. A dependency-deferred assessment permits the native metadata gate to succeed only with `pending-acknowledged`; `unchanged`, missing, unknown, or contradictory publication outputs fail distinctly as dependency deferral. A successful assessment permits `unchanged`, `success-acknowledged`, or `pending-acknowledged`: the last means refreshed proof became pending and the acknowledged status continues withholding readiness. A successful assessment with an absent or already successful barrier needs no write; a foreign barrier remains untouched and independently blocking when non-successful. Missing or unknown assessment/publication outputs fail closed. The metadata-result guard uses `!cancelled()` with the unchanged metadata predicate so it still executes after publisher failure, and requires the publisher outcome itself to be `success` before accepting any assessment/publication pair. Publisher failure, denial, malformed acknowledgment, cancellation, or missing/skipped execution never grants native gate success. The publisher retains normal success-dependent execution without `continue-on-error`; no caller ignores its errors or changes substantive enforcement. - -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. - -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. - -Resolution is serialized by owning workflow identity and head SHA. Only a completed first-attempt metadata run whose gate exposes the distinct deferred failure and whose valid native creation timestamp is no later than the current resolver's creation timestamp is eligible. The same chronology check applies immediately before POST. A queued callback cannot admit a later-created target; that target's own later callback can resolve it. This keeps each admitting resolver within the history window bounded by its retained target even after an older source expires. The resolver re-reads current PR identity and target run/job immediately before one non-retried targeted-job POST. An observed second attempt, including a human rerun, consumes the automatic allowance. After acknowledged POSTs, a successful admission publishes only its actual job IDs in a validated set capped at 20; one subsequent native confirmation step preserves that set in its evaluated name. A complete successful confirmation suppresses later POSTs for those exact jobs even while the target API still reports attempt 1, without blocking a distinct eligible job. A successful zero-POST admission confirms an empty set. Partial or ambiguous admission publishes no set, and a missing, failed, cancelled, incomplete, duplicate, or malformed confirmation requires explicit recovery. No marker is emitted for a job before its POST is acknowledged. These checks suppress duplicates practically; they do not assert an atomic API guarantee. An ambiguous or rejected POST fails closed and requires explicit recovery rather than automatic replay. Success remains the rerun gate's own proof decision. - -The trusted resolver separates preflight from a named admission step. Its native run title binds the original workflow ID and head SHA. Current resolver identity must be attributable and on attempt 1; any matching historical resolver attempt greater than 1 also blocks automation because its latest job snapshot could hide an earlier ambiguous admission. Rerunning the resolver alone cannot establish safe recovery. One complete owning-workflow query filtered by `pull_request` and exact head SHA supplies bounded source evidence. Before reading admission history, the resolver validates and freezes eligible native target run/job identities and their creation timestamps. An empty candidate set returns an empty admission without reading history. The history floor is the earliest frozen eligible target creation timestamp, inclusive of ties. Every admissible resolver was created no earlier than its target, so this window retains possible admissions for every frozen candidate even after an older substantive source expires. A target that becomes eligible later cannot enter this invocation's frozen set; the immediate fresh run/job read must match the frozen job ID and creation timestamp. The complete resolver query uses `created >=` that floor and excludes the validated current resolver only when assessing prior admissions. Source discovery remains one complete page capped at 20 records. Resolver history uses explicit 100-record pages, at most ten pages and 1,000 total records, matching the documented [Actions REST search ceiling](https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow). Every page must report the same positive integer total and its expected record count; the combined history must contain unique IDs and the current resolver. Excess, unavailable, malformed, inconsistent, or incomplete coverage fails closed before admission. The query retains all statuses and uses no assumed source-SHA association for the default-branch listener. Unrelated resolver events still count toward the 1,000-record ceiling, so this bounded budget does not establish fleet-wide scalability; an oversized window or source set requires explicit recovery. A matching first-attempt callback still pending or queued with no conclusion and a strictly later native creation timestamp cannot yet have admitted a POST under the shared workflow/head concurrency group; it does not block the current callback even when the trusted listener revision has advanced. The [native concurrency contract](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency) describes waiting workflows as pending; only later first-attempt callbacks under the exact held group receive this exception. Earlier pending callbacks and uncertain histories remain conservative. Equal timestamps require a complete first-attempt job snapshot with exact run/job identity, queued state, explicit null start/end timestamps, and wholly queued/non-concluded steps; empty steps are acceptable only with that unequivocal never-started job state. Missing, malformed, incomplete, or started evidence remains closed. Native queued-job snapshot availability remains unproved; unavailable evidence holds automation. Each matching resolver job lookup retains complete one-page coverage capped at 20 jobs. An attributable completed/cancelled first-attempt callback with explicit, complete zero-job evidence proves a pending callback was evicted before admission; nonempty, missing, malformed, incomplete, or unknown evidence cannot use that exception. Existing native skipped-admission proof remains a separate clean no-op. A skipped admission is a clean no-op; a failed, cancelled, timed-out, missing, or incomplete admission may have sent a POST and blocks later automation even if the target still reports attempt 1. Unavailable or truncated evidence also blocks admission. This uses retained Actions evidence, not a new receipt. The fresh native rehearsal must establish deployed target-window admission, actual target job/attempt transitions, evaluated confirmation-name persistence, and settled no-op callbacks within the existing budget. Native equal-time queued, zero-job eviction, fork/empty-association, delayed-attempt, and retention-loss cases remain unproved; uncertain evidence holds automation rather than requiring unsafe construction of those cases. The bounded history allowance remains an API ceiling, not proof of fleet-wide scalability or a snapshot-consistency guarantee. - -Native admission evidence is bounded by GitHub retention. Known missing, ambiguous, or deleted admission evidence holds automatic replay; a resolver rerun alone does not prove recovery. Establish the actual target attempt/job outcome and a separate safe boundary before resuming automation for that tuple. - -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. +The [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) checks the gate names, job conditions and concurrency namespaces for all five workflows. 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. @@ -77,12 +57,12 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s | 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. | +| [`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 skip it under a non-required name and do not dispatch or cancel runtime construction; see [Required Gates on Metadata Edits](#required-gates-on-metadata-edits). | | [`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 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 its executed substantive Validation Gate enforcement 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. 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. diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index db27579ff9..fd55e76c29 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -56,7 +56,7 @@ FireMUD owns the project authority and safety requirements below. Follow the act - Open or update a PR autonomously when an implementation branch reaches a coherent review checkpoint, subject to the topology and approval rules in [Change And Merge Policy](#change-and-merge-policy). Stacked PRs are acceptable when their base dependencies are explicit and they let independent work continue while CI or review runs. If the next authorized work is unambiguous and can be cleanly based on a merge-ready PR, continue autonomously in a stacked PR subject to those rules; a draft PR may expose in-progress work and should be marked ready at a coherent review checkpoint. After the parent merges, retarget the child to `develop` subject to those rules before rebasing or pushing. An explicit pause, unresolved human decision, or dependency requiring merged state stops continuation; do not create tiny placeholder PRs without review-worthy content. - When active work moves to another worktree, report its absolute path and branch so the human's IDE context and delegated-worker paths remain aligned. - CI — Validation runs for pull requests targeting any base branch, including stacked feature branches, with the same change classification, jobs, required Validation Gate, and summary as other PRs. Security, License, and CodeQL gates also cover every PR base, and relevant web-client changes receive ZAP validation. Push scopes remain unchanged: Validation, Security, License, and ZAP use `main` and `develop`, while CodeQL uses `main`. A stacked candidate must contain the applicable workflow changes before relying on their coverage. Smoke and the credential-free runtime-image producer also cover feature bases with their existing runtime path classification; irrelevant changes receive an explicit no-op. Validation success alone does not establish smoke proof. Exact tuple selection, parent-advance refresh, and the separate preview/publication restrictions are owned by the [CI/CD runtime and preview chain](../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain). -- When retargeting a stacked PR after its parent merges, change the base before rebasing or pushing the child. Required workflows run replacement validation for base-ref edits and isolate title/body edits from substantive runs. Required gate names and exact original-proof attribution are owned by [CI/CD: Required Gate Preservation](../architecture/system-architecture-cicd.md#required-gate-preservation). Deferred metadata gates publish a pending required status, and trusted completion callbacks clear that barrier only after checking current original proof. A dependency-deferred failure is missing proof, not merge readiness. Ambiguous automatic-rerun outcomes require explicit recovery. +- When retargeting a stacked PR after its parent merges, change the base before rebasing or pushing the child. Required workflows run replacement validation for base-ref edits. Title/body edits skip the required gates under non-required names, so the earlier result stands; see [CI/CD: Required Gates on Metadata Edits](../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits). - For recurring branch, worktree, and PR inventory, use `dev-tools/validation/report-worktree-pr-topology.sh` rather than ad hoc status commands. Renovate PRs are omitted from the selected inventory by default; the report records them in `omitted_renovate`, and `--include-renovate` opts them back in. Pass `--pr ` for a bounded direct base/dependent stack and `--json` for machine-readable evidence; selected reports correlate only exact branch/SHA identities and fail closed on ambiguous matches, while reporting local worktree dirtiness and unpublished or stale local heads. - After a merge, remove its defunct local worktree and merged local/remote branch only after confirming no open PR or active stacked branch depends on it. Preserve unmerged branches and worktrees. - Pass PR-body Markdown through a file or stdin with real newlines rather than literal `\\n` strings. 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 3ca382658e..6fc9587fad 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -136,17 +136,13 @@ Smoke and hosted preview seeders reassert canonical state by stable business ide World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeedProperties` and consumes explicit `{tenantId, gameInstanceId}` targets. It no longer imports `GameplayCatalogProperties` in main-code smoke seeding, declares canonical demo and sandbox targets explicitly, and honors the shared `FIREMUD_BOOTSTRAP_*` overrides. The fresh-bootstrap script invokes helper scripts explicitly so file-mode drift cannot break the repo-owned proof path. The seed boundary does not attempt to become a general fixture framework or seed authored content beyond the smoke/demo contract. -### Required CI Gate Preservation +### Required CI Gates on Metadata Edits -The [activation candidate #3235](https://github.com/benhook1013/FireMUD/pull/3235) exposed a support ownership defect: native pending publication was acknowledged, but combined-status GET records omitted `creator`, preventing legitimate barrier recovery. Security original run `38678278927` succeeded and callback `38678584212` executed reconciliation while owned status `56392930570` remained pending. The source repair uses rich status-history records and adds actual API-shape, bounded pagination, same-second latest-context selection, and foreign-actor fixtures. This records a prepared correction, not live recovery proof; repair merge and a fresh attributable callback using the repaired trusted source remain required before activation can qualify. - -Pending-status producer activation is prepared in source for all five required gates, using the shared trusted-base publisher and explicit assessment/publication outcome guards. The support boundary includes trusted resolver reconciliation, independent native CheckRun/status conjunction in the controller, current-base source recovery, and opt-in selected-source provenance without changing canonical assessor selection. Support is merged and the controller promoted; further activation remains dependent on the merged ownership repair and fresh native pending-to-success qualification on the activation candidate. Source contract coverage exercises caller wiring, publisher outcomes and the accepted result matrix, plus legacy recovery after denied/ambiguous publication and rejection of cancelled/unassessed metadata alongside existing publisher/resolver fixtures; native pending POST acknowledgment is observed, but it does not establish completed activation, repaired pending-to-success recovery, read-only fork-token behavior, cancellation, retarget/base-advancement recovery, or terminal-failure retry recovery. These remain native proof checkpoints until attributable evidence is retained. [CI/CD: Required Gate Preservation](../../architecture/system-architecture-cicd.md#required-gate-preservation) owns the producer identity and resolution contract. - -`PO-3.1` implements canonical one-pass metadata-gate assessment and generic native deferred resolution, including the frozen eligible-target history boundary merged in [PR #3079](https://github.com/benhook1013/FireMUD/pull/3079). The coherent activation source removes isolated proof opt-ins and ordinary polling; default-branch deployment of this change remains pending. [CI/CD: Required Gate Preservation](../../architecture/system-architecture-cicd.md#required-gate-preservation) owns the contract and bounded native evidence. This does not establish broader CI/CD or delivery completion. +A title or description edit skips every job in the five required-gate workflows, and each gate is skipped under a non-required `PR Metadata Edit ()` name, so the earlier substantive result stands and an edit cannot turn a failing PR green. Base retargets still run the full gates. This replaced the earlier metadata preservation machinery (shared preservation and status-publisher actions, the Resolve Required Gates callback and their supplementary pending statuses), which is removed. Disposable proof PRs #3056 and #3081 belonged to that retired design; neither may be merged. Native proof on disposable [PR #3467](https://github.com/benhook1013/FireMUD/pull/3467) (closed): a body edit created only skipped metadata-named gate checks and left the five required checks unchanged, and a retarget reran all five under their required names. GitHub shows a skipped job's unevaluated name expression rather than the evaluated `PR Metadata Edit (...)` label; it is still not a required name. [CI/CD: Required Gates on Metadata Edits](../../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits) owns the contract. The PR runtime producer and Smoke Gate now provide an affirmative native producer guarantee for unavailable GitHub step metadata, with an immutable whole-workflow fingerprint and exact run/job/attempt attribution. The existing required-gate contract exercises successful PR/typed-refresh attribution, native smoke/cleanup outcome failures, altered or unavailable definitions, and older producer fail-closed behavior. Native GitHub execution of this new path remains unproved; the successful runtime run for PR #3200 exposed empty step metadata and its earlier producer cannot qualify retroactively. The [CI/CD workflow owner](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) defines the proof contract and fingerprint upkeep. -Focused source proof is owned by `bash dev-tools/tests/pr-required-gate-context-contract.sh`, `bash dev-tools/tests/pr-retarget-workflow-contract.sh`, and `bash dev-tools/tests/ci-lightweight-scope-contract.sh`. Fixtures cover attribution, original-proof selection, one-pass deferral, chronology, frozen target windows, complete bounded evidence, confirmation, and ambiguous or queued/cancelled admission. Fresh [PR #3081](https://github.com/benhook1013/FireMUD/pull/3081) native rehearsal proved one deferred Validation admission with evaluated confirmation and a successful targeted second attempt, four successful first-attempt metadata gates, then five successful settled-source gates and explicit no-op callbacks. Retired #3056 positives are historical targeted-POST/confirmation evidence only. Neither disposable PR may be merged or its old admissions reused. Equal-time queued snapshots, zero-job eviction, fork/empty-association behavior, delayed target snapshots, and retention loss remain native-proof gaps with fail-closed source coverage and explicit recovery requirements; see the [CI/CD owner](../../architecture/system-architecture-cicd.md#required-gate-preservation). Generic activation still requires source validation, review, and default-branch deployment; these local fixtures do not establish hosted activation. +Focused source proof is owned by `bash dev-tools/tests/pr-required-gate-context-contract.sh` (gate names, job conditions, concurrency, smoke producer fingerprint and PLAY-transition checks), `bash dev-tools/tests/pr-retarget-workflow-contract.sh`, and `bash dev-tools/tests/static-analysis-summary-contract.sh` (metadata runs excluded from the summary). ### Hosted Preview, Dev-Demo, and Deployment Delivery diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index de78292a0f..dce9757e88 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -6,6 +6,7 @@ SUMMARY_PAYLOAD="$(python3 - "$ROOT_DIR" <<'PY' from pathlib import Path import base64 import json +import re import sys import yaml @@ -54,7 +55,11 @@ split_markers = [step for step in ci['jobs']['validation-gate']['steps'] if step.get('name') == 'Declare dev tool contract split'] if split_markers != [{'name': 'Declare dev tool contract split', 'run': ':'}]: raise SystemExit('Split contract inventory must retain its unconditional native source marker') -names = [job['name'] for job in ci['jobs'].values()] +def substantive_name(name): + # Metadata-only edits rename a job; substantive runs use the fallback name. + match = re.fullmatch(r"\$\{\{ .* && 'PR Metadata Edit \((.+)\)' \|\| '\1' \}\}", name) + return match[1] if match else name +names = [substantive_name(job['name']) for job in ci['jobs'].values()] for name in names: if '${{' not in name and json.dumps(name, ensure_ascii=False) not in script: raise SystemExit(f'Detached summary is missing the CI job name {name}') diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index aed084a800..b4d7f211f0 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -2,468 +2,125 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -ACTION="$ROOT_DIR/.github/actions/preserve-required-gate/action.yml" -ASSESS_SCRIPT="$ROOT_DIR/.github/actions/preserve-required-gate/assess-required-gate.sh" -[[ -f "$ACTION" ]] || { - echo "required-gate preservation composite action is missing: $ACTION" >&2 - exit 1 -} -[[ -f "$ASSESS_SCRIPT" ]] || { - echo "required-gate preservation assessment script is missing: $ASSESS_SCRIPT" >&2 - exit 1 -} -# shellcheck disable=SC2016 # Assert literal composite action runtime path. -grep -Fxq ' run: bash "$GITHUB_ACTION_PATH/assess-required-gate.sh"' "$ACTION" || { - echo "required-gate action must invoke its checked-in assessment script" >&2 - exit 1 -} -grep -Fq 'using: composite' "$ACTION" || { - echo "required-gate preservation must be a composite action" >&2 - exit 1 -} -grep -Fq ' gate-name:' "$ACTION" || { - echo "required-gate preservation action must expose a gate-name input" >&2 - exit 1 -} -if grep -Fq 'allow-pending' "$ACTION" || grep -Fq 'ALLOW_PENDING' "$ASSESS_SCRIPT"; then - echo "required-gate preservation must not expose a pending-predecessor success override" >&2 - exit 1 -fi - -assert_required_input_declaration() { - local action_path="$1" - local input_name="$2" - local input_block - - input_block="$(awk -v expected_input="$input_name" ' - /^inputs:$/ { - in_inputs = 1 - next - } - in_inputs && /^[^[:space:]][A-Za-z0-9_-]*:/ { - exit - } - in_inputs && $0 == " " expected_input ":" { - capture = 1 - print - next - } - capture && /^ ? ?[A-Za-z0-9_-]+:/ { - exit - } - capture { - print - } - ' "$action_path")" - if [[ -z "$input_block" ]] || - ! grep -Fxq " ${input_name}:" <<<"$input_block" || - ! grep -Fxq ' required: true' <<<"$input_block"; then - echo "required-gate preservation action must declare ${input_name} as a required input" >&2 - exit 1 - fi -} - -for input_name in workflow-name workflow-file workflow-path; do - assert_required_input_declaration "$ACTION" "$input_name" -done -# Keep a required declaration outside the inputs mapping from satisfying the -# final input's block-local requirement. -malformed_action="$(mktemp)" -sed \ - -e '/^ workflow-path:/,/^runs:/ s/^ required: true$/ required: false/' \ - -e '/^runs:/a\ - required: true' \ - "$ACTION" >"$malformed_action" -malformed_input_status=0 -if (assert_required_input_declaration "$malformed_action" workflow-path) >/dev/null 2>&1; then - malformed_input_status=0 -else - malformed_input_status=$? -fi -rm -f "$malformed_action" -if [[ "$malformed_input_status" -eq 0 ]]; then - echo "required-gate preservation action accepted a required declaration outside its inputs block" >&2 - exit 1 -fi -# shellcheck disable=SC2016 # Assert literal action input interpolation syntax. -if ! grep -Fq 'GH_TOKEN: ${{ github.token }}' "$ACTION" || - ! grep -Fq 'BASE_SHA: ${{ github.event.pull_request.base.sha }}' "$ACTION" || - ! grep -Fq 'HEAD_SHA: ${{ github.event.pull_request.head.sha }}' "$ACTION" || - ! grep -Fq 'REQUIRED_GATE_NAME: ${{ inputs.gate-name }}' "$ACTION" || - ! grep -Fq 'PR_NUMBER: ${{ github.event.pull_request.number }}' "$ACTION" || - ! grep -Fq 'EXPECTED_WORKFLOW_NAME: ${{ inputs.workflow-name }}' "$ACTION" || - ! grep -Fq 'EXPECTED_WORKFLOW_FILE: ${{ inputs.workflow-file }}' "$ACTION" || - ! grep -Fq 'EXPECTED_WORKFLOW_PATH: ${{ inputs.workflow-path }}' "$ACTION" || - grep -Fq 'EXPECTED_JOB_ID' "$ACTION"; then - echo "required-gate action must retain caller, head, gate, and workflow identity inputs without local job identity" >&2 - exit 1 -fi - -python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PY_LANE' -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import yaml - -workflow = yaml.safe_load(Path(sys.argv[1]).read_text()) -step = next(step for step in workflow["jobs"]["validation-gate"]["steps"] if step["name"] == "Explain validation lane") -assert step["env"]["FIREMUD_METADATA_ONLY"] == "${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }}" -with tempfile.TemporaryDirectory(prefix="firemud-ci-lane-") as directory: - for value, heading in [("true", "## Metadata-only PR edit"), ("false", "## Source validation")]: - summary = Path(directory) / f"summary-{value}.md" - environment = dict(os.environ, FIREMUD_METADATA_ONLY=value, GITHUB_STEP_SUMMARY=str(summary)) - subprocess.run(["bash", "-e", "-c", step["run"]], check=True, env=environment) - text = summary.read_text() - assert text.startswith(heading + "\n"), text - assert "qualified source validation" in text if value == "true" else "applicable source checks" in text -PY_LANE - -while IFS='|' read -r workflow gate_job_id gate workflow_name workflow_file workflow_path; do - [[ -n "$workflow" ]] || continue - path="$ROOT_DIR/.github/workflows/$workflow" - [[ -f "$path" ]] || { - echo "required-gate caller workflow is missing: $path" >&2 - 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 }}" - grep -Fxq "$expected_run_name" "$path" || { - echo "$workflow must publish its canonical pull-request run title" >&2 - exit 1 - } - gate_block="$(awk -v expected_job_id="$gate_job_id" ' - /^ [A-Za-z0-9_-]+:$/ { - if (capture) { - exit - } - capture = ($0 == " " expected_job_id ":") - } - capture { - print - } - ' "$path")" - [[ -n "$gate_block" ]] || { - echo "$workflow must contain required gate job ID $gate_job_id" >&2 - exit 1 - } - if grep -Fq 'allow-pending:' <<<"$gate_block"; then - echo "$workflow must retain fail-closed required-gate polling" >&2 - exit 1 - fi - if ! grep -Fxq " name: $gate" <<<"$gate_block"; then - echo "$workflow must always emit the required $gate context" >&2 - exit 1 - fi - if ! grep -Fq "Preserve successful required gate on metadata-only edit" <<<"$gate_block"; then - echo "$workflow must preserve the required $gate context on metadata-only edits" >&2 - exit 1 - fi - grep -Fq 'uses: ./.github/actions/preserve-required-gate' <<<"$gate_block" || { - echo "$workflow must call the shared required-gate action" >&2 - exit 1 - } - grep -Fxq " gate-name: $gate" <<<"$gate_block" || { - echo "$workflow must pass its required gate name to the shared action" >&2 - exit 1 - } - grep -Fxq " workflow-name: $workflow_name" <<<"$gate_block" || { - echo "$workflow must pass its exact workflow name to the shared action" >&2 - exit 1 - } - grep -Fxq " workflow-file: $workflow_file" <<<"$gate_block" || { - echo "$workflow must pass its workflow filename to the shared action" >&2 - exit 1 - } - grep -Fxq " workflow-path: $workflow_path" <<<"$gate_block" || { - echo "$workflow must pass its exact workflow path to the shared action" >&2 - exit 1 - } - preserve_block="$(awk ' - /^ - name: Preserve successful required gate on metadata-only edit$/ { - if (found) exit - found=1 - capture=1 - } - capture { - if (/^ - / && $0 != " - name: Preserve successful required gate on metadata-only edit") exit - print - } - ' <<<"$gate_block")" - if [[ "$workflow" == "smoke.yml" ]]; then - # shellcheck disable=SC2016 # Assert literal smoke classification output syntax. - expected_preserve_condition=" if: \${{ steps.smoke_gate_context.outputs.required != 'true' }}" - else - # shellcheck disable=SC2016 # Assert literal metadata-only pull request syntax. - expected_preserve_condition=" if: \${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }}" - if [[ "$workflow" == "codeql.yml" ]]; then - # CodeQL is pull-request-only at this gate, so its condition omits the redundant event-name check. - expected_preserve_condition=" if: \${{ github.event.action == 'edited' && github.event.changes.base.ref == null }}" - fi - fi - grep -Fq "$expected_preserve_condition" <<<"$preserve_block" || { - echo "$workflow $gate preservation must retain its metadata-only condition" >&2 - exit 1 - } - if grep -Fq 'allow-pending:' <<<"$preserve_block"; then - echo "$workflow must retain fail-closed required-gate polling" >&2 - exit 1 - fi - checkout_block="$(awk ' - /^ - name: Check out required-gate action$/ { - if (found) exit - found=1 - capture=1 - } - capture { - if (/^ - / && $0 != " - name: Check out required-gate action") exit - print - } - ' <<<"$gate_block")" - # shellcheck disable=SC2016 # Assert literal trusted pull request base expression. - grep -Fq ' ref: ${{ github.event.pull_request.base.sha }}' <<<"$checkout_block" || { - echo "$workflow $gate must load the shared action from the trusted pull request base SHA" >&2 - exit 1 - } - # shellcheck disable=SC2016 # Assert literal polling syntax is absent from gate callers. - if grep -Fq 'gh api' <<<"$gate_block" || - grep -Eq 'for[[:space:]]+(attempt|poll_attempt|retry_attempt)[[:space:]]+in|while[[:space:]]+.*(attempt|poll|retry)' <<<"$gate_block"; then - echo "$workflow must delegate required-gate polling to the shared action" >&2 - exit 1 - fi - - first_step="$(awk '/^ steps:$/ {in_steps=1; next} in_steps && /^ - / {print; exit}' <<<"$gate_block")" - [[ "$first_step" == ' - name: Harden runner' ]] || { - echo "$workflow $gate must harden the runner as its unconditional first step" >&2 - exit 1 - } - harden_block="$(awk '/^ - name: Harden runner$/{in_harden=1} in_harden{if (/^ - / && $0 != " - name: Harden runner") exit; print}' <<<"$gate_block")" - harden_action_pattern='^ uses: step-security/harden-runner@[0-9a-f]{40}([[:blank:]]+#.*)?[[:blank:]]*$' - fixture_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - for annotation in '' ' # v2.19.3' ' # verified upstream ref'; do - fixture_uses=" uses: step-security/harden-runner@${fixture_sha}${annotation}" - grep -Eq "$harden_action_pattern" <<<"$fixture_uses" || { - echo "required-gate hardening pin rejected a valid immutable SHA annotation form" >&2 - exit 1 - } - done - for invalid_uses in \ - " uses: actions/harden-runner@${fixture_sha}" \ - ' uses: step-security/harden-runner@v2' \ - " uses: step-security/harden-runner@${fixture_sha%?}"; do - if grep -Eq "$harden_action_pattern" <<<"$invalid_uses"; then - echo "required-gate hardening pin accepted an invalid action reference: $invalid_uses" >&2 - exit 1 - fi - done - if grep -Fq ' if:' <<<"$harden_block" || - ! grep -Eq "$harden_action_pattern" <<<"$harden_block" || - ! grep -Fq ' egress-policy: audit' <<<"$harden_block"; then - echo "$workflow $gate hardening must remain unconditional and retain its pinned audit configuration" >&2 - exit 1 - fi - grep -Fq ' checks: read' <<<"$gate_block" || { - echo "$workflow $gate caller must retain checks: read" >&2 - exit 1 - } - grep -Fq ' actions: read' <<<"$gate_block" || { - echo "$workflow $gate caller must retain actions: read for job-step classification" >&2 - exit 1 - } - grep -Fq ' contents: read' <<<"$gate_block" || { - echo "$workflow $gate caller must retain contents: read" >&2 - exit 1 - } - python3 - "$path" "$gate_job_id" "$workflow" "$gate" "$workflow_name" <<'PY' +# Required gates on metadata-only PR edits: a title/body edit (edited with no +# base change) skips each required gate under a non-required name, so the +# earlier substantive result stands and an edit can never turn a failing PR +# green. Base retargets keep the required name and rerun the full gate. +python3 - "$ROOT_DIR" <<'PY' from pathlib import Path import sys import yaml +root = Path(sys.argv[1]) +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), + "smoke.yml": ("PR Smoke Gate", "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), +} +retired = ( + "preserve-required-gate", + "publish-required-gate-status", + "resolve-required-gates", + "statuses: write", +) -expected_job_if = { - "validation-gate": "${{ always() }}", - "security-gate": "${{ always() }}", - "license-gate": "${{ always() }}", - "smoke-gate": "${{ always() && github.event_name == 'pull_request' }}", - "codeql-gate": "${{ always() && github.event_name == 'pull_request' }}", -} -result_step_names = { - "validation-gate": "Enforce validation success", - "security-gate": "Enforce security success", - "license-gate": "Verify ORT results", - "smoke-gate": "Classify smoke gate execution", - "codeql-gate": "Enforce successful CodeQL analysis", -} -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", - "codeql.yml": "Detect CodeQL-Relevant Changes", -} - -path = Path(sys.argv[1]) -job_id = sys.argv[2] -workflow = sys.argv[3] -gate = sys.argv[4] -expected_workflow_name = sys.argv[5] -try: - data = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) - job = data["jobs"][job_id] -except (KeyError, TypeError, yaml.YAMLError) as exc: - raise SystemExit(f"{workflow} must contain a structured {gate} job: {exc}") from exc - -if not isinstance(job, dict): - raise SystemExit(f"{workflow} {gate} job must be a mapping") -if data.get("name") != expected_workflow_name: - raise SystemExit( - f"{workflow} must declare the caller-supplied workflow name {expected_workflow_name!r}; " - f"found {data.get('name')!r}" - ) -if data.get("jobs", {}).get("changes", {}).get("name") != change_job_names[workflow]: - raise SystemExit( - f"{workflow} changes job name must match the selector's expected " - f"{change_job_names[workflow]!r} pattern" - ) -if job_id not in expected_job_if or job_id not in result_step_names: - raise SystemExit( - f"{workflow} {gate}: unknown gate job ID {job_id!r}; " - "add it to expected_job_if and result_step_names" - ) - -preserve_steps = [step for step in job["steps"] if step.get("name") == "Preserve successful required gate on metadata-only edit"] -deferred_steps = [step for step in job["steps"] if step.get("name") == "Report dependency-deferred required gate"] -if len(preserve_steps) != 1 or preserve_steps[0].get("id") != "preserved_gate": - raise SystemExit(f"{workflow} must bind the preservation output") -if "assessment-mode" in preserve_steps[0].get("with", {}): - raise SystemExit(f"{workflow} must use canonical assessment without a mode opt-in") -if len(deferred_steps) != 1 or deferred_steps[0].get("if") != preserve_steps[0]["if"].replace("${{ ", "${{ !cancelled() && ", 1): - raise SystemExit(f"{workflow} must guard every metadata assessment and publication outcome") -if "exit 1" not in deferred_steps[0].get("run", ""): - raise SystemExit(f"{workflow} must fail distinctly for unacknowledged dependency deferral") -if job.get("if") != expected_job_if[job_id]: - raise SystemExit( - f"{workflow} {gate} must retain its exact job if condition: " - f"{expected_job_if[job_id]!r}" +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", + } + for key, value in values.items(): + body = body.replace(key, value) + body = body.replace("&&", " and ").replace("||", " or ").replace("!=", " != ").replace("null", "None") + return eval(body, {"__builtins__": {}}) + + +for directory in (".github/actions/preserve-required-gate", ".github/actions/publish-required-gate-status"): + if (root / directory).exists(): + raise SystemExit(f"retired metadata preservation machinery must stay deleted: {directory}") +if (root / ".github/workflows/resolve-required-gates.yml").exists(): + raise SystemExit("retired required-gate resolver workflow must stay deleted") + +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") + for token in retired: + if token in text: + raise SystemExit(f"{workflow} still references retired metadata preservation: {token}") + data = yaml.load(text, Loader=yaml.BaseLoader) + if data.get("name") != workflow_name: + raise SystemExit(f"{workflow} must keep workflow name {workflow_name!r}") + if set(data["on"]["pull_request"]["types"]) != {"opened", "synchronize", "reopened", "edited"}: + raise SystemExit(f"{workflow} must still trigger on edited so base retargets rerun the gate") + 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 data.get("run-name") != expected_title: + 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}") -needs = job.get("needs") -if isinstance(needs, str): - dependencies = [needs] -elif isinstance(needs, list): - dependencies = needs -else: - raise SystemExit(f"{workflow} {gate} must define needs as a scalar or list") -if "changes" not in dependencies: - raise SystemExit(f"{workflow} {gate} must depend on the changes job") - -steps = job.get("steps") -if not isinstance(steps, list): - raise SystemExit(f"{workflow} {gate} must define steps as a list") -result_steps = [ - step - for step in steps - if isinstance(step, dict) and step.get("name") == result_step_names[job_id] -] -if len(result_steps) != 1: - raise SystemExit( - f"{workflow} {gate} must contain exactly one {result_step_names[job_id]!r} step" - ) -result_env = result_steps[0].get("env") -if not isinstance(result_env, dict) or result_env.get("CHANGES_RESULT") != "${{ needs.changes.result }}": - raise SystemExit( - f"{workflow} {gate} must read needs.changes.result through the exact " - f"{result_step_names[job_id]!r} CHANGES_RESULT field" + gate = data["jobs"][gate_job] + if gate.get("name") != f"${{{{ {META} && 'PR Metadata Edit ({gate_name})' || '{gate_name}' }}}}": + raise SystemExit(f"{workflow} {gate_name} must take a non-required name on metadata-only edits") + expected_if = ( + f"${{{{ always() && github.event_name == 'pull_request' && {PR_SUBSTANTIVE} }}}}" + if pr_only else f"${{{{ always() && {SUBSTANTIVE} }}}}" ) -PY - - group_line=$(grep -m1 '^ group:' "$path" || true) - if [[ "$workflow" == "ci.yml" || "$workflow" == "security.yml" || "$workflow" == "smoke.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 - fi - elif [[ "$group_line" != *"&& 'metadata' || 'required' }}"* ]]; then - echo "$workflow concurrency group must separate metadata and required PR runs" >&2 - exit 1 - fi - if [[ "$group_line" != *"github.event.pull_request.number"* ]]; then - echo "$workflow concurrency group must remain scoped to the PR number" >&2 - exit 1 - fi - if ! grep -Fq ' cancel-in-progress: true' "$path"; then - echo "$workflow must cancel only within its metadata/required concurrency namespace" >&2 - exit 1 - fi - if grep -Fq "cancel-in-progress: \${{ github.event_name != 'pull_request' || github.event.action != 'edited'" "$path"; then - echo "$workflow still uses shared-group conditional cancellation that can race required contexts" >&2 - exit 1 - fi -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 -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' -from pathlib import Path -import sys - -import yaml - -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), -} + if gate.get("if") != expected_if: + raise SystemExit(f"{workflow} {gate_name} must skip only metadata-only edits: {expected_if}") + # Metadata edits skip; opens, pushes, reopens and base retargets run. + if evaluate(gate["if"], "edited", None): + raise SystemExit(f"{workflow} {gate_name} must skip a title/body edit") + for action, base_ref in (("edited", "develop"), ("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") + if "changes" not in (needs if isinstance(needs, list) else [needs]): + raise SystemExit(f"{workflow} {gate_name} must depend on change detection") + 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 any("if" in step and "edited" in step["if"] for step in gate.get("steps", [])): + raise SystemExit(f"{workflow} {gate_name} steps must not branch on edits; the job condition owns that") + + # 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 + condition = job.get("if", "") + if "github.event.action != 'edited' || github.event.changes.base.ref != null" not in condition: + raise SystemExit(f"{workflow} job {job_id} can run for a metadata-only edit") + if job.get("name") in {name for _, _, name, *_ in gates.values()}: + raise SystemExit(f"{workflow} job {job_id} must not reuse a required gate name") -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) + # Metadata runs never cancel or replace the substantive run. 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'", - ) - 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") + 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") if concurrency.get("cancel-in-progress") != "true": - raise SystemExit(f"{workflow} must cancel obsolete required-gate runs") - - gate = data["jobs"][gate_job] - if gate.get("name") != gate_name: - raise SystemExit(f"{workflow} required gate context changed") - -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]: - 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" - ) + raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") PY # shellcheck disable=SC2016 # Match the checked-in arithmetic assignment literally. @@ -896,2594 +553,6 @@ async function scenario(kind, event = "pull_request") { })().catch(error => {console.error(error); process.exitCode = 1;}); NODE -cat >"$tmp_dir/gh" <<'EOF' -#!/usr/bin/env bash -set -euo pipefail -count_file="${GH_RETRY_COUNT_FILE:?}" -if [[ "${GH_SCENARIO:-}" == attempt-fallback-* ]]; then - python3 - "${GH_SCENARIO}" "$@" <<'ATTEMPT_FALLBACK_FIXTURE' -import json -import os -import sys - -scenario = sys.argv[1] -args = sys.argv[2:] -endpoint = next(argument for argument in args if argument.startswith("/repos/")) -if os.environ.get("GH_CALL_COUNT_DIR"): - from pathlib import Path - Path(os.environ["GH_CALL_COUNT_DIR"]).mkdir(parents=True, exist_ok=True) - if "/actions/runs/" in endpoint and "/attempts/" in endpoint: - with (Path(os.environ["GH_CALL_COUNT_DIR"]) / "attempt-endpoints").open("a") as stream: - stream.write(endpoint + "\n") - if scenario == "attempt-fallback-recovery-limit" and "/actions/jobs/" in endpoint: - with (Path(os.environ["GH_CALL_COUNT_DIR"]) / "candidate-direct-jobs").open("a") as stream: - stream.write(endpoint + "\n") -repo = "example/firemud" -head = "a" * 40 -base = "b" * 40 -title = f"CI — Validation pr-123 base-{base} head-{head}" -attempt = 2 if "attempt-two" in scenario else 1 -if scenario == "attempt-fallback-newer-failure": - ids = [100, 101] -elif scenario == "attempt-fallback-recovery-limit": - ids = [100, 101, 102, 103] -else: - ids = [100] -rows = [] -for index, identity in enumerate(ids): - conclusion = "failure" if identity == 101 else "success" - start = f"2026-07-30T0{index + 1}:00:00Z" - finish = f"2026-07-30T0{index + 1}:30:00Z" - rows.append({"app": {"slug": "github-actions"}, "name": "Validation Gate", "id": identity, - "details_url": f"https://github.com/{repo}/actions/runs/{identity}/job/{identity}", - "status": "completed", "conclusion": conclusion, "completed_at": finish, - "started_at": start, "created_at": start}) -if endpoint.endswith("/actions/workflows/ci.yml"): - result = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith(f"/commits/{head}/check-runs"): - result = [{"total_count": len(rows), "check_runs": rows}] -elif "/actions/runs/" in endpoint and endpoint.endswith(f"/attempts/{attempt}/jobs"): - call_number = 1 - if os.environ.get("GH_CALL_COUNT_DIR"): - from pathlib import Path - Path(os.environ["GH_CALL_COUNT_DIR"]).mkdir(parents=True, exist_ok=True) - call_file = Path(os.environ["GH_CALL_COUNT_DIR"]) / f"attempt-jobs-{endpoint.split('/actions/runs/')[1].split('/')[0]}-{attempt}" - call_number = int(call_file.read_text()) + 1 if call_file.exists() else 1 - call_file.write_text(str(call_number)) - assert "per_page=100" in args and "--paginate" not in args and "--slurp" not in args, args - assert scenario != "attempt-fallback-known-skipped", "known preservation evidence must stay on the ordinary path" - identity = int(endpoint.split("/actions/runs/")[1].split("/")[0]) - candidate = next(row for row in rows if row["id"] == identity) - index = ids.index(identity) - steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", - "conclusion": "skipped" if scenario != "attempt-fallback-metadata" else "success"}] - job = {"id": identity, "run_id": identity, - "run_attempt": 1 if scenario == "attempt-fallback-attempt-two-mismatch" else attempt, "head_sha": head, "head_branch": "proof-branch", - "workflow_name": "CI — Validation", "name": "Validation Gate", "status": "completed", - "conclusion": candidate["conclusion"], "created_at": candidate["created_at"], - "started_at": candidate["started_at"], "completed_at": candidate["completed_at"], - "html_url": candidate["details_url"], "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{identity}", - "steps": steps} - if scenario == "attempt-fallback-empty": - job["steps"] = [] - if scenario == "attempt-fallback-no-steps": - job.pop("steps") - if scenario == "attempt-fallback-wrong-check-url": - job["check_run_url"] = f"https://api.github.com/repos/{repo}/check-runs/999" - if scenario == "attempt-fallback-duplicate": - result = {"total_count": 2, "jobs": [job, dict(job)]} - elif scenario == "attempt-fallback-malformed": - result = {"total_count": "1", "jobs": [job]} - elif scenario == "attempt-fallback-oversized": - others = [{"id": 1000 + index, "run_id": identity, "run_attempt": 1, "head_sha": head, "head_branch": "proof-branch", - "workflow_name": "CI — Validation", "name": f"Build and Test (module-{index:03d})", - "status": "completed", "conclusion": "success", - "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{1000 + index}"} - for index in range(100)] - result = {"total_count": 101, "jobs": [job, *others]} - elif scenario == "attempt-fallback-incomplete": - result = {"total_count": 2, "jobs": [job]} - else: - if scenario == "attempt-fallback-wrong-attempt": - job["run_attempt"] = 2 - if scenario == "attempt-fallback-wrong-head": - job["head_sha"] = "d" * 40 - if scenario == "attempt-fallback-wrong-workflow": - job["workflow_name"] = "Security Checks" - result = {"total_count": 1, "jobs": [job]} -elif "/actions/runs/" in endpoint and "/attempts/" in endpoint: - identity = int(endpoint.split("/actions/runs/")[1].split("/")[0]) - if scenario == "attempt-fallback-attempt-two-api-error": - raise SystemExit(31) - result = {"id": identity, "workflow_id": 42, - "run_attempt": 1 if scenario == "attempt-fallback-attempt-two-mismatch" else attempt, "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "head_sha": head, "head_branch": "proof-branch", "display_title": title, - "repository": {"full_name": repo}, "head_repository": {"full_name": repo}, "event": "pull_request", - "status": "completed", - "pull_requests": [{"number": 123, "base": {"sha": base}, "head": {"sha": head}}]} - if scenario == "attempt-fallback-stale-tuple": - result["display_title"] = result["display_title"].replace(base, "c" * 40) -elif "/actions/runs/" in endpoint: - identity = int(endpoint.rsplit("/", 1)[1]) - result = {"id": identity, "workflow_id": 42, "run_attempt": attempt, "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "head_sha": head, "head_branch": "proof-branch", "display_title": title, - "repository": {"full_name": repo}, "head_repository": {"full_name": repo}, "event": "pull_request", - "pull_requests": [{"number": 123, "base": {"sha": base}, "head": {"sha": head}}]} -elif "/actions/jobs/" in endpoint: - identity = int(endpoint.rsplit("/", 1)[1]) - candidate = next(row for row in rows if row["id"] == identity) - result = {"id": identity, "run_id": identity, "run_attempt": attempt, "head_sha": head, - "workflow_name": "CI — Validation", "name": "Validation Gate", "status": "completed", - "conclusion": candidate["conclusion"], "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{identity}", - "steps": []} - if scenario == "attempt-fallback-known-skipped": - result["steps"] = [ - {"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "skipped"}, - ] - if scenario == "attempt-fallback-duplicate-direct": - result["steps"] = [ - {"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "skipped"}, - {"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "failure"}, - ] - if scenario == "attempt-fallback-malformed-direct": - result["steps"] = "unavailable" -elif "/check-runs/" in endpoint: - identity = int(endpoint.rsplit("/", 1)[1]) - candidate = next(row for row in rows if row["id"] == identity) - result = {"id": identity, "app": {"id": 15368, "slug": "github-actions"}, "head_sha": head, - "name": "Validation Gate", "status": "completed", "conclusion": candidate["conclusion"], - "details_url": candidate["details_url"], "started_at": candidate["started_at"], - "completed_at": candidate["completed_at"]} - if scenario == "attempt-fallback-wrong-app": - result["app"]["id"] = 1 - if scenario == "attempt-fallback-wrong-check-details": - result["details_url"] += "?changed=true" -else: - raise AssertionError(endpoint) -print(json.dumps(result)) -ATTEMPT_FALLBACK_FIXTURE - exit 0 -fi -if [[ "${GH_SCENARIO:-}" == cancellation-* ]]; then - python3 - "$GH_SCENARIO" "$@" <<'CANCELLATION_FIXTURE' -import copy -import json -import os -import sys -scenario = sys.argv[1] -endpoint = next(argument for argument in sys.argv[2:] if argument.startswith("/repos/")) -head, base = os.environ["HEAD_SHA"], os.environ["BASE_SHA"] -repo = os.environ["GITHUB_REPOSITORY"] -title = f"CI — Validation pr-{os.environ['PR_NUMBER']} base-{base} head-{head}" -names = ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", - "Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", - "Build and Test (account-service / $" + "{{ matrix.partition }})", - "Build and Test (world-management-service / $" + "{{ matrix.partition }})", - "Build and Test (game-session-service / $" + "{{ matrix.partition }})", "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", - "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", - "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", - "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", - "Account Coverage Aggregate", "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] -# Retain the exact old 26-job inventory; the new split adds exactly one name. -if scenario.startswith("cancellation-dev-tool-"): - names.insert(-1, "Dev Tool Validation Contracts") -def step(name, conclusion): - return {"name": name, "status": "completed", "conclusion": conclusion} -# Exact split-matrix cancellation shape: prerequisites never reached a step; -# slow-service aggregation prerequisites were skipped without running, -# while the always() gate failed only its enforcement step after cancellation. -jobs = [{"id": 500 + index, "run_id": 100, "run_attempt": 1, "head_sha": head, - "name": name, "workflow_name": "CI — Validation", "status": "completed", - "conclusion": "cancelled", "steps": [], - "html_url": f"https://github.com/{repo}/actions/runs/100/job/{500 + index}", - "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{600 + index}"} - for index, name in enumerate(names)] -aggregate = next(job for job in jobs if job["name"] == "Account Coverage Aggregate") -aggregate["conclusion"] = "skipped" -game_session_aggregate = next(job for job in jobs if job["name"] == "Game Session Coverage Aggregate") -game_session_aggregate["conclusion"] = "skipped" -gate = jobs[-1] -gate["conclusion"] = "failure" -gate["steps"] = [step("Set up job", "success"), step("Pre Harden runner", "success"), - step("Harden runner", "success"), step("Check out required-gate action", "skipped"), - step("Preserve successful required gate on metadata-only edit", "skipped"), - step("Publish pending required gate status", "skipped"), - step("Report dependency-deferred required gate", "skipped"), - step("Enforce validation success", "failure"), step("Post Harden runner", "success"), - step("Complete job", "success")] -if scenario.startswith("cancellation-dev-tool-"): - gate["steps"].append(step("Declare dev tool contract split", "skipped")) -if scenario == "cancellation-dev-tool-duplicate-marker": - gate["steps"].append(step("Declare dev tool contract split", "skipped")) -if scenario == "cancellation-old-shape": - jobs = [job for job in jobs if job["name"] not in ( - "Build and Test (account-service / $" + "{{ matrix.partition }})", - "Build and Test (game-session-service / $" + "{{ matrix.partition }})")] -if scenario == "cancellation-partial-new-shape": - jobs = [job for job in jobs if job["name"] != - "Build and Test (game-session-service / $" + "{{ matrix.partition }})"] -if scenario == "cancellation-pre-world-shape": - jobs = [job for job in jobs if job["name"] not in ( - "Build and Test (world-management-service / $" + "{{ matrix.partition }})", - "World Coverage Aggregate")] -if scenario == "cancellation-world-missing-partition": - jobs = [job for job in jobs if job["name"] != - "Build and Test (world-management-service / $" + "{{ matrix.partition }})"] -if scenario == "cancellation-world-aggregate-executed": - world = next(job for job in jobs if job["name"] == "World Coverage Aggregate") - world["steps"] = [step("Verify complete World partition and report union", "success")] -if scenario == "cancellation-world-aggregate-failed": - world = next(job for job in jobs if job["name"] == "World Coverage Aggregate") - world["conclusion"] = "failure" -if scenario == "cancellation-real-failure": - jobs[1]["conclusion"] = "failure" - jobs[1]["steps"] = [step("Run lint", "failure")] -if scenario == "cancellation-hidden-step-failure": - jobs[1]["steps"] = [step("Assert", "failure")] -if scenario == "cancellation-executed-check": - jobs[1]["steps"] = [step("Assert", "success")] -if scenario == "cancellation-gate-other-failure": - gate["steps"][2]["conclusion"] = "failure" -if scenario == "cancellation-unknown-assertion": - jobs[1]["steps"] = [step("Assert", "unknown")] -if scenario == "cancellation-timed-out": - jobs[1]["conclusion"] = "timed_out" -if scenario == "cancellation-action-required": - jobs[1]["conclusion"] = "action_required" -if scenario == "cancellation-metadata": - gate["steps"][4]["conclusion"] = "failure" -if scenario == "cancellation-aggregate-executed": - aggregate["steps"] = [step("Verify complete Account partition and report union", "success")] -if scenario == "cancellation-aggregate-failed": - aggregate["conclusion"] = "failure" - aggregate["steps"] = [step("Verify complete Account partition and report union", "failure")] -if scenario == "cancellation-game-session-aggregate-executed": - game_session_aggregate["steps"] = [step("Verify complete Game Session partition and report union", "success")] -if scenario == "cancellation-game-session-aggregate-failed": - game_session_aggregate["conclusion"] = "failure" - game_session_aggregate["steps"] = [step("Verify complete Game Session partition and report union", "failure")] -if scenario == "cancellation-dev-tool-real-failure": - sibling = next(job for job in jobs if job["name"] == "Dev Tool Validation Contracts") - sibling["conclusion"] = "failure" - sibling["steps"] = [step("Validate dev tool validation contracts", "failure")] -if scenario == "cancellation-dev-tool-executed": - next(job for job in jobs if job["name"] == "Dev Tool Validation Contracts")["steps"] = [step("Set up Python", "success")] -if scenario == "cancellation-dev-tool-skipped": - next(job for job in jobs if job["name"] == "Dev Tool Validation Contracts")["conclusion"] = "skipped" -run = {"id": 100, "workflow_id": 42, "run_attempt": 1, "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "head_sha": head, "display_title": title, - "repository": {"full_name": repo}, "event": "pull_request", "pull_requests": [], - "status": "completed", "conclusion": "cancelled"} -def check(job): - return {"id": int(job["check_run_url"].rsplit("/", 1)[1]), "app": {"slug": "github-actions", "id": 15368}, - "name": job["name"], "head_sha": head, "details_url": job["html_url"], - "status": job["status"], "conclusion": job["conclusion"], - "started_at": "2026-07-30T01:00:00Z", "completed_at": "2026-07-30T02:00:00Z"} -if endpoint.endswith("/actions/workflows/ci.yml"): - output = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith("/commits/" + head + "/check-runs"): - with open(os.environ["GH_RETRY_COUNT_FILE"], "w") as stream: - stream.write("1") - checks = [check(gate)] - if scenario in ("cancellation-pending", "cancellation-recovery", "cancellation-older-success"): - replacement = check(gate) - replacement.update(id=420, details_url=f"https://github.com/{repo}/actions/runs/101/job/221", - status="queued", conclusion=None, started_at=None, completed_at=None) - if os.environ.get("GH_CANCELLATION_RECOVERED") == "true" or scenario == "cancellation-older-success": - replacement.update(status="completed", conclusion="success", started_at="2026-07-30T03:00:00Z", - completed_at="2026-07-30T04:00:00Z" if scenario != "cancellation-older-success" else "2026-07-30T00:30:00Z") - checks.append(replacement) - output = [{"total_count": len(checks), "check_runs": checks}] -elif endpoint.endswith("/actions/jobs/220"): - output = gate -elif endpoint.endswith("/actions/jobs/221"): - output = copy.deepcopy(gate) - output.update(id=221, run_id=101, check_run_url=f"https://api.github.com/repos/{repo}/check-runs/420") - output["steps"][4]["conclusion"] = "skipped" -elif "/actions/jobs/" in endpoint: - job_id = int(endpoint.rsplit("/", 1)[1]) - output = copy.deepcopy(next(job for job in jobs if job["id"] == job_id)) -elif "/attempts/1/jobs" in endpoint: - snapshot = copy.deepcopy(jobs) - if scenario == "cancellation-partial": - snapshot.pop(0) - if scenario == "cancellation-wrong-attempt": - snapshot[0]["run_attempt"] = 2 - if scenario == "cancellation-wrong-head": - snapshot[0]["head_sha"] = "c" * 40 - if scenario == "cancellation-duplicate": - snapshot[0] = snapshot[1] - if scenario == "cancellation-missing-steps": - del snapshot[0]["steps"] - if scenario == "cancellation-dev-tool-wrong-name": - snapshot[-2]["name"] = "Unknown Contract Checks" - if scenario == "cancellation-dev-tool-duplicate-name": - snapshot[-2]["name"] = "Dev Tool Contract Checks" - if scenario == "cancellation-dev-tool-missing-sibling": - snapshot = [job for job in snapshot if job["name"] != "Dev Tool Validation Contracts"] - if scenario == "cancellation-dev-tool-missing-original": - snapshot = [job for job in snapshot if job["name"] != "Dev Tool Contract Checks"] - if scenario == "cancellation-dev-tool-missing-other": - snapshot = [job for job in snapshot if job["name"] != "ShellCheck"] - if scenario == "cancellation-dev-tool-extra-name": - extra = copy.deepcopy(snapshot[-2]) - extra.update(id=900, name="Unknown Contract Checks") - snapshot.append(extra) - output = [{"total_count": len(snapshot), "jobs": snapshot}] -elif "/check-runs/" in endpoint: - output = check(next(job for job in jobs if job["check_run_url"].endswith("/" + endpoint.rsplit("/", 1)[1]))) - if scenario == "cancellation-wrong-app": - output["app"]["id"] = 1 - if scenario == "cancellation-check-conflict": - output["conclusion"] = "success" -elif "/actions/runs/" in endpoint: - output = copy.deepcopy(run) - if endpoint.endswith("/101"): - output.update(id=101, conclusion=None, status="queued") - if scenario == "cancellation-run-conflict" and "/attempts/" in endpoint: - output["display_title"] = "unbound" - if scenario in ("cancellation-later-attempt", "cancellation-later-attempt-failed-source"): - # Latest run is attempt 2; candidate gate belongs to retained attempt 1. - if "/attempts/" not in endpoint: - output.update(run_attempt=2, conclusion="success") - elif scenario == "cancellation-later-attempt-failed-source": - output["conclusion"] = "failure" -else: - raise AssertionError(endpoint) -print(json.dumps(output)) -CANCELLATION_FIXTURE - exit 0 -fi -if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - mkdir -p "$GH_CALL_COUNT_DIR" -fi -if [[ "$*" == *"/actions/workflows/${EXPECTED_WORKFLOW_FILE}/runs"* ]]; then - if [[ "$*" == *"head_sha="* || "$*" != *"event=pull_request"* || - "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then - echo "simulated active workflow lookup used a branch-tip filter or omitted event/pagination" >&2 - exit 90 - fi - active_status="" - for argument in "$@"; do - case "$argument" in - status=*) active_status="${argument#status=}" ;; - esac - done - case "$active_status" in - in_progress|queued|requested|waiting|pending) ;; - *) - echo "simulated active workflow lookup omitted a single supported status filter" >&2 - exit 90 - ;; - esac - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - active_call_file="$GH_CALL_COUNT_DIR/active-$active_status" - active_call_count=0 - [[ -f "$active_call_file" ]] && active_call_count="$(<"$active_call_file")" - printf '%s' "$((active_call_count + 1))" >"$active_call_file" - fi - case "${GH_SCENARIO:-}" in - active-workflow-delayed-gate|active-workflow-late-arrival|active-workflow-wrong-base|active-workflow-metadata-only|active-workflow-mismatched-tuple) - if [[ "${GH_SCENARIO}" == "active-workflow-late-arrival" && - "$(<"$count_file")" -ne 92 ]]; then - printf '[{"workflow_runs":[]} ]\n' - exit 0 - fi - if [[ "$active_status" != "in_progress" ]]; then - printf '[{"workflow_runs":[]} ]\n' - exit 0 - fi - display_title="CI — Validation pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" - [[ "${GH_SCENARIO}" == "active-workflow-wrong-base" ]] && display_title="CI — Validation pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - run_head_sha="${HEAD_SHA}" - pull_requests='[]' - if [[ "${GH_SCENARIO}" == "active-workflow-delayed-gate" || - "${GH_SCENARIO}" == "active-workflow-late-arrival" ]]; then - # GitHub may report the synthetic merge SHA for pull_request runs; - # the populated PR tuple remains the authoritative identity. - run_head_sha=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - elif [[ "${GH_SCENARIO}" == "active-workflow-mismatched-tuple" ]]; then - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"dddddddddddddddddddddddddddddddddddddddd\"}}]" - fi - printf '[{"workflow_runs":[{"id":100,"workflow_id":42,"name":"%s","path":".github/workflows/ci.yml","head_sha":"%s","display_title":"%s","repository":{"full_name":"example/firemud"},"event":"pull_request","status":"in_progress","pull_requests":%s}]}]\n' "$display_title" "$run_head_sha" "$display_title" "$pull_requests" - ;; - active-workflow-malformed-list) - printf '[{"workflow_runs":"invalid"}]\n' - ;; - *) - printf '[{"workflow_runs":[]}]\n' - ;; - esac - exit 0 -fi -if [[ "$*" == *"/actions/workflows/"* ]]; then - if [[ "$*" != *"/actions/workflows/${EXPECTED_WORKFLOW_FILE}"* ]]; then - echo "simulated workflow lookup did not target the expected workflow filename" >&2 - exit 90 - fi - if [[ "${GH_SCENARIO:-}" == "no-local-workflow-file" ]]; then - : >"$count_file" - fi - if [[ "${GH_SCENARIO:-}" == "workflow-identity-mismatch" ]]; then - cat <<'JSON' -{"id":99,"name":"Security Checks","path":".github/workflows/security.yml"} -JSON - else - cat <<'JSON' -{"id":42,"name":"CI — Validation","path":".github/workflows/ci.yml"} -JSON - fi - exit 0 -fi -if [[ "$*" == *"/actions/runs/100/jobs"* ]]; then - if [[ "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then - echo "simulated workflow jobs lookup omitted pagination" >&2 - exit 90 - fi - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - active_jobs_file="$GH_CALL_COUNT_DIR/run-jobs-100" - active_jobs_count=0 - [[ -f "$active_jobs_file" ]] && active_jobs_count="$(<"$active_jobs_file")" - printf '%s' "$((active_jobs_count + 1))" >"$active_jobs_file" - fi - change_conclusion=success - [[ "${GH_SCENARIO:-}" == "active-workflow-metadata-only" ]] && change_conclusion=skipped - printf '[{"jobs":[{"id":20,"name":"Detect CI-Relevant Changes","status":"completed","conclusion":"%s"}]}]\n' "$change_conclusion" - exit 0 -fi -if [[ "$*" == *"/actions/jobs/"* ]]; then - job_endpoint="${!#}" - job_id="${job_endpoint##*/}" - run_id="$job_id" - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - job_call_file="$GH_CALL_COUNT_DIR/jobs-$job_id" - job_call_count=0 - [[ -f "$job_call_file" ]] && job_call_count="$(<"$job_call_file")" - printf '%s' "$((job_call_count + 1))" >"$job_call_file" - fi - if [[ "${GH_SCENARIO:-}" == "job-failure-retry" && "$job_id" == "100" && - ! -e "${count_file}.job-failure-once" ]]; then - : >"${count_file}.job-failure-once" - echo "gh: HTTP 503 Service Unavailable" >&2 - exit 1 - fi - job_workflow_name='CI — Validation' - if [[ "${GH_SCENARIO:-}" == "dynamic-run-name" || - "${GH_SCENARIO:-}" == "dynamic-run-name-fork-empty" ]]; then - job_workflow_name="${job_workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" - elif [[ "${GH_SCENARIO:-}" == "wrong-job-workflow-name" ]]; then - job_workflow_name='Security Checks' - fi - metadata=false - if [[ "${GH_SCENARIO:-}" == "multiple-metadata" ]] || - [[ "${GH_SCENARIO:-}" == "latest-pending-preferred" && "${job_id}" == "101" ]] || - [[ "${GH_SCENARIO:-}" == "cache-metadata-across-polls" && "${job_id}" == "100" ]]; then - metadata=true - fi - if [[ "${metadata}" == "true" ]]; then - case "${GH_SCENARIO}:${job_id}" in - multiple-metadata:100) preserve_conclusion=success ;; - multiple-metadata:101) preserve_conclusion=failure ;; - multiple-metadata:102) preserve_conclusion=timed_out ;; - multiple-metadata:103) preserve_conclusion=cancelled ;; - *) preserve_conclusion=success ;; - esac - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"%s","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"%s"}]}\n' "$job_id" "$run_id" "$job_workflow_name" "$job_id" "$preserve_conclusion" - elif [[ "${GH_SCENARIO:-}" == "unverified-pending-gate" && "${job_id}" == "100" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "pending-preservation-step-not-concluded" && - "${job_id}" == "100" && "$(<"$count_file")" -le 3 ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "pending-gate-discovery-throttle" && - "${job_id}" == "100" && "$(<"$count_file")" -le 5 ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "pending-missing-step-with-failed-substantive" && - "${job_id}" == "101" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "completed-preservation-step-lag" && - "${job_id}" == "100" && "$(<"$count_file")" -eq 1 ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "completed-preservation-step-persistent-lag" && - "${job_id}" == "100" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" =~ ^completed-(cancelled|skipped|stale)-missing-step$ && - "${job_id}" == "100" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - else - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"%s","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"skipped"}]}\n' "$job_id" "$run_id" "$job_workflow_name" "$job_id" - fi - exit 0 -fi -if [[ "$*" == *"/actions/runs/"* ]]; then - run_endpoint="${!#}" - run_id="${run_endpoint##*/}" - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - run_call_file="$GH_CALL_COUNT_DIR/runs-$run_id" - run_call_count=0 - [[ -f "$run_call_file" ]] && run_call_count="$(<"$run_call_file")" - printf '%s' "$((run_call_count + 1))" >"$run_call_file" - fi - workflow_name='CI — Validation' - workflow_path='.github/workflows/ci.yml' - workflow_id=42 - run_repository='example/firemud' - head_repository='example/firemud' - pull_requests='[{"number":123}]' - display_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" - if [[ "${GH_SCENARIO:-}" == "dynamic-run-name" || - "${GH_SCENARIO:-}" == "dynamic-run-name-fork-empty" ]]; then - workflow_name="$display_title" - display_title="$workflow_name" - elif [[ "${GH_SCENARIO:-}" == "wrong-run-name" ]]; then - workflow_name='Security Checks' - fi - if [[ "${GH_SCENARIO:-}" == "valid-new-tuple" ]]; then - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - elif [[ "${GH_SCENARIO:-}" == "stale-then-current-tuple" ]]; then - if [[ "${run_id}" == "200" ]]; then - display_title="${workflow_name} pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"cccccccccccccccccccccccccccccccccccccccc\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - else - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - fi - fi - if [[ "${GH_SCENARIO:-}" == "fork-empty-association" || - "${GH_SCENARIO:-}" == "dynamic-run-name-fork-empty" ]]; then - pull_requests='[]' - head_repository='other-owner/firemud' - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-pr" ]]; then - pull_requests='[]' - display_title="${workflow_name} pr-456 base-${BASE_SHA} head-${HEAD_SHA}" - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-base" ]]; then - pull_requests='[]' - display_title="${workflow_name} pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - elif [[ "${GH_SCENARIO:-}" == "populated-wrong-base" ]]; then - display_title="${workflow_name} pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"cccccccccccccccccccccccccccccccccccccccc\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-head" ]]; then - pull_requests='[]' - display_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-dddddddddddddddddddddddddddddddddddddddd" - elif [[ "${GH_SCENARIO:-}" == "populated-wrong-head" ]]; then - display_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-dddddddddddddddddddddddddddddddddddddddd" - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"dddddddddddddddddddddddddddddddddddddddd\"}}]" - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-title" ]]; then - pull_requests='[]' - display_title='not the canonical run title' - elif [[ "${GH_SCENARIO:-}" == "empty-malformed-association" ]]; then - pull_requests='null' - elif [[ "${GH_SCENARIO:-}" == "other-pr-association" ]]; then - pull_requests='[{"number":456}]' - elif [[ "${GH_SCENARIO:-}" == "cross-workflow-same-name" || - "${GH_SCENARIO:-}" == "duplicate-invalid-run-identity" ]]; then - workflow_path='.github/workflows/other.yml' - workflow_id=99 - elif [[ "${GH_SCENARIO:-}" == "run-path-ref-suffix" ]]; then - workflow_path='.github/workflows/ci.yml@main' - elif [[ "${GH_SCENARIO:-}" == "run-path-ref-suffix-plus" ]]; then - workflow_path='.github/workflows/ci.yml@feature+metadata' - elif [[ "${GH_SCENARIO:-}" == "run-path-ref-suffix-at" ]]; then - workflow_path='.github/workflows/ci.yml@feature@metadata' - elif [[ "${GH_SCENARIO:-}" == "malformed-run-path-ref-suffix" ]]; then - workflow_path='.github/workflows/ci.yml@' - elif [[ "${GH_SCENARIO:-}" == "fork-head-same-sha" ]]; then - head_repository='other-owner/firemud' - elif [[ "${GH_SCENARIO:-}" == "wrong-run-repository" ]]; then - run_repository='other-owner/firemud' - head_repository='other-owner/firemud' - fi - printf '{"id":%s,"workflow_id":%s,"name":"%s","path":"%s","head_sha":"%s","display_title":"%s","repository":{"full_name":"%s"},"head_repository":{"full_name":"%s"},"event":"pull_request","pull_requests":%s}\n' "$run_id" "$workflow_id" "$workflow_name" "$workflow_path" "$HEAD_SHA" "$display_title" "$run_repository" "$head_repository" "$pull_requests" - exit 0 -fi -if [[ "$*" != *"/repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/check-runs"* ]]; then - echo "simulated gh api call did not target the pull request head check-runs endpoint" >&2 - exit 90 -fi -if [[ "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then - echo "simulated gh api call omitted pagination/slurp" >&2 - exit 90 -fi -if [[ "$*" != *"check_name=${REQUIRED_GATE_NAME}"* || "$*" != *"filter=all"* ]]; then - echo "simulated gh api call did not scope the query to the required gate name" >&2 - exit 90 -fi -if [[ "$*" == *"--jq"* ]]; then - echo "simulated gh api call must leave filtering to external jq" >&2 - exit 90 -fi -count=0 -if [[ -f "$count_file" ]]; then - count="$(<"$count_file")" -fi -count=$((count + 1)) -printf '%s' "$count" >"$count_file" -if [[ "${GH_SCENARIO:-}" == check-coverage-* ]]; then - python3 - "$GH_SCENARIO" <<'PYTHON' -import json -import sys -scenario = sys.argv[1] -def check(identity): - return {"app": {"slug": "github-actions"}, "name": "Validation Gate", "id": identity, - "details_url": f"https://github.com/example/firemud/actions/runs/{identity}/job/{identity}", - "status": "completed", "conclusion": "success", "completed_at": "2026-07-30T02:00:00Z", - "started_at": "2026-07-30T01:00:00Z"} -pages = [{"total_count": 1, "check_runs": [check(100)]}] -if scenario == "check-coverage-truncated": - # Omit the newer failed original from the existing newer-failure case. - pages[0]["total_count"] = 2 -elif scenario == "check-coverage-missing-total": - pages[0].pop("total_count") -elif scenario == "check-coverage-malformed-total": - pages[0]["total_count"] = "1" -elif scenario == "check-coverage-overcount": - pages[0]["total_count"] = 0 -elif scenario == "check-coverage-invalid-id": - pages[0]["check_runs"][0]["id"] = "100" -elif scenario == "check-coverage-empty-pages": - pages = [] -elif scenario == "check-coverage-duplicate": - pages = [{"total_count": 2, "check_runs": [check(100)]}, {"total_count": 2, "check_runs": [check(100)]}] -elif scenario in {"check-coverage-multi", "check-coverage-inconsistent-total"}: - pages = [{"total_count": 2, "check_runs": [check(100)]}, - {"total_count": 3 if scenario.endswith("inconsistent-total") else 2, "check_runs": [check(101)]}] -else: - raise AssertionError(scenario) -print(json.dumps(pages)) -PYTHON - exit 0 -fi -case "${GH_SCENARIO:-failure-retry}" in - latest-pending-preferred) - if [[ "$count" -eq 1 ]]; then - cat <<'JSON' -[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - else - cat <<'JSON' -[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - fi - ;; - missing-created-at) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - pending-predecessor) - if [[ "$count" -eq 1 ]]; then - cat <<'JSON' -[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - else - cat <<'JSON' -[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - fi - ;; - queued-null-started-at) - if [[ "$count" -eq 1 ]]; then - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"queued","conclusion":null,"started_at":null,"created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - retry-success) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","completed_at":"2026-07-30T03:00:00Z","conclusion":"success","started_at":"2026-07-30T02:00:00Z"}]}]\n' - ;; - no-local-workflow-file) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - no-prior|active-workflow-wrong-base|active-workflow-metadata-only|active-workflow-mismatched-tuple|active-workflow-malformed-list) - printf '[{"total_count":0,"check_runs":[]}]\n' - ;; - delayed-predecessor) - if [[ "$count" -eq 1 ]]; then - printf '[{"total_count":0,"check_runs":[]}]\n' - elif [[ "$count" -eq 2 ]]; then - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - delayed-predecessor-after-19-minutes) - if [[ "$count" -le 77 ]]; then - printf '[{"total_count":0,"check_runs":[]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:20:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - active-workflow-delayed-gate) - if [[ "$count" -le 97 ]]; then - printf '[{"total_count":0,"check_runs":[]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:30:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - active-workflow-late-arrival) - if [[ "$count" -le 92 ]]; then - printf '[{"total_count":0,"check_runs":[]} ]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:30:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - failed-predecessor) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"failure","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - newer-failure-over-success) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:50:00Z","created_at":"2026-07-30T00:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"failure","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:50:00Z","created_at":"2026-07-30T01:50:00Z"}]}]\n' - ;; - same-timestamp-newer-failure) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"failure","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - stale-then-current-tuple) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":201,"details_url":"https://github.com/example/firemud/actions/runs/201/job/201","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - cross-workflow-same-name|fork-empty-association|dynamic-run-name|dynamic-run-name-fork-empty|wrong-run-name|wrong-job-workflow-name|empty-wrong-pr|empty-wrong-base|populated-wrong-base|empty-wrong-head|populated-wrong-head|empty-wrong-title|empty-malformed-association|other-pr-association|valid-new-tuple) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - duplicate-invalid-run-identity) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":201,"details_url":"https://github.com/example/firemud/actions/runs/200/job/201","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - run-path-ref-suffix|run-path-ref-suffix-plus|run-path-ref-suffix-at|malformed-run-path-ref-suffix) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - details-url-query|details-url-fragment|malformed-details-url-suffix) - details_suffix='?check_suite_focus=true' - [[ "${GH_SCENARIO:-}" == "details-url-fragment" ]] && details_suffix='#step:1:2' - [[ "${GH_SCENARIO:-}" == "malformed-details-url-suffix" ]] && details_suffix='@evil' - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200%s","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' "$details_suffix" - ;; - fork-head-same-sha) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - wrong-run-repository) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - unknown-app) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"other-checks"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - unknown-check-name) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Other Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - invalid-job-id) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/not-a-number","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - missing-job-id) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - completed-preservation-step-lag) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - completed-preservation-step-persistent-lag) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - completed-cancelled-missing-step|completed-skipped-missing-step|completed-stale-missing-step) - case "${GH_SCENARIO}" in - completed-cancelled-missing-step) non_authoritative_conclusion=cancelled ;; - completed-skipped-missing-step) non_authoritative_conclusion=skipped ;; - completed-stale-missing-step) non_authoritative_conclusion=stale ;; - esac - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"%s","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' "$non_authoritative_conclusion" - ;; - unsupported-status) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"mysterious","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - missing-timestamp) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - multiple-metadata) - printf '[{"total_count":4,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:50:00Z","created_at":"2026-07-30T00:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"failure","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:50:00Z","created_at":"2026-07-30T01:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":102,"details_url":"https://github.com/example/firemud/actions/runs/102/job/102","status":"completed","conclusion":"timed_out","completed_at":"2026-07-30T03:00:00Z","started_at":"2026-07-30T02:50:00Z","created_at":"2026-07-30T02:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":103,"details_url":"https://github.com/example/firemud/actions/runs/103/job/103","status":"completed","conclusion":"cancelled","completed_at":"2026-07-30T04:00:00Z","started_at":"2026-07-30T03:50:00Z","created_at":"2026-07-30T03:50:00Z"}]}]\n' - ;; - self-run-excluded) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":1,"details_url":"https://github.com/example/firemud/actions/runs/999/job/1","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"failure","started_at":"2026-07-30T02:00:00Z","created_at":"2026-07-30T02:00:00Z"}]}]\n' - ;; - alternate-pending) - case "$count" in - 1) status=requested ;; - 2) status=waiting ;; - 3) status=pending ;; - *) status=completed ;; - esac - if [[ "$status" == "completed" ]]; then - conclusion='"success"' - else - conclusion=null - fi - completed_at=null - if [[ "$status" == "completed" ]]; then - completed_at='"2026-07-30T02:00:00Z"' - fi - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"%s","conclusion":%s,"completed_at":%s,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' "$status" "$conclusion" "$completed_at" - ;; - pending-preservation-step-not-concluded) - case "$count" in - 1) status=queued ;; - 2) status=in_progress ;; - 3) status=waiting ;; - *) status=completed ;; - esac - if [[ "$status" == "completed" ]]; then - conclusion='"success"' - completed_at='"2026-07-30T02:00:00Z"' - else - conclusion=null - completed_at=null - fi - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"%s","conclusion":%s,"completed_at":%s,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' "$status" "$conclusion" "$completed_at" - ;; - pending-gate-discovery-throttle) - if [[ "$count" -le 5 ]]; then - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - cache-metadata-across-polls) - if [[ "$count" -eq 1 ]]; then - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"success","completed_at":"2026-07-30T03:00:00Z","started_at":"2026-07-30T02:00:00Z","created_at":"2026-07-30T02:00:00Z"}]}]\n' - fi - ;; - pending-missing-step-with-failed-substantive) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"in_progress","conclusion":null,"completed_at":null,"started_at":"2026-07-30T02:00:00Z","created_at":"2026-07-30T02:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"failure","completed_at":"2026-07-30T03:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - timeout-pending|unverified-pending-gate) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"waiting","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - failure-retry) - case "${GH_FAILURE_MODE:-transient}" in - transient|network) - if [[ "$count" -eq 1 ]]; then - if [[ "${GH_FAILURE_MODE}" == "network" ]]; then - echo "gh: error connecting to api.github.com" >&2 - else - echo "gh: HTTP 503 Service Unavailable" >&2 - fi - exit 1 - fi - ;; - rate-limit) - if [[ "$count" -eq 1 ]]; then - echo "gh: HTTP 403 API rate limit exceeded" >&2 - exit 1 - fi - ;; - permanent) - echo "gh: HTTP 422 Unprocessable Entity" >&2 - exit 1 - ;; - permission) - echo "gh: HTTP 403 Resource not accessible by integration; SSO authorization required" >&2 - exit 1 - ;; - *) - echo "unknown simulated gh failure mode" >&2 - exit 91 - ;; - esac - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - job-failure-retry) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - *) - echo "unknown simulated gh scenario" >&2 - exit 91 - ;; -esac -EOF -cat >"$tmp_dir/sleep" <<'EOF' -#!/usr/bin/env bash -echo "one-pass assessment must never sleep" >&2 -exit 97 -EOF -chmod +x "$tmp_dir/gh" "$tmp_dir/sleep" - -action_script="$(<"$ASSESS_SCRIPT")" -# shellcheck disable=SC2016 # Reject literal GitHub expressions in shell. -if grep -Fq '${{' <<<"$action_script"; then - echo "assessment must receive workflow context through env" >&2; exit 1 -fi -if grep -Eq 'PRESERVATION_MODE|poll_deadline|sleep_until_poll_deadline|find_active_substantive_workflow' <<<"$action_script"; then - echo "assessment must not retain a polling mode or discovery loop" >&2; exit 1 -fi -run_action() { - local count_file="$1" - local failure_mode="$2" - local scenario="${3:-failure-retry}" - local call_count_dir="${4:-}" - # Fixture outputs must never inherit the enclosing Actions step output file. - local assessment_output="${5:-$count_file-output}" - GITHUB_OUTPUT="$assessment_output" \ - GH_RETRY_COUNT_FILE="$count_file" \ - GH_FAILURE_MODE="$failure_mode" \ - GH_SCENARIO="$scenario" \ - GH_CALL_COUNT_DIR="$call_count_dir" \ - PATH="$tmp_dir:$PATH" \ - GITHUB_EVENT_NAME=pull_request \ - GITHUB_REPOSITORY=example/firemud \ - GITHUB_RUN_ID=999 \ - GH_TOKEN=test-token \ - BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb \ - HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - PR_NUMBER=123 \ - REQUIRED_GATE_NAME='Validation Gate' \ - EXPECTED_WORKFLOW_NAME='CI — Validation' \ - EXPECTED_WORKFLOW_FILE=ci.yml \ - EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml \ - bash "$ASSESS_SCRIPT" -} - -# Incomplete or inconsistent successful API responses cannot manufacture proof. -coverage_mode=assess -for coverage_case in truncated missing-total malformed-total overcount invalid-id empty-pages duplicate inconsistent-total; do - coverage_scenario="check-coverage-$coverage_case" - coverage_count="$tmp_dir/$coverage_mode-$coverage_scenario-count" - coverage_output="$tmp_dir/$coverage_mode-$coverage_scenario-output" - coverage_log="$tmp_dir/$coverage_mode-$coverage_scenario-log" - if run_action "$coverage_count" none "$coverage_scenario" "" "$coverage_output" >"$coverage_log" 2>&1; then - echo "required-gate $coverage_mode accepted invalid check coverage: $coverage_case" >&2 - exit 1 - fi - [[ "$(<"$coverage_count")" == 1 && ! -s "$coverage_output" ]] || { - echo "invalid check coverage was retried or emitted an assessment: $coverage_case" >&2 - exit 1 - } - grep -Fq 'malformed or incomplete check-run data' "$coverage_log" || { - echo "invalid check coverage did not fail at the coverage boundary: $coverage_case" >&2 - exit 1 - } -done -coverage_output="$tmp_dir/$coverage_mode-complete-multi-output" -run_action "$tmp_dir/$coverage_mode-complete-multi-count" none check-coverage-multi "" "$coverage_output" -[[ "$(<"$coverage_output")" == assessment=success ]] || { - echo "complete multi-page check coverage lost successful proof" >&2 - exit 1 -} - -attempt_fallback_output="$tmp_dir/attempt-fallback-success-output" -if ! run_action "$tmp_dir/attempt-fallback-success-count" none attempt-fallback-success "" "$attempt_fallback_output" >"$tmp_dir/attempt-fallback-success-log" 2>&1; then - cat "$tmp_dir/attempt-fallback-success-log" >&2 - echo "complete exact-attempt job snapshot did not recover the ordinary skipped preservation step" >&2 - exit 1 -fi -[[ "$(<"$attempt_fallback_output")" == assessment=success ]] || { - echo "complete exact-attempt job snapshot did not recover the ordinary skipped preservation step" >&2 - exit 1 -} -attempt_two_output="$tmp_dir/attempt-fallback-attempt-two-output" -attempt_two_calls="$tmp_dir/attempt-fallback-attempt-two-calls" -REQUIRED_GATE_INCLUDE_SOURCE=true run_action "$tmp_dir/attempt-fallback-attempt-two-count" none \ - attempt-fallback-attempt-two "$attempt_two_calls" "$attempt_two_output" -[[ "$(<"$attempt_two_output")" == $'source_run_id=100\nsource_job_id=100\nsource_check_run_id=100\nsource_run_attempt=2\nassessment=success' ]] || { - echo "successful exact-attempt recovery did not preserve attempt-2 source provenance" >&2 - exit 1 -} -python3 - "$attempt_two_calls/attempt-endpoints" <<'PY_ATTEMPT_TWO' -from pathlib import Path -import sys -endpoints = Path(sys.argv[1]).read_text().splitlines() -assert any(path.endswith("/actions/runs/100/attempts/2") for path in endpoints), endpoints -assert not any("/attempts/1" in path for path in endpoints), endpoints -PY_ATTEMPT_TWO -for scenario in attempt-fallback-attempt-two-mismatch attempt-fallback-attempt-two-api-error; do - output_file="$tmp_dir/$scenario-output" - call_dir="$tmp_dir/$scenario-calls" - if run_action "$tmp_dir/$scenario-count" none "$scenario" "$call_dir" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then - echo "unbound exact-attempt source was accepted: $scenario" >&2; exit 1 - fi - [[ ! -s "$output_file" ]] || { echo "invalid exact-attempt source emitted proof: $scenario" >&2; exit 1; } - if [[ "$scenario" == *api-error ]]; then - grep -Fq 'GitHub API error while reading exact-attempt workflow run.' "$tmp_dir/$scenario-log" || { - echo "exact-attempt API failure lost its distinct diagnostic" >&2; exit 1; - } - else - grep -Fq 'Malformed or unbound exact-attempt evidence:' "$tmp_dir/$scenario-log" || { - echo "mismatched attempt identity lost its evidence diagnostic" >&2; exit 1; - } - fi - ! grep -Fq 'test-token' "$tmp_dir/$scenario-log" || { - echo "exact-attempt diagnostic exposed credentials" >&2; exit 1; - } - python3 - "$call_dir/attempt-endpoints" <<'PY_ATTEMPT_FAILURE' -from pathlib import Path -import sys -endpoints = Path(sys.argv[1]).read_text().splitlines() -assert len(endpoints) == 1 and endpoints[0].endswith("/actions/runs/100/attempts/2"), endpoints -PY_ATTEMPT_FAILURE -done -attempt_recovery_limit_calls="$tmp_dir/attempt-fallback-recovery-limit-calls" -if run_action "$tmp_dir/attempt-fallback-recovery-limit-count" none attempt-fallback-recovery-limit \ - "$attempt_recovery_limit_calls" "$tmp_dir/attempt-fallback-recovery-limit-output" \ - >"$tmp_dir/attempt-fallback-recovery-limit-log" 2>&1; then - echo "historical sparse-candidate recovery exceeded its fixed budget" >&2; exit 1 -fi -[[ ! -s "$tmp_dir/attempt-fallback-recovery-limit-output" ]] || { - echo "recovery-budget exhaustion emitted proof" >&2; exit 1; -} -grep -Fq 'exhausted its 3-snapshot budget' "$tmp_dir/attempt-fallback-recovery-limit-log" || { - echo "historical sparse-candidate exhaustion lost its explicit fail-closed diagnostic" >&2; exit 1; -} -python3 - "$attempt_recovery_limit_calls" <<'PY_RECOVERY_LIMIT' -from pathlib import Path -import sys -calls = list(Path(sys.argv[1]).glob("attempt-jobs-*")) -assert len(calls) == 3, calls -assert all(path.read_text() == "1" for path in calls), calls -candidate_jobs = Path(sys.argv[1], "candidate-direct-jobs").read_text().splitlines() -assert [path.rsplit("/", 1)[1] for path in candidate_jobs] == ["100", "101", "102", "103"], candidate_jobs -PY_RECOVERY_LIMIT -attempt_fallback_known_output="$tmp_dir/attempt-fallback-known-skipped-output" -run_action "$tmp_dir/attempt-fallback-known-skipped-count" none attempt-fallback-known-skipped "" "$attempt_fallback_known_output" -[[ "$(<"$attempt_fallback_known_output")" == assessment=success ]] || { - echo "known skipped preservation with sparse unrelated step metadata lost the ordinary assessment path" >&2 - exit 1 -} -attempt_fallback_metadata_output="$tmp_dir/attempt-fallback-metadata-output" -run_action "$tmp_dir/attempt-fallback-metadata-count" none attempt-fallback-metadata "" "$attempt_fallback_metadata_output" -[[ "$(<"$attempt_fallback_metadata_output")" == assessment=dependency-deferred ]] || { - echo "complete exact-attempt metadata preservation was treated as substantive proof" >&2 - exit 1 -} -attempt_fallback_failure_output="$tmp_dir/attempt-fallback-newer-failure-output" -if run_action "$tmp_dir/attempt-fallback-newer-failure-count" none attempt-fallback-newer-failure "" "$attempt_fallback_failure_output" >"$tmp_dir/attempt-fallback-newer-failure-log" 2>&1; then - echo "complete exact-attempt fallback allowed newer substantive failure over older success" >&2 - exit 1 -fi -[[ ! -s "$attempt_fallback_failure_output" ]] || { - echo "newer exact-attempt failure emitted successful proof" >&2 - exit 1 -} -for scenario in attempt-fallback-empty attempt-fallback-no-steps attempt-fallback-duplicate attempt-fallback-malformed attempt-fallback-oversized attempt-fallback-incomplete attempt-fallback-stale-tuple attempt-fallback-wrong-attempt attempt-fallback-wrong-head attempt-fallback-wrong-workflow attempt-fallback-wrong-app attempt-fallback-wrong-check-url attempt-fallback-wrong-check-details attempt-fallback-duplicate-direct attempt-fallback-malformed-direct; do - output_file="$tmp_dir/$scenario-output" - if run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then - echo "exact-attempt fallback accepted missing or unbound gate evidence: $scenario" >&2 - exit 1 - fi - [[ ! -s "$output_file" ]] || { echo "invalid exact-attempt fallback emitted proof: $scenario" >&2; exit 1; } -done - -# API uncertainty is an error, never dependency deferral or a retry. -for failure_mode in transient network rate-limit permanent permission; do - count_file="$tmp_dir/failure-$failure_mode" - output_file="$tmp_dir/failure-output-$failure_mode" - if run_action "$count_file" "$failure_mode" failure-retry >"$output_file" 2>&1; then - echo "assessment accepted an API failure: $failure_mode" >&2; exit 1 - fi - [[ "$(<"$count_file")" == 1 && ! -s "$count_file-output" ]] || { - echo "API failure was retried or deferred: $failure_mode" >&2; exit 1; - } -done - -for scenario in no-local-workflow-file latest-pending-preferred missing-created-at self-run-excluded fork-head-same-sha fork-empty-association dynamic-run-name dynamic-run-name-fork-empty run-path-ref-suffix run-path-ref-suffix-plus run-path-ref-suffix-at details-url-query details-url-fragment valid-new-tuple stale-then-current-tuple completed-cancelled-missing-step completed-skipped-missing-step completed-stale-missing-step; do - count_file="$tmp_dir/success-$scenario" - run_action "$count_file" none "$scenario" - [[ "$(<"$count_file")" == 1 && "$(<"$count_file-output")" == assessment=success ]] || { - echo "one assessment lost valid original proof: $scenario" >&2; exit 1; - } -done - -for scenario in no-prior pending-predecessor queued-null-started-at multiple-metadata delayed-predecessor delayed-predecessor-after-19-minutes active-workflow-delayed-gate active-workflow-late-arrival active-workflow-wrong-base active-workflow-metadata-only active-workflow-mismatched-tuple alternate-pending pending-preservation-step-not-concluded pending-gate-discovery-throttle timeout-pending unverified-pending-gate populated-wrong-base populated-wrong-head cache-metadata-across-polls; do - count_file="$tmp_dir/deferred-$scenario" - run_action "$count_file" none "$scenario" - [[ "$(<"$count_file")" == 1 && "$(<"$count_file-output")" == assessment=dependency-deferred ]] || { - echo "one assessment did not defer unresolved original proof: $scenario" >&2; exit 1; - } -done - -for scenario in job-failure-retry completed-preservation-step-lag completed-preservation-step-persistent-lag pending-missing-step-with-failed-substantive failed-predecessor newer-failure-over-success same-timestamp-newer-failure duplicate-invalid-run-identity cross-workflow-same-name malformed-run-path-ref-suffix malformed-details-url-suffix wrong-run-repository wrong-run-name wrong-job-workflow-name unknown-app unknown-check-name invalid-job-id missing-job-id unsupported-status missing-timestamp empty-wrong-pr empty-wrong-base empty-wrong-head empty-wrong-title empty-malformed-association other-pr-association; do - count_file="$tmp_dir/rejected-$scenario" - if run_action "$count_file" none "$scenario" >"$tmp_dir/rejected-log-$scenario" 2>&1; then - echo "assessment accepted invalid or unavailable evidence: $scenario" >&2; exit 1 - fi - [[ "$(<"$count_file")" == 1 && ! -s "$count_file-output" ]] || { - echo "invalid evidence was retried or deferred: $scenario" >&2; exit 1; - } -done -# Cancellation cannot become success: only the exact pre-execution shape is -# removed from authoritative failures, leaving existing missing/pending proof. -for scenario in cancellation-only cancellation-dev-tool-only cancellation-pending cancellation-metadata cancellation-later-attempt; do - output_file="$tmp_dir/$scenario-output" - run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" - [[ "$(<"$output_file")" == assessment=dependency-deferred ]] || { - echo "cancellation lost missing-proof behavior: $scenario" >&2; exit 1; - } -done -for scenario in cancellation-dev-tool-missing-sibling cancellation-dev-tool-duplicate-marker cancellation-dev-tool-wrong-name cancellation-dev-tool-duplicate-name cancellation-dev-tool-missing-original cancellation-dev-tool-missing-other cancellation-dev-tool-extra-name cancellation-dev-tool-real-failure cancellation-dev-tool-executed cancellation-dev-tool-skipped cancellation-pre-world-shape cancellation-world-missing-partition cancellation-world-aggregate-executed cancellation-world-aggregate-failed cancellation-old-shape cancellation-partial-new-shape cancellation-later-attempt-failed-source cancellation-real-failure cancellation-hidden-step-failure cancellation-executed-check cancellation-aggregate-executed cancellation-aggregate-failed cancellation-game-session-aggregate-executed cancellation-game-session-aggregate-failed cancellation-gate-other-failure cancellation-unknown-assertion cancellation-timed-out cancellation-action-required cancellation-partial cancellation-wrong-attempt cancellation-wrong-head cancellation-duplicate cancellation-missing-steps cancellation-wrong-app cancellation-check-conflict cancellation-run-conflict; do - output_file="$tmp_dir/$scenario-output" - if run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then - echo "cancellation suppressed failed or incomplete proof: $scenario" >&2; exit 1 - fi - [[ ! -s "$output_file" ]] || { echo "invalid cancellation emitted proof: $scenario" >&2; exit 1; } -done -run_action "$tmp_dir/cancellation-older-count" none cancellation-older-success -[[ "$(<"$tmp_dir/cancellation-older-count-output")" == assessment=success ]] || { - echo "cancellation changed older valid original policy" >&2; exit 1; -} -run_action "$tmp_dir/cancellation-recovery-count" none cancellation-recovery -[[ "$(<"$tmp_dir/cancellation-recovery-count-output")" == assessment=dependency-deferred ]] || exit 1 -GH_CANCELLATION_RECOVERED=true run_action "$tmp_dir/cancellation-recovered-count" none cancellation-recovery -[[ "$(<"$tmp_dir/cancellation-recovered-count-output")" == assessment=success ]] || { - echo "replacement completion did not recover canonical assessment" >&2; exit 1; -} - -if run_action "$tmp_dir/initial-identity-count" none workflow-identity-mismatch >"$tmp_dir/initial-identity-log" 2>&1; then - echo "assessment accepted an initial workflow identity mismatch" >&2; exit 1 -fi -[[ ! -e "$tmp_dir/initial-identity-count" ]] || { - echo "assessment queried checks before verifying workflow identity" >&2; exit 1; -} -for guard in event head output; do - count_file="$tmp_dir/guard-count-$guard" - if ( - export GITHUB_EVENT_NAME=pull_request GITHUB_REPOSITORY=example/firemud GITHUB_RUN_ID=999 GH_TOKEN=test-token - export BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa PR_NUMBER=123 - export REQUIRED_GATE_NAME='Validation Gate' EXPECTED_WORKFLOW_NAME='CI — Validation' EXPECTED_WORKFLOW_FILE=ci.yml EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml - export GITHUB_OUTPUT="$tmp_dir/guard-output-$guard" GH_RETRY_COUNT_FILE="$count_file" GH_SCENARIO=no-local-workflow-file GH_FAILURE_MODE=none - case "$guard" in event) export GITHUB_EVENT_NAME=push ;; head) export HEAD_SHA=' ' ;; output) unset GITHUB_OUTPUT ;; esac - PATH="$tmp_dir:$PATH" bash "$ASSESS_SCRIPT" - ) >"$tmp_dir/guard-log-$guard" 2>&1; then - echo "assessment accepted invalid $guard context" >&2; exit 1 - fi - [[ ! -s "$tmp_dir/guard-output-$guard" ]] || { echo "invalid context emitted an assessment" >&2; exit 1; } - if [[ "$guard" != output && -e "$count_file" ]]; then - echo "assessment queried checks before rejecting $guard context" >&2; exit 1 - fi -done - -RESOLVER="$ROOT_DIR/.github/actions/preserve-required-gate/resolve-deferred-gate.sh" -python3 - "$ROOT_DIR" <<'PY' -from pathlib import Path -import sys -import yaml - -root = Path(sys.argv[1]) -workflow = yaml.load((root / ".github/workflows/resolve-required-gates.yml").read_text(), Loader=yaml.BaseLoader) -action = yaml.load((root / ".github/actions/preserve-required-gate/action.yml").read_text(), Loader=yaml.BaseLoader) -assert "assessment-mode" not in action["inputs"] -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", -} -assert workflow["concurrency"] == { - "group": "required-gate-resolution-${{ github.event.workflow_run.workflow_id }}-${{ github.event.workflow_run.head_sha }}", - "cancel-in-progress": "false", -} -job = workflow["jobs"]["resolve"] -import copy -import json - -assert job["if"] == "${{ github.event.workflow_run.event == 'pull_request' }}" -assert "REQUIRED_GATE_PROOF_ALLOWLIST" not in (job.get("env") or {}) -assert job["permissions"] == {"contents": "read", "checks": "read", "pull-requests": "read", "actions": "write", "statuses": "write"} -checkouts = [step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@")] -assert len(checkouts) == 1 and checkouts[0]["with"] == {"ref": "${{ github.sha }}", "persist-credentials": "false"} -preflight = next(step for step in job["steps"] if step["name"] == "Preflight deferred gate resolution") -admission = next(step for step in job["steps"] if step["name"] == "Admit deferred gate reruns") -assert preflight["id"] == "preflight" and preflight["run"].endswith(" preflight") -assert admission["id"] == "admission" -assert admission["if"] == "${{ steps.preflight.outputs.eligible == 'true' }}" and admission["run"].endswith(" admit") -confirmation = job["steps"][job["steps"].index(admission) + 1] -assert confirmation["name"] == "Confirm admitted deferred gate jobs ${{ steps.admission.outputs.accepted_job_ids }}" -assert confirmation["if"] == "${{ steps.admission.outcome == 'success' }}" and confirmation["run"] == ":" -reconcile = job["steps"][-1] -assert reconcile["name"] == "Reconcile supplementary required gate status" -assert reconcile["if"] == "${{ always() }}" and reconcile["run"].endswith(" reconcile") -assert job["steps"].index(reconcile) > job["steps"].index(confirmation) -PY - -mkdir "$tmp_dir/resolver-bin" -cat >"$tmp_dir/resolver-bin/gh" <<'EOF' -#!/usr/bin/env bash -set -euo pipefail -if [[ "${GITHUB_EVENT_NAME:-}" == pull_request ]]; then - exec "${MOCK_ORIGINAL_GH:?}" "$@" -fi -python3 - "$@" <<'PY' -import json -import os -from pathlib import Path -import sys - -args = sys.argv[1:] -state_path = Path(os.environ["RESOLVER_STATE"]) -state = json.loads(state_path.read_text()) -method = args[args.index("--method") + 1] -endpoint = next(arg for arg in args if arg.startswith("/repos/")) -scenario = state["scenario"] -head, base = "a" * 40, "b" * 40 -title = f"CI — Validation pr-123 base-{base} head-{head}" -repository = "other-owner/firemud" if scenario in {"fork-empty", "bridge-fork"} else "example/firemud" -# The existing fork predecessor fixture is run 200. Keep its resolver target -# distinct so the shared selector correctly excludes only the target itself. -target_id = 300 if scenario == "fork-empty" else 200 -metadata_attempt = 2 if scenario in {"bridge-cross-attempt-two", "bridge-cross-metadata-attempt-mismatch"} else 1 -admission_scenario = scenario.startswith("admission-") or scenario == "partial-admission" or scenario.startswith("window-") -if scenario == "admission-distinct" and state.get("posts", 0): - target_id = 201 -current_id = int(os.environ["GITHUB_RUN_ID"]) -source_id = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())["workflow_run"]["id"] -queue_scenario = scenario.startswith(("queued-", "pending-")) -equal_time_scenario = queue_scenario and "-equal" in scenario -rejected_later = scenario in {"pending-callback-started", "pending-callback-malformed", "pending-callback-attempt", "pending-callback-concluded"} -result = None -exit_status = 0 -state.setdefault("calls", []).append(f"{method} {endpoint}") - -def rich_history_case(scenario, barrier, page): - # Native GET /statuses/ is a newest-first array with creator; the - # combined projection above has the same IDs but deliberately no creator. - case = scenario.removeprefix("bridge-").removeprefix("history-") - older = {**barrier, "id": 499, "created_at": "2026-10-14T00:00:00Z", - "creator": {"id": 99, "login": "foreign", "type": "User"}} - unrelated = [{**barrier, "id": 1000 + (page - 1) * 100 + index, "context": f"other-{page}-{index}", - "created_at": "2026-10-15T01:00:00Z"} for index in range(100)] - if case == "latest-owned": return [barrier, older] - if case == "latest-foreign": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"]}] - if case == "null-actor": return [{**barrier, "creator": None}] - if case == "missing-actor": return [{key: value for key, value in barrier.items() if key != "creator"}] - if case == "unknown-state": return [{**barrier, "state": "unknown"}] - if case == "page-two-owned": return unrelated if page == 1 else [barrier, older] - if case == "page-two-absent": return unrelated if page == 1 else [] - if case == "budget": return unrelated - if case == "unavailable-page": - if page == 1: return unrelated - raise RuntimeError("status page unavailable") - if case == "duplicate-page": return unrelated if page == 1 else [{**unrelated[0], "id": 1000}] - if case == "wrong-head-url": return [{**barrier, "url": barrier["url"].replace("a" * 40, "b" * 40)}] - if case == "same-second": return [barrier, {**older, "created_at": barrier["created_at"]}] - if case == "foreign-same-second": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"], "created_at": barrier["created_at"]}] - if case == "first-page-stop": - if page != 1: raise RuntimeError("older pages must not be read") - return [barrier] + unrelated[:99] - if case == "ignore-old-malformed": return [barrier, "bad"] - if case == "overfull": return unrelated + [barrier] - if case == "scalar": return "bad" - if case == "malformed-row": return ["bad"] - raise AssertionError(case) - - -def run(run_id, attempt=None): - return {"id": run_id, "workflow_id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml", - "created_at": "2026-07-30T01:00:00Z" if run_id == 100 else "2026-07-30T02:00:00Z", - "display_title": title.replace(base, "c" * 40) if scenario.startswith("bridge-cross-") and run_id == 200 else title, "head_sha": head, "head_branch": "proof-branch", - "repository": {"full_name": "example/firemud"}, "head_repository": {"full_name": repository}, - "event": "pull_request", "status": "completed", "conclusion": "cancelled" if scenario == "publisher-cancelled" and run_id == target_id else "failure" if run_id in {target_id, 200, 201} else "success", - "run_attempt": state.get("attempt", 1) if attempt is None else attempt, - "pull_requests": [] if scenario == "fork-empty" else [{"number": 123}]} - -def resolver_run(run_id): - source = source_id if run_id == current_id else 100 - status = "in_progress" if run_id == current_id else "completed" - created = "2026-07-30T03:00:00Z" if run_id == 9000 else "2026-07-30T02:59:00Z" - if queue_scenario: - source = 100 if run_id == 9000 else 200 - created = "2026-07-30T03:00:00Z" if run_id == 9000 else "2026-07-30T03:01:00Z" - if equal_time_scenario: - created = "2026-07-30T03:00:00Z" - if run_id == 9001 and current_id == 9000: - status = "pending" if scenario.startswith("pending-") else "queued" - if scenario == "chronology-before-target": - created = "2026-07-30T01:30:00Z" if run_id == 9000 else "2026-07-30T03:00:00Z" - attempt = state.get("resolver_attempt", 1) if run_id == current_id else 1 - if scenario in {"prior-rerun-skipped", "pending-callback-attempt"} and run_id == 9001: - attempt = 2 - if scenario in {"prior-queued-old", "prior-pending-old"} and run_id == 9001: - status = "pending" if scenario == "prior-pending-old" else "queued" - if scenario == "pending-callback-started" and run_id == 9001: - status = "in_progress" - if scenario == "pending-callback-malformed" and run_id == 9001: - created = None - if scenario.startswith("window-") and run_id == 9001: - created = "2026-07-30T02:00:00Z" - if admission_scenario and not scenario.startswith("window-"): - created = "2026-07-30T03:00:00Z" if run_id == 9000 else "2026-07-30T03:01:00Z" - if scenario == "cancelled-pending-rerun" and run_id == 9001: - attempt = 2 - if scenario == "cancelled-pending-unknown" and run_id == 9001: - status = "unknown" - return {"id": run_id, "workflow_id": 777, "name": "Resolve Required Gates", - "path": ".github/workflows/resolve-required-gates.yml", "event": "workflow_run", - "repository": {"full_name": "example/firemud"}, - "head_sha": "d" * 40 if scenario in {"queued-new-revision", "pending-new-revision"} and run_id == 9001 else "c" * 40, - "run_attempt": attempt, "status": status, "created_at": created, - "conclusion": None if scenario == "cancelled-pending-unknown" and run_id == 9001 else "cancelled" if scenario.startswith("cancelled-pending-") and run_id == 9001 and scenario != "cancelled-pending-unknown" else "failure" if scenario == "pending-callback-concluded" and run_id == 9001 else None if status in {"queued", "pending", "in_progress"} else "success", - "display_title": f"Resolve Required Gates workflow-42 head-{head} source-{source}"} - -if scenario.startswith("bridge-") and method == "POST": - assert endpoint == f"/repos/example/firemud/statuses/{head}", endpoint - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - state.setdefault("status_posts", []).append(fields) - state["barrier_state"] = fields["state"] - if scenario == "bridge-write-denied": - exit_status = 1 -elif scenario.startswith("bridge-") and (endpoint.endswith(f"/commits/{head}/status") or endpoint.endswith(f"/statuses/{head}")): - state["status_reads"] = state.get("status_reads", 0) + 1 - barrier = {"id": 500, "url": f"https://api.github.com/repos/example/firemud/statuses/{head}", - "created_at": "2026-10-15T00:00:00Z", "context": "Validation Gate", "state": state.get("barrier_state", "pending"), - "target_url": f"https://github.com/example/firemud/actions/runs/200/attempts/{metadata_attempt}", - "creator": {"id": 41898282, "login": "github-actions[bot]", "type": "Bot"}} - if scenario in {"bridge-foreign", "bridge-cross-foreign"}: - barrier["creator"]["id"] = 99 - elif scenario == "bridge-wrong-url": - barrier["target_url"] = "https://github.com/foreign/repo/actions/runs/200/attempts/1" - elif scenario in {"bridge-replaced", "bridge-cross-replaced"} and state["status_reads"] > 1: - barrier["id"] = 501 - elif scenario == "bridge-terminal": - barrier["state"] = "success" - rich = [] if scenario == "bridge-absent" else [barrier] - combined = {"sha": head, "total_count": len(rich), "statuses": [{key: value for key, value in row.items() if key != "creator"} for row in rich]} - assert all("creator" not in row for row in combined["statuses"]) - if endpoint.endswith("/status"): - result = [combined] # Actual combined projection deliberately omits creator. - else: - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - assert fields["per_page"] == "100" and "--paginate" not in args - page = int(fields["page"]) - state.setdefault("status_pages", []).append(page) - result = rich - if scenario.startswith("bridge-history-"): - try: - result = rich_history_case(scenario, barrier, page) - except RuntimeError: - result = None - exit_status = 1 - if scenario == "bridge-incomplete-status": - result = combined # Wrong endpoint shape must never qualify. -elif (scenario.startswith("bridge-") and "/attempts/" in endpoint and not endpoint.endswith("/jobs") and - endpoint.split("/actions/runs/")[1].split("/")[0] in {"99", "100", "101"}): - identity = int(endpoint.split("/")[-3]) - attempt = int(endpoint.rsplit("/", 1)[1]) - result = run(identity, attempt) - result["conclusion"] = "success" - if scenario == "bridge-cross-source-wrong-title": - result["display_title"] = title.replace(base, "c" * 40) -elif (scenario.startswith("bridge-") and "/actions/runs/" in endpoint and - "/attempts/" in endpoint and endpoint.endswith("/jobs") and - endpoint.split("/actions/runs/")[1].split("/")[0] in {"99", "100", "101"}): - identity = int(endpoint.split("/actions/runs/")[1].split("/")[0]) - attempt = int(endpoint.split("/attempts/")[1].split("/", 1)[0]) - row_attempt = 1 if scenario == "bridge-cross-source-attempt-mismatch" else attempt - job = {"id": identity, "run_id": identity, "run_attempt": row_attempt, "head_sha": head, - "head_branch": "proof-branch", "workflow_name": "CI — Validation", "name": "Validation Gate", - "status": "completed", "conclusion": "success", - "html_url": f"https://github.com/example/firemud/actions/runs/{identity}/job/{identity}", - "check_run_url": f"https://api.github.com/repos/example/firemud/check-runs/{identity}", - "started_at": "2026-07-30T01:00:00Z", "completed_at": "2026-07-30T01:30:00Z", - "steps": [{"name": "Preserve successful required gate on metadata-only edit", - "status": "completed", "conclusion": "skipped"}]} - if scenario == "bridge-cross-source-metadata": - job["steps"][0]["conclusion"] = "success" - if scenario == "bridge-cross-source-attempt-changed": - reads = state.get("selected_attempt_jobs_reads", 0) + 1 - state["selected_attempt_jobs_reads"] = reads - if reads > 1: - job["steps"][0]["conclusion"] = "success" - result = {"total_count": 1, "jobs": [job]} -elif scenario.startswith("bridge-") and any(endpoint.endswith(f"/actions/jobs/{identity}") for identity in (99, 100, 101)): - identity = int(endpoint.rsplit("/", 1)[1]) - result = {"id": identity, "run_id": identity, "run_attempt": 2 if scenario in {"bridge-cross-attempt-two", "bridge-cross-source-attempt-mismatch"} else 1, "head_sha": head, "name": "Validation Gate", - "status": "completed", "conclusion": "success", - "check_run_url": f"https://api.github.com/repos/example/firemud/check-runs/{identity}", - "steps": [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "skipped"}]} - if scenario == "bridge-cross-source-metadata": - result["steps"][0]["conclusion"] = "success" - if scenario in {"bridge-cross-attempt-two", "bridge-cross-source-attempt-mismatch", "bridge-cross-source-attempt-changed"}: - result["steps"] = [] - if scenario == "bridge-cross-source-null-steps": - result["steps"] = None -elif scenario.startswith("bridge-") and any(endpoint.endswith(f"/check-runs/{identity}") for identity in (99, 100, 101)): - identity = int(endpoint.rsplit("/", 1)[1]) - state["selected_check_reads"] = state.get("selected_check_reads", 0) + 1 - result = {"id": identity, "head_sha": head, "name": "Validation Gate", "status": "completed", "conclusion": "success", - "details_url": f"https://github.com/example/firemud/actions/runs/{identity}/job/{identity}", - "started_at": "2026-07-30T01:00:00Z", "completed_at": "2026-07-30T01:30:00Z", - "app": {"id": 99 if scenario == "bridge-cross-source-wrong-app" else 15368, "slug": "github-actions"}} - if scenario == "bridge-cross-source-changed" and state["selected_check_reads"] > 1: - result["conclusion"] = "failure" -elif scenario == "bridge-retry" and endpoint.endswith("/actions/runs/101"): - result = run(101) -elif scenario.startswith("bridge-") and endpoint.endswith(f"/actions/runs/200/attempts/{metadata_attempt}/jobs"): - job = {"id": 2000 + metadata_attempt - 1, "run_id": 200, "run_attempt": 1 if scenario == "bridge-cross-metadata-attempt-mismatch" else metadata_attempt, - "head_sha": head, "workflow_name": "CI — Validation", "name": "Validation Gate", "status": "completed", - "conclusion": "cancelled" if scenario == "bridge-cancelled" else "success", - "check_run_url": f"https://api.github.com/repos/example/firemud/check-runs/{3000 + metadata_attempt - 1}", - "steps": [{"name": name, "status": "completed", "conclusion": "success"} for name in - ("Preserve successful required gate on metadata-only edit", "Publish pending required gate status")]} - if scenario in {"bridge-running", "bridge-running-wrong-app", "bridge-cross-running"} and not state.get("metadata_completed"): - job.update(status="in_progress", conclusion=None) - # The acknowledged POST is visible before publication completes; the - # preservation step has not yet appeared in this native snapshot. - job["steps"] = [{"name": "Publish pending required gate status", "status": "in_progress", "conclusion": None}] - if scenario == "bridge-failed-producer": - job["steps"][1]["conclusion"] = "failure" - if scenario == "bridge-failed-preservation": - job["steps"][0]["conclusion"] = "failure" - if scenario == "bridge-no-producer": - job["steps"].pop() - result = [{"total_count": 2 if scenario == "bridge-incomplete-jobs" else 1, "jobs": [job]}] -elif scenario.startswith("bridge-") and endpoint.endswith(f"/check-runs/{3000 + metadata_attempt - 1}"): - result = {"id": 3000 + metadata_attempt - 1, "head_sha": head, "name": "Validation Gate", "status": "completed", - "conclusion": "cancelled" if scenario == "bridge-cancelled" else "success", - "app": {"id": 99 if scenario in {"bridge-wrong-app", "bridge-running-wrong-app"} else 15368, "slug": "github-actions"}} - if scenario in {"bridge-running", "bridge-running-wrong-app", "bridge-cross-running"} and not state.get("metadata_completed"): - result.update(status="in_progress", conclusion=None) -elif scenario.startswith("bridge-") and (endpoint.endswith("/actions/runs/200") or endpoint.endswith(f"/actions/runs/200/attempts/{metadata_attempt}")): - requested_attempt = metadata_attempt if "/attempts/" in endpoint else 1 - result = run(200, requested_attempt) - if scenario == "bridge-cross-metadata-attempt-mismatch" and "/attempts/" in endpoint: - result["run_attempt"] = 1 - result["conclusion"] = "cancelled" if scenario == "bridge-cancelled" else "success" - if scenario in {"bridge-running", "bridge-running-wrong-app", "bridge-cross-running"} and not state.get("metadata_completed"): - result.update(status="in_progress", conclusion=None) - if scenario == "bridge-wrong-attempt" or (scenario == "bridge-cross-earlier-attempt" and endpoint.endswith("/actions/runs/200")): - result["run_attempt"] = 2 - if scenario == "bridge-empty-association": - result["pull_requests"] = [] - if scenario == "bridge-wrong-title": - result["display_title"] = title.replace("pr-123", "pr-456") -elif method == "POST": - job_id = int(endpoint.split("/")[-2]) - assert job_id in {2000, 2001} and endpoint.endswith(f"/actions/jobs/{job_id}/rerun"), endpoint - state["posts"] = state.get("posts", 0) + 1 - state.setdefault("post_jobs", []).append(job_id) - if scenario in {"ambiguous-post", "same-id-rerun"} or (scenario == "partial-admission" and job_id == 2001): - state["ambiguous_admission"] = True - exit_status = 1 - print("simulated connection lost after admission", file=sys.stderr) - elif not admission_scenario: - state["attempt"] = 2 -elif endpoint.endswith("/actions/workflows/resolve-required-gates.yml"): - result = {"id": 777, "name": "Resolve Required Gates", "path": ".github/workflows/resolve-required-gates.yml"} -elif endpoint.endswith("/actions/runs/9000") or endpoint.endswith("/actions/runs/9001"): - result = resolver_run(int(endpoint.rsplit("/", 1)[1])) -elif endpoint.endswith("/actions/workflows/resolve-required-gates.yml/runs"): - assert "--paginate" not in args and "--slurp" not in args - assert "created=>=2026-07-30T02:00:00Z" in args and "per_page=100" in args - state["history_floor"] = "2026-07-30T02:00:00Z" - assert "head_sha=" + head not in args and not any(arg.startswith("status=") for arg in args) - page = int(next(arg.split("=", 1)[1] for arg in args if arg.startswith("page="))) - assert 1 <= page <= 10 - state.setdefault("history_pages", []).append(page) - runs = [resolver_run(9000)] - if scenario.startswith("history-") or scenario in {"window-final-admitted", "window-final-ambiguous"}: - count = 1000 if scenario == "history-ceiling" else 201 - for index in range(count - 2): - unrelated = resolver_run(10000 + index) - unrelated["display_title"] = f"Resolve Required Gates workflow-43 head-{'e' * 40} source-{10000 + index}" - runs.append(unrelated) - # A matching admission on the final page must not be skipped. - runs.append(resolver_run(9001)) - if scenario == "history-duplicate": - runs[100] = runs[1] - elif scenario == "history-missing-current": - runs[0] = runs[2].copy() - runs[0]["id"] = 20000 - elif scenario == "history-before-floor": - runs[100]["created_at"] = "2026-07-29T01:00:00Z" - elif scenario.startswith(("prior-", "cancelled-pending-", "window-")) or queue_scenario or ( - state.get("ambiguous_admission") and scenario != "same-id-rerun" - ): - runs.append(resolver_run(9001)) - if current_id == 9001 and not any(item["id"] == current_id for item in runs): - runs.append(resolver_run(current_id)) - if scenario == "window-old-source": - old = [dict(resolver_run(20000 + index), created_at="2026-07-30T01:30:00Z") for index in range(1001)] - runs.extend(old) - if scenario != "history-before-floor": - runs = [item for item in runs if item["created_at"] is None or item["created_at"] >= "2026-07-30T02:00:00Z"] - total = 1001 if scenario in {"prior-oversized", "history-overcap"} else len(runs) + (1 if scenario == "prior-incomplete" else 0) - result = {"total_count": total, "workflow_runs": runs[(page - 1) * 100:page * 100]} - if page == 2: - if scenario == "history-incomplete": - result["workflow_runs"].pop() - elif scenario == "history-missing-total": - result.pop("total_count") - elif scenario == "history-malformed-total": - result["total_count"] = str(total) - elif scenario == "history-inconsistent-total": - result["total_count"] += 1 - elif scenario == "history-malformed-page": - result["workflow_runs"] = None - elif scenario == "history-unavailable-page": - exit_status = 1 -elif endpoint.endswith("/actions/runs/9001/attempts/1/jobs") or endpoint.endswith("/actions/runs/9000/attempts/1/jobs"): - prior_id = int(endpoint.split("/")[-4]) - if queue_scenario: - assert (current_id == 9001 and prior_id == 9000) or ( - (equal_time_scenario or rejected_later) and current_id == 9000 and prior_id == 9001 - ), "strictly later waiting callback was queried as potentially admitted" - assert "--paginate" not in args and "--slurp" not in args and "per_page=20" in args - if scenario == "prior-unavailable": - exit_status = 1 - else: - conclusion = "skipped" if scenario in {"prior-noop", "prior-cancelled-between-steps", "prior-rerun-skipped"} or (scenario.startswith("history-") and scenario != "history-ambiguous-tail") else "failure" - if queue_scenario and not rejected_later: - conclusion = "success" - if scenario.startswith("window-"): - conclusion = "failure" if scenario in {"window-boundary-ambiguous", "window-final-ambiguous"} else "success" - if scenario == "prior-cancelled-admission": - conclusion = "cancelled" - steps = [{"name": "Preflight deferred gate resolution", "status": "completed", "conclusion": "success"}, - {"name": "Admit deferred gate reruns", "status": "completed", "conclusion": conclusion}] - if scenario in {"prior-missing-step", "prior-queued-old", "prior-pending-old"}: - steps.pop() - result = {"total_count": 1, "jobs": [{"id": prior_id * 10, "run_id": prior_id, "name": "Resolve deferred metadata gate", - "head_sha": resolver_run(prior_id)["head_sha"], - "status": "completed", "conclusion": "cancelled" if scenario.startswith("prior-cancelled") else "failure", - "steps": steps}]} - record = state.get("native_admissions", {}).get(str(prior_id)) - if record: - steps[-1].update(status="completed", conclusion=record["admission_conclusion"]) - steps.extend(record["confirmations"]) - elif conclusion == "success": - steps.append({"name": "Confirm admitted deferred gate jobs " + ("[2000]" if scenario in {"window-boundary-admitted", "window-final-admitted", "window-source-expiry", "window-ties"} else "[]"), "status": "completed", "conclusion": "success"}) - if scenario.startswith("cancelled-pending-"): - result = {"total_count": 0, "jobs": []} - if scenario == "cancelled-pending-nonempty": - result = {"total_count": 1, "jobs": [{"id": 90010, "run_id": prior_id, - "head_sha": resolver_run(prior_id)["head_sha"], "name": "Resolve deferred metadata gate", - "status": "completed", "conclusion": "cancelled", "steps": []}]} - elif scenario == "cancelled-pending-incomplete": - result["total_count"] = 1 - elif scenario == "cancelled-pending-malformed": - result["jobs"] = None - elif scenario == "cancelled-pending-missing": - result.pop("total_count") - elif scenario == "cancelled-pending-started": - result = {"total_count": 1, "jobs": [{"id": 90010, "run_id": prior_id, - "head_sha": resolver_run(prior_id)["head_sha"], "name": "Resolve deferred metadata gate", - "status": "in_progress", "conclusion": None, "steps": []}]} - if equal_time_scenario and current_id == 9000: - job = result["jobs"][0] - job.update(status="queued", conclusion=None, started_at=None, completed_at=None, steps=[]) - if scenario in {"queued-equal-started", "pending-equal-started"}: - job.update(status="in_progress", started_at="2026-07-30T03:00:00Z") - elif scenario in {"queued-equal-missing", "pending-equal-missing"}: - job.pop("started_at") - elif scenario in {"queued-equal-malformed", "pending-equal-malformed"}: - job["steps"] = None - elif scenario in {"queued-equal-incomplete", "pending-equal-incomplete"}: - result["total_count"] = 2 - elif scenario in {"queued-equal-wrong-job", "pending-equal-wrong-job"}: - job["run_id"] = 9002 - elif scenario == "pending-equal-started-step": - job["steps"] = [{"name": "Set up job", "status": "in_progress", "conclusion": None}] -elif endpoint.endswith("/actions/workflows/ci.yml"): - result = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith("/actions/workflows/ci.yml/runs"): - assert "--paginate" not in args and "--slurp" not in args - assert "head_sha=" + head in args and "event=pull_request" in args and "per_page=20" in args - state["source_listing_reads"] = state.get("source_listing_reads", 0) + 1 - runs = [run(100), run(200 if admission_scenario else target_id)] - if scenario in {"partial-admission", "window-ties", "window-new-target"} or (scenario == "admission-distinct" and state.get("posts", 0)): - runs.append(run(201)) - if scenario == "window-source-expiry": - runs = [run(200)] - total_count = 21 if scenario == "source-oversized" else len(runs) - if scenario == "source-transient-row-count" and state["source_listing_reads"] == 1: - total_count += 1 - elif scenario == "source-third-read-complete" and state["source_listing_reads"] <= 2: - total_count += 1 - elif scenario == "source-incomplete-then-malformed": - if state["source_listing_reads"] == 1: - total_count += 1 - else: - runs = ["bad"] - total_count = 1 - elif scenario == "source-transient-missing-source" and state["source_listing_reads"] == 1: - runs = [run(200)] - total_count = len(runs) - elif scenario == "source-empty-then-complete" and state["source_listing_reads"] == 1: - runs = [] - total_count = 0 - elif scenario == "source-persistent-incomplete": - total_count += 1 - elif scenario == "source-empty-persistent": - runs = [] - total_count = 0 - elif scenario == "source-malformed-schema": - runs[0].pop("created_at") - elif scenario == "source-identity-mismatch": - runs[0]["head_sha"] = "f" * 40 - elif scenario == "source-malformed-row": - runs = ["bad"] - total_count = 1 - elif scenario == "source-malformed-repository": - runs[0]["repository"] = "bad" - result = {"total_count": total_count, "workflow_runs": runs} - if scenario == "source-scalar-response": - result = "bad" - elif scenario == "source-array-response": - result = [] -elif endpoint.endswith("/pulls/123"): - state["pr_reads"] = state.get("pr_reads", 0) + 1 - result = {"number": 123, "state": "open", "base": {"sha": base, "ref": "develop", "repo": {"full_name": "example/firemud"}}, - "head": {"sha": "c" * 40 if scenario == "stale-pr" or (scenario == "bridge-pr-changed" and state["pr_reads"] > 1) else head, "ref": "proof-branch", "repo": {"full_name": repository}}} - if scenario == "bridge-cross-obsolete": - result["base"]["sha"] = "c" * 40 - if state["pr_reads"] >= 2 and scenario == "fresh-base-branch": - result["base"]["ref"] = "main" - elif state["pr_reads"] >= 2 and scenario == "fresh-head-repository": - result["head"]["repo"]["full_name"] = "other-owner/firemud" -elif endpoint.endswith(f"/actions/runs/{target_id}/attempts/1/jobs") or (admission_scenario and any(endpoint.endswith(f"/actions/runs/{run_id}/attempts/1/jobs") for run_id in (200, 201))): - requested_target = int(endpoint.split("/")[-4]) - assert "--paginate" in args and "--slurp" in args - steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "success"}] - if scenario.startswith("publisher-"): - if scenario == "publisher-unassessed": - steps[0]["conclusion"] = "failure" - steps.append({"name": "Publish pending required gate status", "status": "completed", - "conclusion": "cancelled" if scenario == "publisher-cancelled" else "skipped" if scenario == "publisher-unassessed" else "failure"}) - if scenario != "ordinary-failure": - steps.append({"name": "Report dependency-deferred required gate", "status": "completed", - "conclusion": "skipped" if scenario == "publisher-cancelled" else "failure"}) - result = [{"total_count": 1, "jobs": [{"id": 2001 if requested_target == 201 else 2000, "run_id": requested_target, "head_sha": head, "status": "completed", "conclusion": "failure", - "name": "Validation Gate", "steps": steps}]}] - if scenario == "publisher-cancelled": - result[0]["jobs"][0]["conclusion"] = "cancelled" - if scenario.startswith("target-jobs-"): - gate = result[0]["jobs"][0] - if scenario == "target-jobs-truncated": - # A second gate job is omitted, so uniqueness is unproved. - result[0]["total_count"] = 2 - elif scenario == "target-jobs-missing-total": - result[0].pop("total_count") - elif scenario == "target-jobs-malformed-total": - result[0]["total_count"] = "1" - elif scenario == "target-jobs-overcount": - result[0]["total_count"] = 0 - elif scenario == "target-jobs-invalid-id": - gate["id"] = "2000" - elif scenario == "target-jobs-empty-pages": - result = [] - elif scenario == "target-jobs-zero": - result = [{"total_count": 0, "jobs": []}] - elif scenario == "target-jobs-duplicate": - result = [{"total_count": 2, "jobs": [gate]}, {"total_count": 2, "jobs": [gate]}] - elif scenario in {"target-jobs-multi", "target-jobs-inconsistent-total"}: - other = dict(gate, id=2002, name="Other job") - result = [{"total_count": 2, "jobs": [other]}, - {"total_count": 3 if scenario.endswith("inconsistent-total") else 2, "jobs": [gate]}] - else: - raise AssertionError(scenario) -elif endpoint.endswith(f"/actions/runs/{target_id}") or (admission_scenario and any(endpoint.endswith(f"/actions/runs/{run_id}") for run_id in (200, 201))): - requested_target = int(endpoint.rsplit("/", 1)[1]) - state["target_reads"] = state.get("target_reads", 0) + 1 - state.setdefault("target_reads_by_id", {})[str(requested_target)] = state.get("target_reads_by_id", {}).get(str(requested_target), 0) + 1 - result = run(requested_target) - if scenario == "window-new-target" and requested_target == 201 and not state.get("history_pages"): - result["status"] = "queued" - if scenario == "chronology-missing-created": - result.pop("created_at") - elif scenario == "chronology-invalid-created": - result["created_at"] = "not-a-timestamp" - elif scenario == "chronology-fresh-created" and state["target_reads"] >= 2: - result["created_at"] = "2026-07-30T03:01:00Z" - elif scenario == "consumed": - result["run_attempt"] = 2 - elif scenario == "fresh-changed" and state["target_reads"] >= 2: - result["status"] = "queued" - elif scenario == "wrong-tuple": - result["display_title"] = title.replace(base, "c" * 40) - elif scenario == "wrong-association": - result["pull_requests"] = [{"number": 456}] - elif scenario == "malformed-path": - result["path"] += "@" -elif endpoint.endswith("/actions/runs/100"): - result = run(100) -else: - raise AssertionError(endpoint) -state_path.write_text(json.dumps(state)) -if result is not None: - print(json.dumps(result)) -sys.exit(exit_status) -PY -EOF -chmod +x "$tmp_dir/resolver-bin/gh" -cat >"$tmp_dir/resolver-bin/sleep" <<'EOF' -#!/usr/bin/env python3 -import json -import os -from pathlib import Path -import sys -state_path = Path(os.environ["RESOLVER_STATE"]) -state = json.loads(state_path.read_text()) -state.setdefault("source_listing_waits", []).append(int(sys.argv[1])) -state_path.write_text(json.dumps(state)) -EOF -chmod +x "$tmp_dir/resolver-bin/sleep" - -run_resolver() { - local scenario="$1" source_id="${2:-100}" original_scenario="${3:-no-local-workflow-file}" - local phase="${4:-admit}" - local resolver_id="${5:-9000}" - local event_file="$tmp_dir/resolver-event-$scenario" - local result_status=0 - : >"$tmp_dir/resolver-output-$scenario" - printf '{"action":"completed","workflow_run":{"id":%s,"workflow_id":42,"head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","event":"pull_request"}}\n' \ - "$source_id" >"$event_file" - PATH="$tmp_dir/resolver-bin:$PATH" MOCK_ORIGINAL_GH="$tmp_dir/gh" \ - RESOLVER_STATE="$tmp_dir/resolver-state-$scenario" \ - GITHUB_EVENT_NAME=workflow_run GITHUB_EVENT_PATH="$event_file" GITHUB_RUN_ID="$resolver_id" \ - GITHUB_OUTPUT="$tmp_dir/resolver-output-$scenario" \ - GITHUB_REPOSITORY=example/firemud GH_TOKEN=test-token \ - GH_RETRY_COUNT_FILE="$tmp_dir/resolver-proof-count-$scenario" \ - GH_CALL_COUNT_DIR="$tmp_dir/resolver-proof-calls-$scenario" GH_SCENARIO="$original_scenario" \ - GH_FAILURE_MODE=none bash "$RESOLVER" "$phase" >"$tmp_dir/resolver-log-$scenario" 2>&1 || result_status=$? - if [[ "$phase" == admit ]]; then - python3 - "$tmp_dir/resolver-state-$scenario" "$tmp_dir/resolver-output-$scenario" "$resolver_id" "$result_status" <<'PY' -import json -from pathlib import Path -import sys -state_path, output_path = map(Path, sys.argv[1:3]) -run_id, result = sys.argv[3], int(sys.argv[4]) -state = json.loads(state_path.read_text()) -outputs = dict(line.split("=", 1) for line in output_path.read_text().splitlines()) -encoded_ids = outputs.get("accepted_job_ids", "") -confirmations = [] -if result == 0: - # Emulate the following native confirmation step from the actual output. - json.loads(encoded_ids) - confirmation = {"name": "Confirm admitted deferred gate jobs " + encoded_ids, - "status": "completed", "conclusion": "success"} - scenario = state["scenario"] - if scenario == "admission-marker-failed": - confirmation["conclusion"] = "failure" - elif scenario == "admission-marker-cancelled": - confirmation["conclusion"] = "cancelled" - elif scenario == "admission-marker-incomplete": - confirmation.update(status="in_progress", conclusion=None) - elif scenario == "admission-marker-malformed": - confirmation["name"] = "Confirm admitted deferred gate jobs not-json" - elif scenario == "admission-marker-duplicate-ids": - confirmation["name"] = "Confirm admitted deferred gate jobs [2000,2000]" - elif scenario == "admission-marker-string-id": - confirmation["name"] = 'Confirm admitted deferred gate jobs ["2000"]' - elif scenario == "admission-marker-oversized": - confirmation["name"] = "Confirm admitted deferred gate jobs " + json.dumps(list(range(1, 22)), separators=(",", ":")) - confirmations.append(confirmation) - if scenario == "admission-marker-missing": - confirmations = [] - elif scenario == "admission-marker-duplicate-step": - confirmations.append(confirmation.copy()) -else: - assert "accepted_job_ids" not in outputs, "uncertain admission published acknowledged IDs" -state.setdefault("native_admissions", {})[run_id] = { - "admission_conclusion": "success" if result == 0 else "failure", "confirmations": confirmations, -} -state_path.write_text(json.dumps(state)) -PY - fi - return "$result_status" -} -# Source completion can arrive after publication but before metadata completes. -printf '{"scenario":"bridge-running"}\n' >"$tmp_dir/resolver-state-bridge-running" -run_resolver bridge-running 100 pending-predecessor reconcile -python3 - "$tmp_dir/resolver-state-bridge-running" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -path = Path(sys.argv[1]) -state = json.loads(path.read_text()) -assert not state.get("status_posts"), state -state["metadata_completed"] = True -path.write_text(json.dumps(state)) -PY_BRIDGE -run_resolver bridge-running 200 no-local-workflow-file reconcile -python3 - "$tmp_dir/resolver-state-bridge-running" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert len(state.get("status_posts", [])) == 1 and state["status_posts"][0]["state"] == "success", state -PY_BRIDGE - -# A cancellation-only original leaves the owned barrier pending; the existing -# independently verified successful replacement callback can later settle it. -printf '{"scenario":"bridge-retry"}\n' >"$tmp_dir/resolver-state-bridge-retry" -run_resolver bridge-retry 100 cancellation-pending reconcile -[[ "$(jq '.status_posts // [] | length' "$tmp_dir/resolver-state-bridge-retry")" == 0 ]] || exit 1 -run_resolver bridge-retry 101 retry-success reconcile -[[ "$(jq -c '[.status_posts[].state]' "$tmp_dir/resolver-state-bridge-retry")" == '["success"]' ]] || { - echo "cancelled original did not recover through existing callback" >&2; exit 1; -} - -# Support is dormant until a producer publishes the exact recognizable barrier. -for scenario in bridge-success bridge-failed-producer bridge-failed-preservation bridge-empty-association bridge-fork bridge-pending bridge-failed bridge-cancelled bridge-replaced bridge-pr-changed bridge-foreign bridge-wrong-url bridge-terminal bridge-absent; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - original=no-local-workflow-file - [[ "$scenario" != bridge-pending ]] || original=pending-predecessor - [[ "$scenario" != bridge-failed ]] || original=failed-predecessor - # Both substantive-first and metadata-first callbacks use the same target. - source_id=100 - [[ "$scenario" != bridge-empty-association ]] || source_id=200 - run_resolver "$scenario" "$source_id" "$original" reconcile - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -scenario = sys.argv[2] -posts = state.get("status_posts", []) -expected = "success" if scenario in {"bridge-success", "bridge-failed-producer", "bridge-failed-preservation", "bridge-empty-association", "bridge-fork", "bridge-cancelled"} else "failure" if scenario in {"bridge-failed"} else None -assert len(posts) == (1 if expected else 0), state -if expected: - assert posts[0]["state"] == expected, state -assert not state.get("posts"), "bridge entered legacy rerun admission" -PY_BRIDGE -done -for scenario in bridge-running-wrong-app bridge-no-producer bridge-incomplete-status bridge-incomplete-jobs bridge-wrong-app bridge-wrong-attempt bridge-wrong-title bridge-cross-metadata-attempt-mismatch bridge-write-denied; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - if run_resolver "$scenario" 100 no-local-workflow-file reconcile; then - echo "unproved bridge settlement succeeded: $scenario" >&2; exit 1 - fi - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert len(state.get("status_posts", [])) == (1 if sys.argv[2] == "bridge-write-denied" else 0), state -PY_BRIDGE -done - -# Mirrors the observed Security ordering: metadata38678293269/1 published -# pending56392930570 before original38678278927 completed successfully; callback -#38678584212 executed reconciliation. Normalized identities below must now recover -# using rich creator evidence, while combined records omit that evidence. -for history_case in latest-owned latest-foreign null-actor missing-actor unknown-state page-two-owned page-two-absent budget unavailable-page duplicate-page wrong-head-url same-second foreign-same-second first-page-stop ignore-old-malformed overfull scalar malformed-row; do - scenario="bridge-history-$history_case" - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - case "$history_case" in - budget|unavailable-page|duplicate-page|wrong-head-url|overfull|scalar|malformed-row) - if run_resolver "$scenario" 100 no-local-workflow-file reconcile; then - echo "invalid rich resolver history qualified: $history_case" >&2; exit 1 - fi ;; - *) run_resolver "$scenario" 100 no-local-workflow-file reconcile ;; - esac - python3 - "$tmp_dir/resolver-state-$scenario" "$history_case" <<'PY_HISTORY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -case = sys.argv[2] -assert len(state.get("status_posts", [])) == (1 if case in {"latest-owned", "page-two-owned", "same-second", "first-page-stop", "ignore-old-malformed"} else 0), state -assert not any("/commits/" in call and call.endswith("/status") for call in state["calls"]), state -if case.startswith("page-two-"): assert 2 in state["status_pages"], state -if case == "first-page-stop": assert all(page == 1 for page in state["status_pages"]), state -if case == "budget": assert state["status_pages"] == list(range(1, 11)), state -PY_HISTORY -done - -# Same-head base advancement uses historical ownership and CURRENT proof. -for scenario in bridge-cross-success bridge-cross-attempt-two bridge-cross-source-null-steps bridge-cross-running bridge-cross-earlier-attempt bridge-cross-no-proof bridge-cross-failure bridge-cross-foreign bridge-cross-replaced bridge-cross-obsolete bridge-cross-cancelled-selection; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - original=no-local-workflow-file - [[ "$scenario" != bridge-cross-no-proof ]] || original=no-prior - [[ "$scenario" != bridge-cross-failure ]] || original=failed-predecessor - [[ "$scenario" != bridge-cross-cancelled-selection ]] || original=completed-cancelled-missing-step - [[ "$scenario" != bridge-cross-attempt-two ]] || original=attempt-fallback-attempt-two - if ! run_resolver "$scenario" 100 "$original" reconcile; then - cat "$tmp_dir/resolver-log-$scenario" >&2; exit 1 - fi - # A later old-base metadata completion cannot reclaim current-base authority. - if [[ "$scenario" != bridge-cross-obsolete ]]; then - jq '.metadata_completed = true' "$tmp_dir/resolver-state-$scenario" >"$tmp_dir/recovery-state-update" - mv "$tmp_dir/recovery-state-update" "$tmp_dir/resolver-state-$scenario" - run_resolver "$scenario" 200 no-local-workflow-file reconcile - fi - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_RECOVERY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -expected = "success" if sys.argv[2] in {"bridge-cross-success", "bridge-cross-attempt-two", "bridge-cross-source-null-steps", "bridge-cross-running", "bridge-cross-earlier-attempt", "bridge-cross-cancelled-selection"} else "failure" if sys.argv[2] == "bridge-cross-failure" else None -posts = state.get("status_posts", []) -assert len(posts) == (1 if expected else 0), state -if expected: - assert posts[0]["state"] == expected, state - if sys.argv[2] == "bridge-cross-attempt-two": - assert posts[0]["target_url"].endswith("/200/attempts/2"), state - calls = state["calls"] - for path in ("/actions/runs/100/attempts/2/jobs", "/actions/runs/200/attempts/2", - "/actions/runs/200/attempts/2/jobs"): - assert any(path in call for call in calls), (path, calls) - assert sum("/actions/runs/100/attempts/2/jobs" in call for call in calls) == 2, state - assert sum("/actions/runs/200/attempts/2/jobs" in call for call in calls) == 2, state - elif sys.argv[2] == "bridge-cross-success": - assert posts[0]["target_url"].endswith("/200/attempts/1"), state - assert not any("/actions/runs/100/attempts/1/jobs" in call for call in state["calls"]), state - elif sys.argv[2] == "bridge-cross-source-null-steps": - assert posts[0]["target_url"].endswith("/200/attempts/1"), state - assert sum("/actions/runs/100/attempts/1/jobs" in call for call in state["calls"]) == 2, state - assert sum("/actions/runs/200/attempts/1/jobs" in call for call in state["calls"]) == 2, state - else: - assert posts[0]["target_url"].endswith("/200/attempts/1"), state -PY_RECOVERY -done -for scenario in bridge-cross-source-wrong-app bridge-cross-source-wrong-title bridge-cross-source-metadata bridge-cross-source-changed bridge-cross-source-attempt-mismatch bridge-cross-source-attempt-changed; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - original=no-local-workflow-file - [[ "$scenario" != bridge-cross-source-attempt-mismatch ]] || original=attempt-fallback-attempt-two - if run_resolver "$scenario" 100 "$original" reconcile; then - echo "invalid independent current-base source accepted: $scenario" >&2; exit 1 - fi - [[ "$(jq '.status_posts // [] | length' "$tmp_dir/resolver-state-$scenario")" == 0 ]] || exit 1 - if [[ "$scenario" == bridge-cross-source-attempt-changed ]]; then - [[ "$(jq '.selected_attempt_jobs_reads // 0' "$tmp_dir/resolver-state-$scenario")" == 2 ]] || { - echo "selected sparse source was not independently revalidated before publication" >&2; exit 1; - } - fi -done -printf '{"scenario":"bridge-retry"}\n' >"$tmp_dir/resolver-state-bridge-retry" -run_resolver bridge-retry 100 failed-predecessor reconcile -run_resolver bridge-retry 101 retry-success reconcile -python3 - "$tmp_dir/resolver-state-bridge-retry" <<'PY_RECOVERY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert [post["state"] for post in state["status_posts"]] == ["failure", "success"], state -PY_RECOVERY -printf '{"scenario":"bridge-retry","barrier_state":"error"}\n' >"$tmp_dir/resolver-state-bridge-retry" -run_resolver bridge-retry 101 retry-success reconcile -python3 - "$tmp_dir/resolver-state-bridge-retry" <<'PY_RECOVERY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert [post["state"] for post in state["status_posts"]] == ["success"], state -PY_RECOVERY - -resolver_posts() { - jq -r '.posts // 0' "$tmp_dir/resolver-state-$1" -} -resolver_source_listing_reads() { - jq -r '.source_listing_reads // 0' "$tmp_dir/resolver-state-$1" -} -resolver_source_listing_waits() { - jq -c '.source_listing_waits // []' "$tmp_dir/resolver-state-$1" -} -for scenario in success metadata-last metadata-first consumed fresh-changed fresh-base-branch fresh-head-repository ordinary-failure stale-pr wrong-tuple wrong-association malformed-path fork-empty ambiguous-post original-failure preflight prior-noop prior-cancelled-between-steps prior-cancelled-admission prior-ambiguous prior-unavailable prior-incomplete prior-missing-step prior-oversized source-oversized source-transient-row-count source-transient-missing-source source-empty-then-complete source-third-read-complete source-incomplete-then-malformed source-persistent-incomplete source-empty-persistent source-malformed-schema source-identity-mismatch source-malformed-row source-malformed-repository source-scalar-response source-array-response same-id-rerun prior-rerun-skipped queued-callback queued-new-revision queued-equal queued-equal-started queued-equal-missing queued-equal-malformed queued-equal-incomplete queued-equal-wrong-job prior-queued-old pending-callback pending-new-revision pending-equal pending-equal-started pending-equal-missing pending-equal-malformed pending-equal-incomplete pending-equal-wrong-job pending-equal-started-step pending-callback-started pending-callback-malformed pending-callback-attempt pending-callback-concluded prior-pending-old history-multi history-ceiling history-ambiguous-tail history-duplicate history-missing-current history-before-floor history-overcap history-incomplete history-missing-total history-malformed-total history-inconsistent-total history-malformed-page history-unavailable-page admission-delayed admission-zero admission-distinct admission-marker-failed admission-marker-cancelled admission-marker-incomplete admission-marker-missing admission-marker-malformed admission-marker-duplicate-ids admission-marker-string-id admission-marker-oversized admission-marker-duplicate-step partial-admission cancelled-pending-zero cancelled-pending-nonempty cancelled-pending-incomplete cancelled-pending-malformed cancelled-pending-missing cancelled-pending-unknown cancelled-pending-rerun cancelled-pending-started; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" -done -for target_coverage_case in truncated missing-total malformed-total overcount invalid-id empty-pages duplicate inconsistent-total zero multi; do - target_coverage_scenario="target-jobs-$target_coverage_case" - printf '{"scenario":"%s"}\n' "$target_coverage_scenario" >"$tmp_dir/resolver-state-$target_coverage_scenario" - case "$target_coverage_case" in - zero|multi) - run_resolver "$target_coverage_scenario" - expected_posts=0 - [[ "$target_coverage_case" != multi ]] || expected_posts=1 - [[ "$(resolver_posts "$target_coverage_scenario")" == "$expected_posts" ]] || { - echo "complete target job coverage selected the wrong gate: $target_coverage_case" >&2 - exit 1 - } - ;; - *) - if run_resolver "$target_coverage_scenario"; then - echo "resolver accepted invalid target job coverage: $target_coverage_case" >&2 - exit 1 - fi - [[ "$(resolver_posts "$target_coverage_scenario")" == 0 ]] || { - echo "invalid target job coverage admitted a POST: $target_coverage_case" >&2 - exit 1 - } - grep -Fq 'malformed or incomplete target jobs' "$tmp_dir/resolver-log-$target_coverage_scenario" || { - echo "invalid target job coverage did not fail at coverage validation: $target_coverage_case" >&2 - exit 1 - } - ;; - esac -done - -# A queued resolver cannot admit a target created after its own callback. -# The target's later callback remains eligible; no external receipt is needed. -for chronology_case in before-target missing-created invalid-created fresh-created; do - chronology_scenario="chronology-$chronology_case" - printf '{"scenario":"%s"}\n' "$chronology_scenario" >"$tmp_dir/resolver-state-$chronology_scenario" - run_resolver "$chronology_scenario" - [[ "$(resolver_posts "$chronology_scenario")" == 0 && "$(<"$tmp_dir/resolver-output-$chronology_scenario")" == 'accepted_job_ids=[]' ]] || { - echo "unproved target creation chronology admitted a POST: $chronology_case" >&2; exit 1; - } -done -[[ "$(jq '.target_reads' "$tmp_dir/resolver-state-chronology-fresh-created")" == 2 ]] || { - echo "target chronology was not rechecked immediately before admission" >&2; exit 1; -} -run_resolver chronology-before-target 200 no-local-workflow-file admit 9001 -[[ "$(resolver_posts chronology-before-target)" == 1 ]] || { - echo "target's later callback did not resolve a target refused by the earlier queued resolver" >&2; exit 1; -} - -# A denied or ambiguous publisher stays failed, but the non-cancelled guard -# exposes existing legacy recovery after independent original success. -for scenario in publisher-denied publisher-ambiguous publisher-cancelled publisher-unassessed; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - run_resolver "$scenario" 200 pending-predecessor - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "publisher failure bypassed pending original proof: $scenario" >&2; exit 1; } - run_resolver "$scenario" - expected_posts=1 - [[ "$scenario" != publisher-cancelled && "$scenario" != publisher-unassessed ]] || expected_posts=0 - [[ "$(resolver_posts "$scenario")" == "$expected_posts" ]] || { echo "publisher legacy recovery violated native outcome: $scenario" >&2; exit 1; } -done - -run_resolver success -run_resolver success -[[ "$(resolver_posts success)" == 1 ]] || { echo "duplicate completion replayed a targeted rerun" >&2; exit 1; } -run_resolver metadata-last 200 -[[ "$(resolver_posts metadata-last)" == 1 ]] || { echo "metadata completion after original success was not resolved" >&2; exit 1; } -run_resolver metadata-first 200 pending-predecessor -[[ "$(resolver_posts metadata-first)" == 0 ]] || { echo "pending original admitted a rerun" >&2; exit 1; } -run_resolver metadata-first 100 pending-predecessor -[[ "$(resolver_posts metadata-first)" == 1 ]] || { echo "later original completion did not resolve metadata deferral" >&2; exit 1; } -for scenario in consumed fresh-changed fresh-base-branch fresh-head-repository ordinary-failure stale-pr wrong-tuple wrong-association malformed-path; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "resolver reran rejected target: $scenario" >&2; exit 1; } -done -for scenario in source-transient-row-count source-transient-missing-source source-empty-then-complete; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 && "$(resolver_source_listing_reads "$scenario")" == 2 && - "$(resolver_source_listing_waits "$scenario")" == '[1]' ]] || { - echo "valid incomplete source listing was not reread before admission: $scenario" >&2; exit 1; - } - grep -F "Exact-head source listing is incomplete (read 1/3):" "$tmp_dir/resolver-log-$scenario" >/dev/null || { - echo "source-list retry diagnostic was missing: $scenario" >&2; exit 1; - } -done -run_resolver source-third-read-complete -[[ "$(resolver_posts source-third-read-complete)" == 1 && - "$(resolver_source_listing_reads source-third-read-complete)" == 3 && - "$(resolver_source_listing_waits source-third-read-complete)" == '[1,2]' ]] || { - echo "third-read source recovery exceeded or bypassed the read/wait budget" >&2; exit 1; -} -if run_resolver source-incomplete-then-malformed; then - echo "source listing that became malformed did not fail closed" >&2; exit 1 -fi -[[ "$(resolver_posts source-incomplete-then-malformed)" == 0 && - "$(resolver_source_listing_reads source-incomplete-then-malformed)" == 2 && - "$(resolver_source_listing_waits source-incomplete-then-malformed)" == '[1]' ]] || { - echo "source listing retried after becoming malformed" >&2; exit 1; -} -grep -F 'Exact-head source coverage rejected: classification=malformed-row, total_count=1, returned_rows=1, source_present=false, limit=20.' \ - "$tmp_dir/resolver-log-source-incomplete-then-malformed" >/dev/null || { - echo "source listing that became malformed lost its classification" >&2; exit 1; -} -for scenario in source-persistent-incomplete source-empty-persistent; do - if run_resolver "$scenario"; then - echo "persistent exact-head source undercoverage did not fail closed: $scenario" >&2; exit 1 - fi - [[ "$(resolver_posts "$scenario")" == 0 && "$(resolver_source_listing_reads "$scenario")" == 3 && - "$(resolver_source_listing_waits "$scenario")" == '[1,2]' ]] || { - echo "persistent source undercoverage exceeded or bypassed the read budget: $scenario" >&2; exit 1; - } -done -grep -F 'Exact-head source coverage remains incomplete after 3 reads: classification=incomplete-row-count, total_count=3, returned_rows=2, source_present=true, limit=20.' \ - "$tmp_dir/resolver-log-source-persistent-incomplete" >/dev/null || { - echo "persistent source undercoverage diagnostic did not report exact counts" >&2; exit 1; -} -grep -F 'Exact-head source coverage remains incomplete after 3 reads: classification=incomplete-missing-source, total_count=0, returned_rows=0, source_present=false, limit=20.' \ - "$tmp_dir/resolver-log-source-empty-persistent" >/dev/null || { - echo "persistent empty source listing was not reported as missing its event source" >&2; exit 1; -} -for scenario in source-malformed-schema source-identity-mismatch source-oversized source-malformed-row source-malformed-repository source-scalar-response source-array-response; do - if run_resolver "$scenario"; then - echo "malformed, misattributed, or over-limit source listing was accepted: $scenario" >&2; exit 1 - fi - [[ "$(resolver_posts "$scenario")" == 0 && "$(resolver_source_listing_reads "$scenario")" == 1 && - "$(resolver_source_listing_waits "$scenario")" == '[]' ]] || { - echo "malformed, misattributed, or over-limit source listing was retried or admitted: $scenario" >&2; exit 1; - } - case "$scenario" in - source-malformed-schema) expected_diagnostic='classification=malformed-created-at, total_count=2, returned_rows=2, source_present=true, limit=20.' ;; - source-identity-mismatch) expected_diagnostic='classification=identity-mismatch, total_count=2, returned_rows=2, source_present=true, limit=20.' ;; - source-oversized) expected_diagnostic='classification=overflow-total-count, total_count=21, returned_rows=2, source_present=true, limit=20.' ;; - source-malformed-row) expected_diagnostic='classification=malformed-row, total_count=1, returned_rows=1, source_present=false, limit=20.' ;; - source-malformed-repository) expected_diagnostic='classification=malformed-row-repository, total_count=2, returned_rows=2, source_present=true, limit=20.' ;; - source-scalar-response|source-array-response) expected_diagnostic='classification=malformed-response, total_count=unknown, returned_rows=unknown, source_present=false, limit=20.' ;; - esac - grep -F "Exact-head source coverage rejected: $expected_diagnostic" "$tmp_dir/resolver-log-$scenario" >/dev/null || { - echo "source-list rejection omitted its cause or bounded numeric evidence: $scenario" >&2; exit 1; - } -done -run_resolver fork-empty 100 fork-empty-association -[[ "$(resolver_posts fork-empty)" == 1 ]] || { echo "resolver lost fork/empty-association attribution" >&2; exit 1; } -if run_resolver ambiguous-post; then - echo "ambiguous rerun POST did not fail closed" >&2 - exit 1 -fi -[[ "$(resolver_posts ambiguous-post)" == 1 ]] || { echo "ambiguous POST was replayed" >&2; exit 1; } -if run_resolver ambiguous-post; then - echo "a prior ambiguous admission with a still-visible attempt 1 did not require recovery" >&2 - exit 1 -fi -[[ "$(resolver_posts ambiguous-post)" == 1 ]] || { echo "later completion replayed an ambiguous POST" >&2; exit 1; } -if run_resolver same-id-rerun; then - echo "initial ambiguous same-ID admission did not fail closed" >&2; exit 1 -fi -jq '.resolver_attempt = 2' "$tmp_dir/resolver-state-same-id-rerun" >"$tmp_dir/resolver-state-update" -mv "$tmp_dir/resolver-state-update" "$tmp_dir/resolver-state-same-id-rerun" -if run_resolver same-id-rerun; then - echo "current resolver rerun hid its ambiguous first attempt" >&2; exit 1 -fi -[[ "$(resolver_posts same-id-rerun)" == 1 ]] || { echo "same-ID resolver rerun replayed admission" >&2; exit 1; } -for scenario in queued-callback queued-new-revision queued-equal pending-callback pending-new-revision pending-equal; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "later waiting callback poisoned current resolution: $scenario" >&2; exit 1; } - run_resolver "$scenario" 200 no-local-workflow-file admit 9001 - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "successor callback repeated consumed admission: $scenario" >&2; exit 1; } -done -run_resolver preflight 100 no-local-workflow-file preflight -[[ "$(resolver_posts preflight)" == 0 && "$(<"$tmp_dir/resolver-output-preflight")" == 'eligible=true' ]] || { - echo "preflight performed admission or lost native eligibility output" >&2; exit 1; -} -for scenario in prior-noop prior-cancelled-between-steps; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "clean skipped admission blocked resolution" >&2; exit 1; } -done -for scenario in prior-ambiguous prior-cancelled-admission prior-unavailable prior-incomplete prior-missing-step prior-oversized source-oversized prior-rerun-skipped prior-queued-old queued-equal-started queued-equal-missing queued-equal-malformed queued-equal-incomplete queued-equal-wrong-job pending-equal-started pending-equal-missing pending-equal-malformed pending-equal-incomplete pending-equal-wrong-job pending-equal-started-step pending-callback-started pending-callback-malformed pending-callback-attempt pending-callback-concluded prior-pending-old history-ambiguous-tail history-duplicate history-missing-current history-before-floor history-overcap history-incomplete history-missing-total history-malformed-total history-inconsistent-total history-malformed-page history-unavailable-page; do - if run_resolver "$scenario"; then - echo "unproved prior admission did not require recovery: $scenario" >&2; exit 1 - fi - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "unproved prior admission was replayed" >&2; exit 1; } -done -for scenario in history-multi history-ceiling; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "complete resolver history did not admit once: $scenario" >&2; exit 1; } - expected_pages=3 - [[ "$scenario" != history-ceiling ]] || expected_pages=10 - jq -e --argjson pages "$expected_pages" '.history_pages == [range(1; $pages + 1)]' \ - "$tmp_dir/resolver-state-$scenario" >/dev/null || { echo "resolver history pagination was incomplete: $scenario" >&2; exit 1; } -done -for scenario in prior-oversized history-overcap; do - [[ "$(jq '.history_pages | length' "$tmp_dir/resolver-state-$scenario")" == 1 ]] || { - echo "resolver fetched more history after observing the API ceiling: $scenario" >&2; exit 1; - } -done -[[ "$(jq '[.calls[] | select(endswith("/actions/runs/9001/attempts/1/jobs"))] | length' "$tmp_dir/resolver-state-prior-rerun-skipped")" == 0 ]] || { - echo "historical rerun relied on a latest skipped snapshot over its ambiguous first attempt" >&2; exit 1; -} -run_resolver admission-delayed -[[ "$(<"$tmp_dir/resolver-output-admission-delayed")" == 'accepted_job_ids=[2000]' ]] || { - echo "acknowledged POST did not publish its exact job ID" >&2; exit 1; -} -run_resolver admission-delayed 200 no-local-workflow-file admit 9001 -[[ "$(resolver_posts admission-delayed)" == 1 && "$(<"$tmp_dir/resolver-output-admission-delayed")" == 'accepted_job_ids=[]' ]] || { - echo "confirmed admission replayed while target attempt remained one" >&2; exit 1; -} -run_resolver admission-zero 200 pending-predecessor -[[ "$(resolver_posts admission-zero)" == 0 && "$(<"$tmp_dir/resolver-output-admission-zero")" == 'accepted_job_ids=[]' ]] || { - echo "successful zero-POST admission did not publish an empty set" >&2; exit 1; -} -run_resolver admission-zero 100 no-local-workflow-file admit 9001 -[[ "$(resolver_posts admission-zero)" == 1 ]] || { echo "confirmed zero-POST no-op poisoned later admission" >&2; exit 1; } -run_resolver admission-distinct -run_resolver admission-distinct 201 no-local-workflow-file admit 9001 -jq -e '.post_jobs == [2000,2001]' "$tmp_dir/resolver-state-admission-distinct" >/dev/null || { - echo "one acknowledged job blocked a distinct eligible gate or replayed itself" >&2; exit 1; -} -[[ "$(<"$tmp_dir/resolver-output-admission-distinct")" == 'accepted_job_ids=[2001]' ]] || { - echo "admission output included a previously acknowledged job" >&2; exit 1; -} -for scenario in admission-marker-failed admission-marker-cancelled admission-marker-incomplete admission-marker-missing admission-marker-malformed admission-marker-duplicate-ids admission-marker-string-id admission-marker-oversized admission-marker-duplicate-step; do - run_resolver "$scenario" - if run_resolver "$scenario" 200 no-local-workflow-file admit 9001; then - echo "uncertain native confirmation allowed a later admission: $scenario" >&2; exit 1; - fi - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "uncertain confirmation replayed a POST: $scenario" >&2; exit 1; } -done -if run_resolver partial-admission; then - echo "partial admission did not fail closed" >&2; exit 1; -fi -if run_resolver partial-admission 200 no-local-workflow-file admit 9001; then - echo "partial admission did not require explicit recovery" >&2; exit 1; -fi -[[ "$(resolver_posts partial-admission)" == 2 ]] || { echo "partial admission replayed a POST" >&2; exit 1; } -run_resolver cancelled-pending-zero -[[ "$(resolver_posts cancelled-pending-zero)" == 1 ]] || { echo "cancelled-before-start zero-job callback blocked admission" >&2; exit 1; } -for scenario in cancelled-pending-nonempty cancelled-pending-incomplete cancelled-pending-malformed cancelled-pending-missing cancelled-pending-unknown cancelled-pending-rerun cancelled-pending-started; do - if run_resolver "$scenario"; then - echo "uncertain cancelled callback was treated as never admitted: $scenario" >&2; exit 1; - fi - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "uncertain cancelled callback admitted a POST: $scenario" >&2; exit 1; } -done -if run_resolver original-failure 100 failed-predecessor; then - echo "resolver accepted failed original proof" >&2 - exit 1 -fi -[[ "$(resolver_posts original-failure)" == 0 ]] || { echo "failed original admitted a rerun" >&2; exit 1; } - -# History starts at the earliest frozen eligible target, including ties. Old -# substantive evidence and unrelated earlier traffic do not widen that window. -for scenario in window-old-source window-boundary-admitted window-boundary-ambiguous window-final-admitted window-final-ambiguous window-source-expiry window-ties window-new-target; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - source_id=100 - [[ "$scenario" != window-source-expiry ]] || source_id=200 - if [[ "$scenario" == *ambiguous ]]; then - if run_resolver "$scenario" "$source_id"; then - echo "target-boundary ambiguous admission was ignored: $scenario" >&2; exit 1 - fi - else - run_resolver "$scenario" "$source_id" - fi - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_WINDOW' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -scenario = sys.argv[2] -assert state["history_floor"] == "2026-07-30T02:00:00Z" -expected = [2000] if scenario in {"window-old-source", "window-new-target"} else [2001] if scenario == "window-ties" else [] -assert state.get("post_jobs", []) == expected, (scenario, state) -if "final" in scenario: - assert state["history_pages"] == [1, 2, 3], state -if scenario == "window-new-target": - assert state["target_reads_by_id"]["201"] == 1, state -PY_WINDOW -done -# Ineligible or consumed targets need neither history nor recovery inference. -for scenario in ordinary-failure consumed chronology-missing-created chronology-invalid-created; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - run_resolver "$scenario" - python3 - "$tmp_dir/resolver-state-$scenario" <<'PY_WINDOW' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert not state.get("history_pages") and not state.get("posts"), state -PY_WINDOW -done - -echo "PR required-gate context contract checks passed" - -# Activated callers preserve native proof and require acknowledged pending barriers. -PUBLISH_SCRIPT="$ROOT_DIR/.github/actions/publish-required-gate-status/publish-required-gate-status.sh" -python3 - "$ROOT_DIR" <<'PY_PUBLISH' -from pathlib import Path -import os -import subprocess -import sys -import yaml -root = Path(sys.argv[1]) -action = yaml.load((root / ".github/actions/publish-required-gate-status/action.yml").read_text(), Loader=yaml.BaseLoader) -assert set(action["inputs"]) == {"assessment", "gate-name", "workflow-name", "workflow-file", "workflow-path"} -assert all(value["required"] == "true" for value in action["inputs"].values()) -assert action["outputs"]["publication"]["value"] == "${{ steps.publish.outputs.publication }}" -callers = ( - ("ci.yml", "validation-gate", "Validation Gate", "CI — Validation"), - ("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"), -) -for filename, job_id, gate, workflow_name in callers: - data = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) - job = data["jobs"][job_id] - assert job["permissions"] == {"contents": "read", "checks": "read", "actions": "read", "pull-requests": "read", "statuses": "write"} - # The new write permission is confined to the required gate job. - assert "statuses" not in data.get("permissions", {}) - assert all("statuses" not in value.get("permissions", {}) for key, value in data["jobs"].items() if key != job_id) - steps = job["steps"] - preserve = next(step for step in steps if step.get("id") == "preserved_gate") - publishers = [step for step in steps if step.get("uses") == "./.github/actions/publish-required-gate-status"] - assert len(publishers) == 1 - publisher = publishers[0] - assert publisher["name"] == "Publish pending required gate status" - assert publisher["id"] == "publish-pending-status" - assert publisher["if"] == preserve["if"] - assert publisher["with"] == { - "assessment": "${{ steps.preserved_gate.outputs.assessment }}", "gate-name": gate, - "workflow-name": workflow_name, "workflow-file": filename, "workflow-path": f".github/workflows/{filename}", - } - guard = next(step for step in steps if step.get("name") == "Report dependency-deferred required gate") - assert guard["if"] == preserve["if"].replace("${{ ", "${{ !cancelled() && ", 1) - assert guard["env"] == {"PUBLISHER_OUTCOME": "${{ steps.publish-pending-status.outcome }}", "ASSESSMENT": "${{ steps.preserved_gate.outputs.assessment }}", "PUBLICATION": "${{ steps.publish-pending-status.outputs.publication }}"} - assert steps.index(publisher) == steps.index(preserve) + 1 - assert steps.index(guard) == steps.index(publisher) + 1 - assert not any("continue-on-error" in step for step in (preserve, publisher, guard)) - # Execute each actual caller guard: only these complete outcome pairs pass. - allowed = {("dependency-deferred", "pending-acknowledged"), ("success", "unchanged"), - ("success", "success-acknowledged"), ("success", "pending-acknowledged")} - for outcome in ("success", "failure", "skipped", "cancelled", ""): - for assessment in ("dependency-deferred", "success", "failure", "", "unknown"): - for publication in ("pending-acknowledged", "success-acknowledged", "unchanged", "", "unknown"): - result = subprocess.run(["bash", "-e", "-c", guard["run"]], - env={**os.environ, "PUBLISHER_OUTCOME": outcome, "ASSESSMENT": assessment, "PUBLICATION": publication}, - capture_output=True, text=True, check=False) - expected = 0 if outcome == "success" and (assessment, publication) in allowed else 1 - assert result.returncode == expected, (filename, outcome, assessment, publication, result) - -PY_PUBLISH -mkdir "$tmp_dir/producer-bin" -cat >"$tmp_dir/producer-bin/gh" <<'EOF_PRODUCER_GH' -#!/usr/bin/env bash -set -euo pipefail -if [[ "${GITHUB_OUTPUT}" != "${PRODUCER_OUTPUT_PATH}" ]]; then - exec "${MOCK_ORIGINAL_GH}" "$@" -fi -python3 - "$@" <<'PY_PRODUCER_GH' -import json -import os -from pathlib import Path -import sys -args = sys.argv[1:] -state_path = Path(os.environ["PRODUCER_STATE"]) -state = json.loads(state_path.read_text()) -scenario = state["scenario"] -method = args[args.index("--method") + 1] -endpoint = next(arg for arg in args if arg.startswith("/repos/")) -head, base, old_base = "a" * 40, "b" * 40, "c" * 40 -repo = "example/firemud" -head_repo = "fork-owner/firemud" if scenario == "deferred-fork" else repo -current_attempt = 2 if scenario == "deferred-owned-earlier-attempt" else 1 -api_url = f"https://api.github.com/repos/{repo}/statuses/{head}" -run_url = f"https://github.com/{repo}/actions/runs/" -creator = {"id": 41898282, "login": "github-actions[bot]", "type": "Bot"} -state.setdefault("calls", []).append(f"{method} {endpoint}") - -def rich_history_case(scenario, barrier, page): - # Native GET /statuses/ is a newest-first array with creator; the - # combined projection above has the same IDs but deliberately no creator. - case = scenario.removeprefix("bridge-").removeprefix("history-") - older = {**barrier, "id": 499, "created_at": "2026-10-14T00:00:00Z", - "creator": {"id": 99, "login": "foreign", "type": "User"}} - unrelated = [{**barrier, "id": 1000 + (page - 1) * 100 + index, "context": f"other-{page}-{index}", - "created_at": "2026-10-15T01:00:00Z"} for index in range(100)] - if case == "latest-owned": return [barrier, older] - if case == "latest-foreign": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"]}] - if case == "null-actor": return [{**barrier, "creator": None}] - if case == "missing-actor": return [{key: value for key, value in barrier.items() if key != "creator"}] - if case == "unknown-state": return [{**barrier, "state": "unknown"}] - if case == "page-two-owned": return unrelated if page == 1 else [barrier, older] - if case == "page-two-absent": return unrelated if page == 1 else [] - if case == "budget": return unrelated - if case == "unavailable-page": - if page == 1: return unrelated - raise RuntimeError("status page unavailable") - if case == "duplicate-page": return unrelated if page == 1 else [{**unrelated[0], "id": 1000}] - if case == "wrong-head-url": return [{**barrier, "url": barrier["url"].replace("a" * 40, "b" * 40)}] - if case == "same-second": return [barrier, {**older, "created_at": barrier["created_at"]}] - if case == "foreign-same-second": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"], "created_at": barrier["created_at"]}] - if case == "first-page-stop": - if page != 1: raise RuntimeError("older pages must not be read") - return [barrier] + unrelated[:99] - if case == "ignore-old-malformed": return [barrier, "bad"] - if case == "overfull": return unrelated + [barrier] - if case == "scalar": return "bad" - if case == "malformed-row": return ["bad"] - raise AssertionError(case) - -result = None -exit_status = 0 -if method == "POST": - assert endpoint == f"/repos/{repo}/statuses/{head}", endpoint - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - state.setdefault("posts", []).append(fields) - result = {"id": 501, "url": api_url, "creator": creator, - "state": fields["state"], "context": fields["context"], "target_url": fields["target_url"], - "created_at": "2026-10-15T00:00:00Z", "updated_at": "2026-10-15T00:00:00Z"} - # Deliberately no sha/app_id: those fields do not exist in native statuses. - if scenario in {"ack-denied", "ack-ambiguous"}: - exit_status = 1 - elif scenario == "ack-wrong-url": - result["url"] = api_url.replace(head, base) - elif scenario == "ack-missing-creator": - result.pop("creator") - elif scenario == "ack-missing-id": - result.pop("id") - elif scenario == "ack-bad-timestamp": - result["created_at"] = "unknown" - elif scenario == "ack-wrong-state": - result["state"] = "success" -elif endpoint.endswith("/actions/workflows/ci.yml"): - result = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith("/pulls/123"): - state["pr_reads"] = state.get("pr_reads", 0) + 1 - result = {"number": 123, "state": "open", "base": {"sha": base, "ref": "develop", "repo": {"full_name": repo}}, - "head": {"sha": head, "ref": "proof-branch", "repo": {"full_name": head_repo}}} - if scenario in {"tuple-replaced", "durable-tuple-replaced"} and state["pr_reads"] > 1: - result["base"]["sha"] = old_base -elif endpoint.endswith(f"/commits/{head}/status") or endpoint.endswith(f"/statuses/{head}"): - state["status_reads"] = state.get("status_reads", 0) + 1 - barrier_state = "pending" - if scenario in {"deferred-owned-failure", "success-owned-failure"}: - barrier_state = "failure" - elif scenario in {"deferred-owned-error", "success-owned-error"}: - barrier_state = "error" - elif scenario in {"deferred-owned-success", "success-owned-success"}: - barrier_state = "success" - barrier = {"id": 500, "url": api_url, "created_at": "2026-10-15T00:00:00Z", "context": "Validation Gate", "state": barrier_state, - "target_url": f"{run_url}{300 if current_attempt == 2 else 200}/attempts/1", "creator": creator} - if scenario.endswith("foreign"): - barrier["creator"] = {"id": 99, "login": "foreign", "type": "User"} - if scenario == "status-replaced" and state["status_reads"] > 1: - barrier["id"] = 999 - if scenario == "durable-status-replaced" and state["status_reads"] > 1: - barrier["id"] = 999 - if scenario in {"deferred-owned-current-pending", "status-arrived-current-pending", "status-arrived-current-foreign", "durable-current-wrong-app", "durable-current-missing-publisher", "durable-tuple-replaced", "durable-status-replaced"}: - barrier["target_url"] = f"{run_url}200/attempts/1" - if scenario == "status-arrived-current-foreign": - barrier["creator"] = {"id": 99, "login": "foreign", "type": "User"} - absent = scenario in {"deferred-absent", "deferred-fork", "success-absent"} or scenario.startswith("ack-") or scenario.startswith("current-") - rich = [] if absent else [barrier] - if scenario in {"status-arrived-current-pending", "status-arrived-stale-pending", "status-arrived-current-foreign"} and state["status_reads"] == 1: - rich = [] - combined = {"sha": head, "total_count": len(rich), "statuses": [{key: value for key, value in row.items() if key != "creator"} for row in rich]} - assert all("creator" not in row for row in combined["statuses"]) - if endpoint.endswith("/status"): - result = combined # Actual combined projection deliberately omits creator. - else: - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - assert fields["per_page"] == "100" and "--paginate" not in args - page = int(fields["page"]) - state.setdefault("status_pages", []).append(page) - result = rich - if scenario.startswith("history-"): - try: - result = rich_history_case(scenario, barrier, page) - except RuntimeError: - result = None - exit_status = 1 - if scenario == "incomplete-status": - result = combined # Wrong endpoint shape must never qualify. -elif "/actions/runs/" in endpoint and not endpoint.endswith("/jobs"): - historical = "/attempts/" in endpoint - run_id = int(endpoint.split("/")[-3] if historical else endpoint.rsplit("/", 1)[1]) - assert run_id in {200, 300}, endpoint - old = historical - attempt = int(endpoint.rsplit("/", 1)[1]) if historical else current_attempt - running = not old or scenario == "deferred-owned-running" - run_base = base if scenario in {"deferred-owned-current-pending", "status-arrived-current-pending", "status-arrived-current-foreign", "durable-current-wrong-app", "durable-current-missing-publisher", "durable-tuple-replaced", "durable-status-replaced"} else old_base if run_id == 200 else base - result = {"id": run_id, "run_attempt": attempt, "run_number": 2 if run_id == 200 else 3, "workflow_id": 42, "event": "pull_request", - "repository": {"full_name": repo}, "head_repository": {"full_name": head_repo}, - "head_sha": head, "head_branch": "proof-branch", "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "pull_requests": [], - "display_title": f"CI — Validation pr-123 base-{run_base} head-{head}", - "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success"} - if old and scenario == "deferred-owned-newer": - result["run_number"] = 4 - if old and scenario == "deferred-old-equal-number": - result["run_number"] = 3 - if old and scenario == "deferred-old-missing-number": - result.pop("run_number") - if old and scenario == "deferred-old-wrong-title": - result["display_title"] = result["display_title"].replace("pr-123", "pr-456") - if not old and scenario == "current-wrong-tuple": - result["head_sha"] = old_base -elif endpoint.endswith("/jobs"): - run_id = int(endpoint.split("/")[-4]) - attempt = int(endpoint.split("/")[-2]) - old = run_id == 200 or (current_attempt == 2 and attempt == 1) - running = not old or scenario == "deferred-owned-running" - native_id = run_id * 10 + attempt if current_attempt == 2 else run_id * 10 - publisher = {"name": "Publish pending required gate status", "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "skipped" if scenario == "deferred-old-skipped" else "success"} - steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "success"}, publisher] - if old and running: - steps = [publisher] - if not old and scenario == "durable-current-missing-publisher": - steps = steps[:1] - job = {"id": native_id, "run_id": run_id, "name": "Validation Gate", "head_sha": head, - "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success", - "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{native_id}", "steps": steps} - result = {"total_count": 1, "jobs": [job]} - if scenario == "current-incomplete-jobs" and not old: - result["total_count"] = 2 -elif "/check-runs/" in endpoint: - check_id = int(endpoint.rsplit("/", 1)[1]) - old = check_id == 2000 or (current_attempt == 2 and check_id == 3001) - running = not old or scenario == "deferred-owned-running" - result = {"id": check_id, "name": "Validation Gate", "head_sha": head, - "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success", - "app": {"id": 99 if scenario == "deferred-old-wrong-app" or (not old and scenario in {"current-wrong-app", "durable-current-wrong-app"}) else 15368, "slug": "github-actions"}} -else: - raise AssertionError(endpoint) -state_path.write_text(json.dumps(state)) -if result is not None: - print(json.dumps(result)) - if scenario == "ack-multiple" and method == "POST": - print(json.dumps(result)) -sys.exit(exit_status) -PY_PRODUCER_GH -EOF_PRODUCER_GH -chmod +x "$tmp_dir/producer-bin/gh" -run_producer() { - local scenario="$1" assessment="$2" original="${3:-no-local-workflow-file}" - local event_file="$tmp_dir/producer-event-$scenario" head_repository=example/firemud current_attempt=1 - [[ "$scenario" != deferred-owned-earlier-attempt ]] || current_attempt=2 - [[ "$scenario" != deferred-fork ]] || head_repository=fork-owner/firemud - jq -n --arg head_repo "$head_repository" '{action: "edited", number: 123, repository: {full_name: "example/firemud"}, changes: {title: {from: "old"}}, - pull_request: {number: 123, base: {sha: ("b" * 40), ref: "develop", repo: {full_name: "example/firemud"}}, - head: {sha: ("a" * 40), ref: "proof-branch", repo: {full_name: $head_repo}}}}' >"$event_file" - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/producer-state-$scenario" - : >"$tmp_dir/producer-output-$scenario" - PATH="$tmp_dir/producer-bin:$PATH" GH_TOKEN=test-token GITHUB_REPOSITORY=example/firemud \ - GITHUB_EVENT_NAME=pull_request GITHUB_EVENT_PATH="$event_file" GITHUB_RUN_ID=300 GITHUB_RUN_ATTEMPT="$current_attempt" \ - GITHUB_OUTPUT="$tmp_dir/producer-output-$scenario" PRODUCER_OUTPUT_PATH="$tmp_dir/producer-output-$scenario" \ - PRODUCER_STATE="$tmp_dir/producer-state-$scenario" MOCK_ORIGINAL_GH="$tmp_dir/gh" \ - GH_SCENARIO="$original" GH_FAILURE_MODE=none GH_RETRY_COUNT_FILE="$tmp_dir/producer-proof-count-$scenario" \ - BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - PR_NUMBER=123 ASSESSMENT="$assessment" REQUIRED_GATE_NAME='Validation Gate' EXPECTED_WORKFLOW_NAME='CI — Validation' \ - EXPECTED_WORKFLOW_FILE=ci.yml EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml \ - bash "$PUBLISH_SCRIPT" >"$tmp_dir/producer-log-$scenario" 2>&1 -} -for scenario in deferred-absent deferred-fork deferred-owned-pending deferred-owned-current-pending deferred-owned-earlier-attempt deferred-owned-newer deferred-old-equal-number deferred-old-missing-number deferred-owned-failure deferred-owned-error deferred-owned-success deferred-owned-running deferred-owned-cancelled deferred-owned-step-failed success-owned-pending success-owned-failure success-owned-error success-assessment-pending status-replaced status-arrived-current-pending status-arrived-stale-pending status-arrived-current-foreign tuple-replaced durable-tuple-replaced durable-status-replaced deferred-foreign deferred-old-wrong-app deferred-old-wrong-title deferred-old-skipped success-absent success-owned-success success-foreign; do - assessment=dependency-deferred - [[ "$scenario" != success-* ]] || assessment=success - original=no-local-workflow-file - [[ "$scenario" != success-assessment-pending ]] || original=pending-predecessor - if ! run_producer "$scenario" "$assessment" "$original"; then - cat "$tmp_dir/producer-log-$scenario" >&2; exit 1 - fi - python3 - "$tmp_dir/producer-state-$scenario" "$tmp_dir/producer-output-$scenario" "$scenario" <<'PY_PUBLISH' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -scenario = sys.argv[3] -unchanged = scenario in {"status-replaced", "status-arrived-stale-pending", "status-arrived-current-foreign", "tuple-replaced", "durable-tuple-replaced", "durable-status-replaced", "deferred-owned-newer", "deferred-old-equal-number", "deferred-old-missing-number", "deferred-foreign", "deferred-old-wrong-app", "deferred-old-wrong-title", "deferred-old-skipped", "success-absent", "success-owned-success", "success-foreign"} -expected = "unchanged" if unchanged else "success-acknowledged" if scenario in {"success-owned-pending", "success-owned-failure", "success-owned-error"} else "pending-acknowledged" -assert Path(sys.argv[2]).read_text().strip() == f"publication={expected}", (scenario, state) -already_durable = scenario in {"deferred-owned-current-pending", "deferred-owned-earlier-attempt", "status-arrived-current-pending"} -assert len(state.get("posts", [])) == (0 if unchanged or already_durable else 1), state -if not unchanged and not already_durable: - assert state["posts"][0]["target_url"] == f"https://github.com/example/firemud/actions/runs/300/attempts/{2 if scenario == 'deferred-owned-earlier-attempt' else 1}", state - assert state["posts"][0]["state"] == expected.split("-")[0], state -PY_PUBLISH -done -# Refreshed cancellation-only proof must acknowledge a pending status, even -# when the caller originally assessed success. It never acknowledges success. -run_producer success-assessment-pending success cancellation-pending -[[ "$(<"$tmp_dir/producer-output-success-assessment-pending")" == publication=pending-acknowledged ]] || exit 1 -[[ "$(jq -r '.posts[0].state' "$tmp_dir/producer-state-success-assessment-pending")" == pending ]] || exit 1 - -for history_case in latest-owned latest-foreign null-actor missing-actor unknown-state page-two-owned page-two-absent budget unavailable-page duplicate-page wrong-head-url same-second foreign-same-second first-page-stop ignore-old-malformed overfull scalar malformed-row; do - scenario="history-$history_case" - case "$history_case" in - budget|unavailable-page|duplicate-page|wrong-head-url|overfull|scalar|malformed-row) - if run_producer "$scenario" success; then - echo "invalid rich producer history qualified: $history_case" >&2; exit 1 - fi ;; - *) run_producer "$scenario" success ;; - esac - python3 - "$tmp_dir/producer-state-$scenario" "$tmp_dir/producer-output-$scenario" "$history_case" <<'PY_HISTORY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -case = sys.argv[3] -expected = "success-acknowledged" if case in {"latest-owned", "page-two-owned", "same-second", "first-page-stop", "ignore-old-malformed"} else "unchanged" if case in {"latest-foreign", "foreign-same-second", "null-actor", "missing-actor", "unknown-state", "page-two-absent"} else None -assert Path(sys.argv[2]).read_text().strip() == (f"publication={expected}" if expected else ""), state -assert len(state.get("posts", [])) == (1 if expected == "success-acknowledged" else 0), state -assert not any("/commits/" in call and call.endswith("/status") for call in state["calls"]), state -if case.startswith("page-two-"): assert 2 in state["status_pages"], state -if case == "first-page-stop": assert all(page == 1 for page in state["status_pages"]), state -if case == "budget": assert state["status_pages"] == list(range(1, 11)), state -PY_HISTORY -done - -for scenario in success-assessment-failed incomplete-status current-wrong-app current-wrong-tuple current-incomplete-jobs durable-current-wrong-app durable-current-missing-publisher ack-denied ack-ambiguous ack-wrong-url ack-missing-creator ack-missing-id ack-bad-timestamp ack-wrong-state ack-multiple; do - assessment=dependency-deferred - original=no-local-workflow-file - if [[ "$scenario" == success-assessment-failed ]]; then assessment=success; original=failed-predecessor; fi - if run_producer "$scenario" "$assessment" "$original"; then - echo "invalid publication succeeded: $scenario" >&2; exit 1 - fi - [[ ! -s "$tmp_dir/producer-output-$scenario" ]] || { echo "failed publication emitted native-success allowance" >&2; exit 1; } - python3 - "$tmp_dir/producer-state-$scenario" "$scenario" <<'PY_PUBLISH' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert len(state.get("posts", [])) == (1 if sys.argv[2].startswith("ack-") else 0), state -PY_PUBLISH -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' diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index b47d12f249..1aac58fb7a 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -362,7 +362,7 @@ for filename in ("ci.yml", "security.yml", "license-scan.yml", "codeql.yml"): expected_events.add("schedule") if events["schedule"] != [{"cron": "0 0 * * 0"}]: raise SystemExit("CodeQL must retain its weekly full-analysis schedule") - if workflow["jobs"]["codeql-gate"]["if"] != "${{ always() && github.event_name == 'pull_request' }}": + if workflow["jobs"]["codeql-gate"]["if"] != "${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}": raise SystemExit("CodeQL Gate must cover every PR base and remain PR-only") if set(events) != expected_events: raise SystemExit(f"{filename} must retain exactly its supported events") @@ -552,9 +552,11 @@ PYTHON # 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' +# A metadata-only edit skips the required gate under a non-required name so the +# earlier substantive result stands; pr-required-gate-context-contract.sh owns +# the full gate-condition matrix. +# shellcheck disable=SC2016 # Assert literal GitHub expression syntax. +assert_job_contains smoke.yml smoke-gate "name: \${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || '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]' @@ -648,8 +650,8 @@ assert "branches" not in runtime["on"]["workflow_run"] PYTHON # Reproduce the metadata-edit sequence structurally: the edit has its own -# concurrency namespace, all runtime construction jobs remain skipped, and no -# dispatch-capable step exists in Smoke Gate. The original event tuple remains +# concurrency namespace, all runtime construction jobs remain skipped, and Smoke +# Gate skips under a non-required name. 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' @@ -663,8 +665,11 @@ smoke_path, runtime_path = map(Path, sys.argv[1:]) smoke = yaml.load(smoke_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) 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 smoke["jobs"]["smoke-gate"].get("name") != ( + "${{ github.event_name == 'pull_request' && github.event.action == 'edited' && " + "github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || 'Smoke Gate' }}" +): + raise SystemExit("metadata-only smoke must skip under a non-required name and keep Smoke Gate otherwise") runtime_jobs = runtime["jobs"] metadata_guard = "github.event.action != 'edited' || github.event.changes.base.ref != null" @@ -934,7 +939,6 @@ async function runDispatcher({ workflow_name: "CI — Validation", name: "Validation Gate", status: "completed", conclusion: "success", check_run_url: `https://api.github.com/repos/${repository}/check-runs/8001`, steps: [ - { name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: "skipped" }, { name: "Enforce validation success", status: "completed", conclusion: "success" }, ], ...(ciEvidence.gate ?? {}), @@ -1124,14 +1128,12 @@ async function runDispatcher({ const emptyBranch = await runDispatcher({ tuples: [child], callback: { ...prCallback, head_branch: "" } }); assert.equal(emptyBranch.dispatches.length, 0); assert.equal(emptyBranch.refRequests.length, 0, "empty callback branch must be rejected before ref lookup"); - const preservationStep = { name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: "skipped" }; const enforcementStep = { name: "Enforce validation success", status: "completed", conclusion: "success" }; for (const [label, ciEvidence] of [ - ["metadata preservation executed", { gate: { steps: [{ ...preservationStep, conclusion: "success" }, { ...enforcementStep, conclusion: "skipped" }] } }], - ["failed metadata preservation", { gate: { steps: [{ ...preservationStep, conclusion: "failure" }, { ...enforcementStep, conclusion: "skipped" }] } }], - ["missing preservation", { gate: { steps: [enforcementStep] } }], - ["ambiguous preservation", { gate: { steps: [preservationStep, preservationStep, enforcementStep] } }], - ["skipped enforcement", { gate: { steps: [preservationStep, { ...enforcementStep, conclusion: "skipped" }] } }], + ["metadata-only edit gate", { gate: { name: "PR Metadata Edit (Validation Gate)", conclusion: "skipped", steps: [] } }], + ["legacy metadata gate with skipped enforcement", { gate: { steps: [{ ...enforcementStep, conclusion: "skipped" }] } }], + ["missing enforcement", { gate: { steps: [] } }], + ["ambiguous enforcement", { gate: { steps: [enforcementStep, enforcementStep] } }], ["old native attempt job", { gate: { run_attempt: 2 } }], ["wrong native job run", { gate: { run_id: 7002 } }], ["wrong native job head", { gate: { head_sha: sha("f") } }], @@ -1151,7 +1153,7 @@ async function runDispatcher({ } const failedSubstantive = await runDispatcher({ tuples: [child], sourceTuples: [source], callback: { ...prCallback, conclusion: "failure" }, - ciEvidence: { gate: { conclusion: "failure", steps: [preservationStep, { ...enforcementStep, conclusion: "failure" }] } }, + ciEvidence: { gate: { conclusion: "failure", steps: [{ ...enforcementStep, conclusion: "failure" }] } }, }); assert.equal(runtimeDispatches(failedSubstantive).length, 2, "failed substantive CI remains a reconcile signal requiring each source/child's independent runtime smoke"); @@ -2383,21 +2385,17 @@ require_ordered_sequence \ 'if (fullSmokeJob?.conclusion !== "success") {' \ 'PR Full-Stack Smoke job did not complete successfully:' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -require_contains "$smoke_path" 'SMOKE_GATE_REQUIRED: ${{ github.event.action != '\''edited'\'' || github.event.changes.base.ref != null }}' -# shellcheck disable=SC2016 # Assert literal GitHub expression syntax. require_contains "$smoke_path" 'CHANGES_RESULT: ${{ needs.changes.result }}' # shellcheck disable=SC2016 # Assert literal shell source. -require_contains "$smoke_path" 'echo "required=$SMOKE_GATE_REQUIRED" >> "$GITHUB_OUTPUT"' -# shellcheck disable=SC2016 # Assert literal shell source. -require_contains "$smoke_path" 'if [ "$SMOKE_GATE_REQUIRED" = "true" ] && [ "$CHANGES_RESULT" = "success" ]; then' +require_contains "$smoke_path" 'if [ "$CHANGES_RESULT" = "success" ]; then' # shellcheck disable=SC2016 # Assert literal shell source. require_contains "$smoke_path" 'echo "execute=true" >> "$GITHUB_OUTPUT"' # shellcheck disable=SC2016 # Assert literal shell source. require_contains "$smoke_path" 'echo "execute=false" >> "$GITHUB_OUTPUT"' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -require_contains "$smoke_path" 'if: ${{ steps.smoke_gate_context.outputs.required == '\''true'\'' && steps.smoke_gate_context.outputs.execute != '\''true'\'' }}' +require_contains "$smoke_path" 'if: ${{ steps.smoke_gate_context.outputs.execute != '\''true'\'' }}' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -if grep -Fq 'echo "required=${{' "$smoke_path" || grep -Fq 'echo "execute=${{' "$smoke_path"; then +if grep -Fq 'echo "execute=${{' "$smoke_path"; then echo "smoke_gate_context must pass expressions through step env" >&2 exit 1 fi diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index fb98491bc3..e3e5976ea2 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -15,8 +15,8 @@ if ! awk ' fi grep -Fq 'github.paginate(github.rest.actions.listWorkflowRuns' "$workflow" -grep -Fq 'workflowRunFor("codeql.yml")' "$workflow" -grep -Fq 'workflowRunFor("license-scan.yml")' "$workflow" +grep -Fq 'workflowRunFor("codeql.yml", "CodeQL Gate", checkRuns)' "$workflow" +grep -Fq 'workflowRunFor("license-scan.yml", "License Gate", checkRuns)' "$workflow" grep -Fq 'head_sha: headSha,' "$workflow" grep -Fq 'return "skipped";' "$workflow" grep -Fq 'run_attempt' "$workflow" @@ -137,6 +137,18 @@ const github = { status: "completed", conclusion: "failure", }, + { + // A later metadata-only edit run: its gate is skipped under a + // non-required name and must not mask the substantive failure. + id: 270, + event: "pull_request", + head_sha: headSha, + display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + created_at: "2026-09-20T12:00:00Z", + run_attempt: 1, + status: "completed", + conclusion: "success", + }, { id: 250, event: "pull_request", @@ -183,6 +195,16 @@ const github = { completed_at: "2026-09-19T00:02:00Z", details_url: "https://github.example/actions/runs/100/job/1001", }, + { + id: 2701, + // Native skipped-job name: GitHub leaves the expression unevaluated. + name: "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate'", + status: "completed", + conclusion: "skipped", + created_at: "2026-09-20T12:00:01Z", + completed_at: "2026-09-20T12:00:01Z", + details_url: "https://github.example/actions/runs/270/job/2701", + }, { id: 2001, name: "CodeQL Gate",