name: Baseline Checks

on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]
  push:
    branches:
      - main

permissions:
  contents: read

env:
  # Keep browser bootstraps compatible with the installed Convex CLI.
  CONVEX_LOCAL_BACKEND_VERSION: precompiled-2026-11-30-e48d3c8

concurrency:
  group: baseline-checks-${{ github.ref }}
  cancel-in-progress: true

jobs:
  visual-selection:
    name: Select Visual Evidence
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      browsers: ${{ steps.selection.outputs.browsers }}
      visuals: ${{ steps.selection.outputs.visuals }}
      full: ${{ steps.selection.outputs.full }}
      jobs: ${{ steps.selection.outputs.jobs }}
      flows: ${{ steps.selection.outputs.flows }}
      flowPattern: ${{ steps.selection.outputs.flowPattern }}
      publicPattern: ${{ steps.selection.outputs.publicPattern }}
      media: ${{ steps.selection.outputs.media }}
      claimAuth: ${{ steps.selection.outputs.claimAuth }}
      analytics: ${{ steps.selection.outputs.analytics }}
      scripts: ${{ steps.selection.outputs.scripts }}
      restream: ${{ steps.selection.outputs.restream }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - name: Test selection and verification contracts
        run: node --test scripts/candidate-preview-acceptance.test.mjs .github/scripts/ci-scopes.test.cjs .github/scripts/visual-ci.test.cjs
      - name: Select visual evidence
        id: selection
        env:
          BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
        run: node .github/scripts/visual-ci.cjs

  lint-web:
    name: Lint Web
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run lint
        run: pnpm lint:web

  verify-docs:
    name: Verify Docs
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run docs verification
        run: pnpm verify:docs

  verify-api-mcp:
    name: Verify API and MCP
    needs: [visual-selection]
    # Match the supported Ubuntu release used in the browser/media jobs.
    runs-on: ubuntu-24.04
    timeout-minutes: 15

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Test CI selection and report contracts
        run: node --test .github/scripts/ci-scopes.test.cjs .github/scripts/visual-ci.test.cjs .github/scripts/pr-verification-report.test.cjs .github/scripts/visual-label-removal.test.cjs

      - name: Run API contract verification
        run: pnpm verify:api-contracts

      - name: Install script media test prerequisites
        timeout-minutes: 5
        run: |
          sudo "$(command -v node)" .github/scripts/configure-ubuntu-mirror.mjs
          sudo apt-get update
          sudo apt-get install --no-install-recommends --yes ffmpeg
          ffmpeg -version

      - name: Run MCP package verification
        run: pnpm typecheck:vrdex-mcp && pnpm test:vrdex-mcp && pnpm smoke:mcp-compat && pnpm check:mcp-client-matrix
      - name: Verify web source contracts
        if: needs.visual-selection.outputs.scripts != 'true'
        run: pnpm test:scripts:web

      - name: Verify affected script contracts
        if: needs.visual-selection.outputs.scripts == 'true'
        run: pnpm test:scripts

      - name: Verify media relay package
        run: |
          pnpm --filter @vrdex/media-relay typecheck
          pnpm --filter @vrdex/media-relay test

      - name: Setup Terraform for relay mocks
        uses: hashicorp/setup-terraform@v4
        with:
          terraform_version: 1.10.5
          terraform_wrapper: false

      - name: Validate media relay with mock providers
        env:
          TF_IN_AUTOMATION: "true"
          TF_INPUT: "false"
          AWS_EC2_METADATA_DISABLED: "true"
        run: |
          terraform -chdir=infra/terraform/media-relay init -backend=false
          terraform -chdir=infra/terraform/media-relay validate
          terraform -chdir=infra/terraform/media-relay test

  typecheck-web:
    name: Typecheck Web
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run typecheck
        run: pnpm typecheck:web

      - name: Run web unit tests
        run: pnpm test:web

  typecheck-backend:
    name: Typecheck Backend
    # Match the supported Ubuntu release used in the browser/media jobs.
    runs-on: ubuntu-24.04
    timeout-minutes: 10

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Setup Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.12"

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install backend media test prerequisites
        timeout-minutes: 5
        run: |
          sudo "$(command -v node)" .github/scripts/configure-ubuntu-mirror.mjs
          sudo apt-get update
          sudo apt-get install --no-install-recommends --yes ffmpeg
          ffmpeg -version

      - name: Run backend typecheck
        run: pnpm typecheck:backend

      - name: Run backend unit tests
        run: pnpm test:backend

      - name: Run temporal runtime tests
        run: pnpm test:temporal-runtime

      - name: Run temporal inference worker tests
        run: pnpm test:temporal-inference

  verify-backend-local:
    name: Verify Backend Local
    runs-on: ubuntu-latest
    timeout-minutes: 10
    env:
      CONVEX_LOCAL_BACKEND_VERSION: precompiled-2026-11-30-e48d3c8
      MIGRATION_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha || '' }}

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Require fresh owned local migration state
        run: node scripts/verify-event-broadcast-migration-local.mjs preflight

      - name: Verify backend bootstrap
        run: pnpm verify:backend:local

      - name: Check generated backend files
        run: git diff --exit-code -- convex/_generated

      - name: Rehearse local migration and production admission denial
        id: migration
        timeout-minutes: 6
        run: node --import tsx scripts/verify-event-broadcast-migration-local.mjs run-admission-blocked

      - name: Check generated backend files after closure
        if: ${{ always() && steps.migration.outcome != 'skipped' }}
        run: git diff --exit-code -- convex/_generated

      - name: Stage safe migration evidence and require completeness
        id: migration-evidence
        if: ${{ always() && steps.migration.outcome != 'skipped' }}
        run: node scripts/verify-event-broadcast-migration-local.mjs check-artifacts

      - name: Upload safe migration evidence
        if: ${{ always() && steps.migration.outcome != 'skipped' && steps.migration-evidence.outputs.upload-path != '' }}
        uses: actions/upload-artifact@v7
        with:
          name: event-broadcast-migration-local-${{ github.run_id }}-${{ github.run_attempt }}
          retention-days: 7
          if-no-files-found: error
          path: ${{ steps.migration-evidence.outputs.upload-path }}

  restream-local-checks:
    name: Restream Local Checks
    needs: [visual-selection]
    runs-on: ubuntu-24.04
    timeout-minutes: 20

    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Check restream-relevant changes
        id: changes
        env:
          BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
          RESTREAM_SELECTED: ${{ needs.visual-selection.outputs.restream }}
        run: |
          echo "enabled=$RESTREAM_SELECTED" >> "$GITHUB_OUTPUT"
          echo "Native restream acceptance selected: $RESTREAM_SELECTED" >> "$GITHUB_STEP_SUMMARY"

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Check native CI contracts
        run: node --test .github/scripts/restream-native*.test.mjs

      - name: Build hosted restream worker image
        if: steps.changes.outputs.enabled == 'true'
        run: docker build -f workers/restream/Dockerfile -t vrdex-restream-worker:ci .

      - name: Run required native transport gate
        if: steps.changes.outputs.enabled == 'true'
        timeout-minutes: 8
        run: node .github/scripts/restream-native.mjs

      - name: Verify captured transport with packaged runtime
        if: steps.changes.outputs.enabled == 'true'
        timeout-minutes: 5
        run: |
          docker run --rm --network none --read-only --cap-drop ALL \
            --memory 4g --cpus 4 --tmpfs /tmp:rw,size=1g \
            -v "$PWD/tests:/tests:ro" \
            -e CAPTURED_TRANSPORT_NATIVE=1 \
            -e CAPTURED_TRANSPORT_RUNTIME_ROOT=/app \
            vrdex-restream-worker:ci node --test /tests/scripts/event-captured-transport.test.mjs

      - name: Install dependencies
        if: steps.changes.outputs.enabled == 'true'
        run: pnpm install --frozen-lockfile

      - name: Install FFmpeg
        if: steps.changes.outputs.enabled == 'true'
        timeout-minutes: 8
        run: |
          if command -v ffmpeg && command -v ffprobe; then exit 0; fi
          sudo "$(command -v node)" .github/scripts/configure-ubuntu-mirror.mjs
          sudo apt-get update
          sudo apt-get install -y --no-install-recommends ffmpeg

      - name: Typecheck Discord Gateway
        if: steps.changes.outputs.enabled == 'true'
        run: pnpm typecheck:discord-gateway

      - name: Test Discord Gateway
        if: steps.changes.outputs.enabled == 'true'
        run: pnpm test:discord-gateway

      - name: Dry-run hosted restream worker image
        if: steps.changes.outputs.enabled == 'true'
        run: |
          docker run --rm \
            -e CONVEX_URL=https://example.invalid \
            -e VRDEX_RESTREAM_BENCHMARK_MODE=dry-run \
            -e VRDEX_RESTREAM_QUALITY_GATE=1080p60 \
            -e VRDEX_RESTREAM_MAX_CONCURRENT_WORKERS=10 \
            -e VRDEX_RESTREAM_MAX_SESSION_SECONDS=43200 \
            -e VRDEX_RESTREAM_KILL_SWITCH_SSM_PARAMETER=/vrdex/restream/hosted-worker/enabled \
            -e VRDEX_RESTREAM_SECRET_REF_NAMES=event-media/vrcdn/main-output \
            vrdex-restream-worker:ci

      - name: Run local restream validation
        if: steps.changes.outputs.enabled == 'true'
        run: pnpm proof:restream:local

      - name: Check local restream validation
        if: steps.changes.outputs.enabled == 'true'
        run: pnpm check:restream:local

  build-web:
    name: Build Web
    needs:
      - lint-web
      - verify-docs
      - verify-api-mcp
      - typecheck-web
      - typecheck-backend
      - verify-backend-local
      - restream-local-checks
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run build
        run: pnpm build:web

  build-storybook:
    name: Build Storybook
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'build-storybook')
    needs: [lint-web, verify-docs, typecheck-web, visual-selection]
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run Storybook build
        run: pnpm build:storybook

  deploy-convex-production:
    name: Deploy Convex Production
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    needs: [build-web]
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Check Convex deploy key
        id: gate
        env:
          CONVEX_DEPLOY_KEY: ${{ secrets.CONVEX_DEPLOY_KEY_PROD }}
        run: |
          if [ -z "$CONVEX_DEPLOY_KEY" ]; then
            echo "enabled=false" >> "$GITHUB_OUTPUT"
            {
              echo "## Convex production deploy"
              echo "Skipped because CONVEX_DEPLOY_KEY_PROD is not configured."
            } >> "$GITHUB_STEP_SUMMARY"
            exit 0
          fi

          echo "enabled=true" >> "$GITHUB_OUTPUT"

      - name: Setup pnpm
        if: steps.gate.outputs.enabled == 'true'
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        if: steps.gate.outputs.enabled == 'true'
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        if: steps.gate.outputs.enabled == 'true'
        run: pnpm install --frozen-lockfile

      - name: Provision PostHog claim delivery when configured
        if: steps.gate.outputs.enabled == 'true'
        env:
          CONVEX_DEPLOY_KEY: ${{ secrets.CONVEX_DEPLOY_KEY_PROD }}
          POSTHOG_PROJECT_API_KEY: ${{ secrets.TERRAFORM_POSTHOG_PUBLIC_KEY }}
        run: |
          set -euo pipefail
          if [ -z "$POSTHOG_PROJECT_API_KEY" ]; then
            echo "::notice::TERRAFORM_POSTHOG_PUBLIC_KEY is absent; analytics provisioning was skipped and existing Convex configuration was left unchanged."
            exit 0
          fi
          if ! printf '%s' "$POSTHOG_PROJECT_API_KEY" | grep -qE '^phc_[A-Za-z0-9_-]+$'; then
            echo "::error::TERRAFORM_POSTHOG_PUBLIC_KEY is not a PostHog project key."
            exit 1
          fi
          printf '%s' "$POSTHOG_PROJECT_API_KEY" | pnpm exec convex env set POSTHOG_PROJECT_API_KEY
          pnpm exec convex env set POSTHOG_DEPLOYMENT_CATEGORY production

      - name: Deploy Convex functions and schema
        if: steps.gate.outputs.enabled == 'true'
        env:
          CONVEX_DEPLOY_KEY: ${{ secrets.CONVEX_DEPLOY_KEY_PROD }}
        run: pnpm exec convex deploy --yes --typecheck=enable

      - name: Run deploy-time migrations
        if: steps.gate.outputs.enabled == 'true'
        env:
          CONVEX_DEPLOY_KEY: ${{ secrets.CONVEX_DEPLOY_KEY_PROD }}
        run: pnpm exec convex run migrations:runAll --prod

  playwright-public-smoke:
    name: Playwright Public Smoke
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'playwright-public-smoke')
    needs: [build-web, visual-selection]
    # Pinned: ubuntu-latest moved to 26.04, where this Playwright version cannot install chromium.
    # Revert to ubuntu-latest once Playwright is upgraded to a release that supports 26.04.
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    permissions:
      contents: read

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install Playwright Chromium
        working-directory: apps/web
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          pnpm exec playwright install --with-deps chromium

      - name: Verify review capture modes
        env:
          PLAYWRIGHT_SKIP_WEBSERVERS: "true"
        run: pnpm --filter web exec playwright test review-capture.spec.ts --project=desktop-chromium --project=mobile-chromium --workers=1

      - name: Run public route browser assertions
        id: flow
        env:
          PLAYWRIGHT_RECORD_VIDEO: "true"
          VRDEX_ENABLE_E2E_HELPERS: "true"
          VRDEX_E2E_BROWSER_TOKEN: local-playwright-token
          VRDEX_E2E_CONVEX_SECRET: local-convex-e2e-secret
        run: pnpm --filter web exec playwright test public-routes.smoke.spec.ts --project=desktop-chromium --project=mobile-chromium --workers=1

      - name: Verify synthetic analytics and disabled presentation
        if: needs.visual-selection.outputs.analytics == 'true'
        run: |
          pnpm --filter web exec playwright test --config playwright.analytics.config.mjs --workers=1
          NEXT_PUBLIC_POSTHOG_FOUNDATION_ENABLED=false pnpm --filter web exec playwright test --config playwright.analytics.config.mjs --workers=1

      - name: Upload public smoke artifacts
        id: upload
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: playwright-public-smoke
          if-no-files-found: error
          retention-days: 7
          path: |
            apps/web/playwright-report
            apps/web/test-results
            apps/web/playwright-artifacts

  playwright-data-flow:
    name: Playwright Data Flow
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'playwright-data-flow')
    needs: [build-web, visual-selection]
    # Pinned: ubuntu-latest moved to 26.04, where this Playwright version cannot install chromium.
    # Revert to ubuntu-latest once Playwright is upgraded to a release that supports 26.04.
    runs-on: ubuntu-24.04
    # The full serial flow suite and composed-media playback share this job budget.
    timeout-minutes: ${{ needs.visual-selection.outputs.flowPattern == '.*' && needs.visual-selection.outputs.media == 'true' && 70 || 45 }}
    permissions:
      contents: read

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install Playwright Chromium
        working-directory: apps/web
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          pnpm exec playwright install --with-deps chromium

      - name: Run current-branch signed-in claim and host regressions
        id: claim-auth
        if: needs.visual-selection.outputs.claimAuth == 'true' && github.event.pull_request.head.repo.fork == false
        env:
          PLAYWRIGHT_RECORD_VIDEO: "true"
          PLAYWRIGHT_OUTPUT_DIR: test-results-claim-auth
          PLAYWRIGHT_HTML_REPORT_DIR: playwright-report-claim-auth
          PLAYWRIGHT_JSON_REPORT_FILE: playwright-artifacts/results-claim-auth.json
          VRDEX_ENABLE_E2E_HELPERS: "true"
          VRDEX_ENABLE_E2E_AUTH_HELPERS: "true"
          VRDEX_ENABLE_E2E_ADAPTER_HELPERS: "true"
          VRDEX_ENABLE_E2E_CLERK_AUTH: "true"
          VRDEX_E2E_CLUB_INVITATIONS: "true"
          VRDEX_E2E_HOST_ACCESS: "true"
          VRDEX_E2E_BROWSER_TOKEN: local-playwright-token
          VRDEX_E2E_CONVEX_SECRET: local-convex-e2e-secret
          # Reuse the retained development tenant with this runner's isolated
          # local backend. The issuer/key check rejects production or mismatch.
          NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ${{ secrets.VRDEX_HOSTED_E2E_CLERK_PUBLISHABLE_KEY }}
          CLERK_SECRET_KEY: ${{ secrets.VRDEX_HOSTED_E2E_CLERK_SECRET_KEY }}
          CLERK_JWT_ISSUER_DOMAIN: ${{ vars.VRDEX_STAGING_CLERK_JWT_ISSUER_DOMAIN }}
          VRDEX_E2E_RUN_ID: local-claim-pr-${{ github.event.pull_request.number }}-${{ github.run_id }}-${{ github.run_attempt }}
        run: |
          case "$CLERK_SECRET_KEY" in
            sk_test_*) ;;
            *) echo "::error::The current-branch claim regression requires the retained Clerk development secret key."; exit 1 ;;
          esac
          node scripts/check-clerk-issuer-match.mjs --issuer "$CLERK_JWT_ISSUER_DOMAIN" --publishable-key "$NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY"
          pnpm --filter web exec playwright test auth-claim.flow.spec.ts club-invitation.flow.spec.ts --grep "reactive query saves a dated VRChat account|real invitation sign-in, acceptance and denials" --project=desktop-chromium --workers=1
          node --input-type=module <<'NODE'
          import { readFileSync } from "node:fs";
          const { stats } = JSON.parse(readFileSync("apps/web/playwright-artifacts/results-claim-auth.json", "utf8"));
          if (stats.expected !== 2 || stats.skipped !== 0 || stats.unexpected !== 0) {
            throw new Error("The current-branch signed-in claim and host regressions did not both execute and pass.");
          }
          console.log("Current-branch signed-in claim and host coverage:", stats);
          NODE

      - name: Run selected mutation-backed flows
        id: flow
        if: needs.visual-selection.outputs.flows == 'true'
        env:
          PLAYWRIGHT_RECORD_VIDEO: "true"
          CI_FLOW_PATTERN: ${{ needs.visual-selection.outputs.flowPattern }}
          VRDEX_ENABLE_E2E_HELPERS: "true"
          VRDEX_E2E_BROWSER_TOKEN: local-playwright-token
          VRDEX_E2E_CONVEX_SECRET: local-convex-e2e-secret
        run: pnpm --filter web exec playwright test "$CI_FLOW_PATTERN" --grep @flow --project=desktop-chromium --workers=1

      - name: Install synthetic media tools
        if: needs.visual-selection.outputs.media == 'true'
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" .github/scripts/configure-ubuntu-mirror.mjs
          sudo apt-get update && sudo apt-get install -y ffmpeg pulseaudio pulseaudio-utils
          pnpm --filter web exec playwright install --with-deps firefox

      - name: Prepare local browser audio backend
        if: needs.visual-selection.outputs.media == 'true'
        run: node scripts/playwright-audio-backend.mjs prepare

      - name: Run isolated composed media acceptance
        if: needs.visual-selection.outputs.media == 'true'
        env:
          MOBILE_MEDIA_ACCEPTANCE: "true"
          EVENT_PLAYBACK_PROOF: "true"
          NATIVE_HLS_PLAYBACK_PROOF: "true"
          CLERK_SECRET_KEY: ""
          NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ""
          PLAYWRIGHT_OUTPUT_DIR: playwright-artifacts/mobile-media/results
          PLAYWRIGHT_HTML_REPORT_DIR: playwright-artifacts/mobile-media/report
          PLAYWRIGHT_JSON_REPORT_FILE: playwright-artifacts/mobile-media/results.json
        run: pnpm --filter web exec playwright test mobile-hls-playback.spec.ts event-lineup-live.spec.ts native-trial-routing.spec.ts --project=desktop-chromium --workers=1

      - name: Stop job-owned browser audio backend
        if: always() && needs.visual-selection.outputs.media == 'true'
        run: node scripts/playwright-audio-backend.mjs cleanup

      - name: Write data-flow summary
        if: always()
        env:
          FLOW_OUTCOME: ${{ steps.flow.outcome }}
          CLAIM_AUTH_OUTCOME: ${{ steps.claim-auth.outcome }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          mkdir -p apps/web/playwright-artifacts
          cat > apps/web/playwright-artifacts/data-flow-summary.md <<EOF
          ## Playwright data-flow preview

          Outcome: ${FLOW_OUTCOME}

          Current-branch signed-in claim and host regressions: ${CLAIM_AUTH_OUTCOME:-not run}
          Forks do not receive development keys. A skipped regression is not acceptance.

          Selected flows: ${{ needs.visual-selection.outputs.flowPattern }}
          Media acceptance selected: ${{ needs.visual-selection.outputs.media }}

          Run: ${RUN_URL}
          EOF

      - name: Upload Playwright data-flow artifacts
        id: upload
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: playwright-data-flow
          if-no-files-found: error
          retention-days: 7
          path: |
            apps/web/playwright-report
            apps/web/test-results
            apps/web/playwright-artifacts
            apps/web/playwright-report-claim-auth
            apps/web/test-results-claim-auth

  playwright-hosted-data-flow:
    name: Candidate Preview Acceptance
    # Upper bound for the reusable manual-report jobs; its PR build/test jobs
    # explicitly restrict their own tokens to read-only.
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && github.event.pull_request.head.repo.fork == false && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'playwright-hosted-data-flow')
    needs: [build-web, visual-selection]
    permissions:
      contents: read
      issues: write
      pull-requests: read
    uses: ./.github/workflows/vercel-preview-deploy.yml
    with:
      pull_number: ${{ format('{0}', github.event.pull_request.number) }}
      head_sha: ${{ github.event.pull_request.head.sha }}
      browser_acceptance: true
      capture_screenshots: ${{ needs.visual-selection.outputs.visuals == 'true' }}
    secrets:
      VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
      VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
      VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
      CONVEX_DEPLOY_KEY_PREVIEW: ${{ secrets.CONVEX_DEPLOY_KEY_PREVIEW }}
      CLERK_JWT_ISSUER_DOMAIN: ${{ secrets.CLERK_JWT_ISSUER_DOMAIN }}
      VRDEX_HOSTED_E2E_BROWSER_TOKEN: ${{ secrets.VRDEX_HOSTED_E2E_BROWSER_TOKEN }}
      VRDEX_HOSTED_E2E_CLERK_PUBLISHABLE_KEY: ${{ secrets.VRDEX_HOSTED_E2E_CLERK_PUBLISHABLE_KEY }}
      VRDEX_HOSTED_E2E_CLERK_SECRET_KEY: ${{ secrets.VRDEX_HOSTED_E2E_CLERK_SECRET_KEY }}

  playwright-public-preview:
    name: Playwright Public Preview
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'playwright-public-preview')
    needs: [build-web, visual-selection]
    # Pinned: ubuntu-latest moved to 26.04, where this Playwright version cannot install chromium.
    # Revert to ubuntu-latest once Playwright is upgraded to a release that supports 26.04.
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    permissions:
      contents: read

    env:
      CI_PUBLIC_PATTERN: ${{ needs.visual-selection.outputs.publicPattern }}
      PLAYWRIGHT_CAPTURE_SCREENSHOTS: ${{ needs.visual-selection.outputs.visuals }}

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install Playwright Chromium
        working-directory: apps/web
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          pnpm exec playwright install --with-deps chromium

      - name: Run public route assertions and selected captures
        id: visual
        run: |
          pnpm --filter web exec playwright test "$CI_PUBLIC_PATTERN" --grep @visual
          node .github/scripts/visual-ci.cjs --check-captures apps/web/playwright-artifacts/screenshots

      - name: Write visual summary
        if: always()
        env:
          VISUAL_OUTCOME: ${{ steps.visual.outcome }}
          CAPTURE_SELECTED: ${{ needs.visual-selection.outputs.visuals }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          mkdir -p apps/web/playwright-artifacts

          # Counted from the run, not asserted. This previously stated "all public
          # route checks passed" unconditionally — on a failed run, and on a run
          # where a whole lane skipped. A skipped Playwright file still exits 0,
          # and `clerk-auth.ts` records where that leads: the auth-session matrix
          # lane reported green for months over a spec that ran nothing, with a
          # summary describing coverage that never executed. A summary that cannot
          # be wrong is not evidence, and this job exists to be evidence.
          counts=$(python3 - <<'PY'
          import json, pathlib
          report = pathlib.Path("apps/web/playwright-artifacts/results.json")
          if not report.exists():
              print("unknown unknown unknown unknown unknown")
              raise SystemExit
          data = json.loads(report.read_text(encoding="utf-8"))
          # `flaky` is Playwright's status for a test that failed an attempt and
          # then passed; the run exits successfully. Folding it into `failed`
          # would print failures next to `Outcome: success`, which is its own kind
          # of summary nobody can trust. Counted on its own instead, because a
          # retry that passed is worth seeing without being alarming.
          tally = {"passed": 0, "failed": 0, "skipped": 0, "flaky": 0}
          buckets = {"expected": "passed", "skipped": "skipped", "flaky": "flaky"}
          def walk(suite):
              for spec in suite.get("specs", []):
                  for test in spec.get("tests", []):
                      tally[buckets.get(test.get("status", ""), "failed")] += 1
              for child in suite.get("suites", []):
                  walk(child)
          for suite in data.get("suites", []):
              walk(suite)
          # A discovery, config, or global-setup failure lands in the report's
          # top-level `errors` and creates no test status at all, so counting only
          # `suites` can print `Outcome: failure` beside `0 failed` — the same
          # untrustworthy pairing this whole summary exists to remove.
          print(tally["passed"], tally["failed"], tally["skipped"], tally["flaky"], len(data.get("errors", [])))
          PY
          )
          passed=$(echo "$counts" | cut -d' ' -f1)
          failed=$(echo "$counts" | cut -d' ' -f2)
          skipped=$(echo "$counts" | cut -d' ' -f3)
          flaky=$(echo "$counts" | cut -d' ' -f4)
          fatal=$(echo "$counts" | cut -d' ' -f5)

          {
            echo "## Playwright public browser preview"
            echo ""
            echo "Outcome: ${VISUAL_OUTCOME}"
            echo "Review screenshot collection selected: ${CAPTURE_SELECTED}"
            echo ""
            echo "Tests: ${passed} passed, ${failed} failed, ${skipped} skipped, ${flaky} flaky."
            if [ "$fatal" != "0" ] && [ "$fatal" != "unknown" ]; then
              echo ""
              echo "**${fatal} fatal error(s)** before or outside any test — discovery,"
              echo "configuration, or global setup. These produce no test status, so the"
              echo "counts above do not reflect them."
            fi
            if [ "$skipped" != "0" ] && [ "$skipped" != "unknown" ]; then
              echo ""
              echo "Skipped tests produced no screenshots."
            fi
            echo ""
            echo "Run: ${RUN_URL}"
          } > apps/web/playwright-artifacts/visual-summary.md

      - name: Upload Playwright artifacts
        id: upload
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: playwright-public-preview
          if-no-files-found: error
          retention-days: 7
          path: |
            apps/web/playwright-report
            apps/web/test-results
            apps/web/playwright-artifacts

  playwright-image-diff:
    name: Playwright Image Diff
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.visuals == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'playwright-image-diff')
    needs: [build-web, visual-selection]
    # Pinned: ubuntu-latest moved to 26.04, where this Playwright version cannot install chromium.
    # Revert to ubuntu-latest once Playwright is upgraded to a release that supports 26.04.
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    permissions:
      contents: read

    env:
      CI_PUBLIC_PATTERN: ${{ needs.visual-selection.outputs.publicPattern }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install Playwright Chromium
        working-directory: apps/web
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          pnpm exec playwright install --with-deps chromium

      - name: Compare public route screenshots to baselines
        id: snapshots
        run: pnpm --filter web exec playwright test "$CI_PUBLIC_PATTERN" --grep @snapshot --grep-invert @storybook

      - name: Write image-diff summary
        if: always()
        env:
          DIFF_OUTCOME: ${{ steps.snapshots.outcome }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          mkdir -p apps/web/playwright-artifacts
          cat > apps/web/playwright-artifacts/image-diff-summary.md <<EOF
          ## Playwright image diff

          Outcome: ${DIFF_OUTCOME}

          Baselines: committed public route screenshots for desktop and mobile Chromium.

          Run: ${RUN_URL}
          EOF

      - name: Find changed baseline images
        if: always()
        env:
          BASE_REF: ${{ github.base_ref }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          set -euo pipefail
          git fetch --no-tags --depth=1 origin "${BASE_REF}:refs/remotes/origin/${BASE_REF}"
          git fetch --no-tags --depth=1 origin "pull/${PR_NUMBER}/head:refs/remotes/origin/pr-head"
          git diff --name-status "refs/remotes/origin/${BASE_REF}" "refs/remotes/origin/pr-head" -- 'apps/web/e2e/__screenshots__/desktop-chromium/*.png' 'apps/web/e2e/__screenshots__/mobile-chromium/*.png' > apps/web/playwright-artifacts/changed-baselines.txt
          cat apps/web/playwright-artifacts/changed-baselines.txt

      - name: Upload Playwright image-diff artifacts
        id: upload
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: playwright-image-diff
          if-no-files-found: error
          retention-days: 7
          path: |
            apps/web/playwright-report
            apps/web/test-results
            apps/web/playwright-artifacts
            apps/web/e2e/__screenshots__

  storybook-component-preview:
    name: Storybook Component Preview
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'storybook-component-preview')
    needs: [build-storybook, visual-selection]
    # Pinned: ubuntu-latest moved to 26.04, where this Playwright version cannot install chromium.
    # Revert to ubuntu-latest once Playwright is upgraded to a release that supports 26.04.
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    permissions:
      contents: read

    env:
      PLAYWRIGHT_CAPTURE_SCREENSHOTS: ${{ needs.visual-selection.outputs.visuals }}

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install Playwright Chromium
        working-directory: apps/web
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          pnpm exec playwright install --with-deps chromium

      - name: Run Storybook assertions and selected captures
        id: visual
        run: |
          pnpm test:storybook:visual
          node .github/scripts/visual-ci.cjs --check-captures apps/web/playwright-artifacts/storybook

      - name: Write Storybook visual summary
        if: always()
        env:
          VISUAL_OUTCOME: ${{ steps.visual.outcome }}
          CAPTURE_SELECTED: ${{ needs.visual-selection.outputs.visuals }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          mkdir -p apps/web/playwright-artifacts
          cat > apps/web/playwright-artifacts/storybook-visual-summary.md <<EOF
          ## Storybook component browser preview

          Outcome: ${VISUAL_OUTCOME}
          Review screenshot collection selected: ${CAPTURE_SELECTED}

          Browser assertions: component stories on desktop and mobile. Review PNGs are collected only when selected.

          Run: ${RUN_URL}
          EOF

      - name: Upload Storybook visual artifacts
        id: upload
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: storybook-component-preview
          if-no-files-found: error
          retention-days: 7
          path: |
            apps/web/playwright-report-storybook
            apps/web/test-results
            apps/web/playwright-artifacts

  storybook-image-diff:
    name: Storybook Image Diff
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.visuals == 'true' && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'storybook-image-diff')
    needs: [build-storybook, visual-selection]
    # Pinned: ubuntu-latest moved to 26.04, where this Playwright version cannot install chromium.
    # Revert to ubuntu-latest once Playwright is upgraded to a release that supports 26.04.
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    permissions:
      contents: read

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Install Playwright Chromium
        working-directory: apps/web
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          pnpm exec playwright install --with-deps chromium

      - name: Compare Storybook component screenshots to baselines
        id: snapshots
        run: pnpm test:storybook:snapshots

      - name: Write Storybook image-diff summary
        if: always()
        env:
          DIFF_OUTCOME: ${{ steps.snapshots.outcome }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          mkdir -p apps/web/playwright-artifacts
          cat > apps/web/playwright-artifacts/storybook-image-diff-summary.md <<EOF
          ## Storybook component image diff

          Outcome: ${DIFF_OUTCOME}

          Baselines: committed Storybook primitive screenshots for desktop and mobile Chromium.

          Run: ${RUN_URL}
          EOF

      - name: Find changed Storybook baseline images
        if: always()
        env:
          BASE_REF: ${{ github.base_ref }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          set -euo pipefail
          git fetch --no-tags --depth=1 origin "${BASE_REF}:refs/remotes/origin/${BASE_REF}"
          git fetch --no-tags --depth=1 origin "pull/${PR_NUMBER}/head:refs/remotes/origin/pr-head"
          git diff --name-status "refs/remotes/origin/${BASE_REF}" "refs/remotes/origin/pr-head" -- 'apps/web/e2e/__screenshots__/storybook-*/*.png' > apps/web/playwright-artifacts/changed-storybook-baselines.txt
          cat apps/web/playwright-artifacts/changed-storybook-baselines.txt

      - name: Upload Storybook image-diff artifacts
        id: upload
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: storybook-image-diff
          if-no-files-found: error
          retention-days: 7
          path: |
            apps/web/playwright-report-storybook
            apps/web/test-results
            apps/web/playwright-artifacts
            apps/web/e2e/__screenshots__/storybook-*

  broadcast-native-acceptance:
    name: Broadcast Candidate Acceptance
    if: github.event_name == 'pull_request' && needs.visual-selection.outputs.browsers == 'true' && github.event.pull_request.head.repo.fork == false && contains(fromJSON(needs.visual-selection.outputs.jobs || '[]'), 'broadcast-native-acceptance')
    needs: [visual-selection]
    runs-on: ubuntu-24.04
    timeout-minutes: 45
    permissions:
      contents: read
    env:
      CONVEX_LOCAL_BACKEND_VERSION: precompiled-2026-11-30-e48d3c8
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - uses: pnpm/action-setup@v6
      - uses: actions/setup-node@v6
        with:
          node-version: 24
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - name: Install native browser prerequisites
        timeout-minutes: 10
        run: |
          sudo "$(command -v node)" "${{ github.workspace }}/.github/scripts/configure-ubuntu-mirror.mjs"
          sudo apt-get update
          sudo apt-get install --no-install-recommends --yes ffmpeg
          pnpm --filter web exec playwright install --with-deps chromium
      - name: Build candidate packaged worker
        timeout-minutes: 7
        run: docker build -f workers/restream/Dockerfile -t vrdex-broadcast-native:ci .
      - name: Run isolated candidate broadcast acceptance
        timeout-minutes: 24
        env:
          BROADCAST_NATIVE_ACCEPTANCE: "true"
          BROADCAST_CANDIDATE_HEAD: ${{ github.event.pull_request.head.sha }}
          VRDEX_ENABLE_E2E_HELPERS: "true"
          VRDEX_ENABLE_E2E_AUTH_HELPERS: "true"
          VRDEX_ENABLE_E2E_CLERK_AUTH: "true"
          VRDEX_E2E_BROWSER_TOKEN: local-playwright-token
          VRDEX_E2E_CONVEX_SECRET: local-convex-e2e-secret
          CLERK_SECRET_KEY: ${{ secrets.VRDEX_HOSTED_E2E_CLERK_SECRET_KEY }}
          NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ${{ secrets.VRDEX_HOSTED_E2E_CLERK_PUBLISHABLE_KEY }}
          CLERK_JWT_ISSUER_DOMAIN: ${{ vars.VRDEX_STAGING_CLERK_JWT_ISSUER_DOMAIN }}
          PLAYWRIGHT_OUTPUT_DIR: playwright-artifacts/broadcast-native/results
          PLAYWRIGHT_HTML_REPORT_DIR: playwright-artifacts/broadcast-native/report
          PLAYWRIGHT_JSON_REPORT_FILE: playwright-artifacts/broadcast-native/results.json
        run: |
          case "$CLERK_SECRET_KEY" in sk_test_*) ;; *) exit 1 ;; esac
          node scripts/check-clerk-issuer-match.mjs --issuer "$CLERK_JWT_ISSUER_DOMAIN" --publishable-key "$NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY"
          pnpm --filter web exec playwright test event-broadcast-native.flow.spec.ts --project=desktop-chromium --workers=1
          node -e "const r=require('./apps/web/playwright-artifacts/broadcast-native/results.json');if(r.stats.expected!==1||r.stats.skipped||r.stats.unexpected)process.exit(1)"
      - name: Upload candidate broadcast evidence
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: broadcast-native-acceptance
          path: apps/web/playwright-artifacts/broadcast-native
          if-no-files-found: error
          retention-days: 7

  pr-verification-report:
    name: PR Verification Report
    if: always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false
    concurrency:
      group: pr-verification-comment-${{ github.event.pull_request.number }}
      cancel-in-progress: false
    needs:
      - lint-web
      - verify-docs
      - verify-api-mcp
      - typecheck-web
      - typecheck-backend
      - verify-backend-local
      - restream-local-checks
      - build-web
      - build-storybook
      - visual-selection
      - playwright-public-smoke
      - playwright-data-flow
      - broadcast-native-acceptance
      - playwright-hosted-data-flow
      - playwright-public-preview
      - playwright-image-diff
      - storybook-component-preview
      - storybook-image-diff
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      actions: read
      contents: read
      issues: write
      pull-requests: write

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Test PR verification report helper
        run: node --test .github/scripts/ci-scopes.test.cjs .github/scripts/visual-ci.test.cjs .github/scripts/pr-verification-report.test.cjs

      - name: Update consolidated PR verification report
        uses: actions/github-script@v9
        env:
          NEEDS_JSON: ${{ toJSON(needs) }}
        with:
          script: |
            const { updatePrVerificationReport } = require(
              "./.github/scripts/pr-verification-report.cjs",
            );
            await updatePrVerificationReport({
              core,
              context,
              github,
              needs: JSON.parse(process.env.NEEDS_JSON),
            });
