name: CLI 0.15.0 interaction endpoint diagnosis

on:
  push:
    branches: [codex/cli-0150-phase-diagnostics]
    paths:
      - .github/workflows/cli-interaction-endpoints.yml
      - .github/release-diagnostics/interaction-endpoints/**

permissions:
  contents: read

env:
  CONTROL_SHA: b0c894fe71f927827b0a30ea9f366e3ad04f24d3
  CANDIDATE_SHA: 996b8c10b0627d6f9c9e6a03e1800900bec079c4
  UV_EXCLUDE_NEWER: "14 days"

jobs:
  release-comparison:
    runs-on: ubuntu-24.04
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          fetch-depth: 0
          persist-credentials: false
      - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
        with:
          version: "0.11.26"
          checksum: "6426a73c3837e6e2483ee344cbc00f36394d179afcba6183cb77437e67db4af0"
          python-version: "3.13"
          enable-cache: false
      - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: "24.18.0"
      - name: Build exact wheels and public corpus
        id: build_exact_wheels
        shell: bash
        run: |
          set -euo pipefail
          test "$(git rev-parse 'v0.14.0^{commit}')" = "$CONTROL_SHA"
          test -z "$(git status --porcelain)"
          command -v xvfb-run
          google-chrome --version | grep -E '^Google Chrome 158[.]0[.]8127[.]36 *$'
          support="$RUNNER_TEMP/mb-release-comparison"
          mkdir -p "$support"/{tmp,uv,cargo,evidence}
          export TMPDIR="$support/tmp" UV_CACHE_DIR="$support/uv" CARGO_TARGET_DIR="$support/cargo"
          git worktree add --detach "$support/control" "$CONTROL_SHA"
          git worktree add --detach "$support/candidate" "$CANDIDATE_SHA"
          df -h "$support"
          for side in control candidate; do
            (
              cd "$support/$side"
              uv --config-file uv.toml sync --locked --all-extras --all-groups
              uv --config-file uv.toml build --clear --no-build-isolation --wheel \
                --out-dir "$support/$side-wheel"
              wheel=("$support/$side-wheel"/metabrowser-*.whl)
              test "${#wheel[@]}" -eq 1
              UV_PROJECT_ENVIRONMENT="$support/$side-env" \
                uv --config-file uv.toml sync --locked --no-dev --no-install-project
              uv --config-file uv.toml pip install --no-deps --compile-bytecode \
                --python "$support/$side-env/bin/python" "${wheel[0]}"
              uv --config-file uv.toml pip check --python "$support/$side-env/bin/python"
              expected="$(basename "${wheel[0]}" | cut -d- -f2)"
              test "$("$support/$side-env/bin/metab" --version)" = "metab $expected"
              printf '%s\n' "${wheel[0]}" > "$support/$side.wheel-path"
              sha256sum "${wheel[0]}" | awk '{print $1}' > "$support/evidence/$side.sha256"
              uv --config-file uv.toml pip list --format json \
                --python "$support/$side-env/bin/python" > "$support/evidence/$side-dependencies.json"
            )
          done
          grep -Fx b1906784ae60fd6de276af6d03c40399a2dc86f27c093225df9135471f1a18fb "$support/evidence/control.sha256"
          grep -Fx eb4e01ef0a25ac604c00cc330a5d76cb0e541fc6b7f188fcd7a3621c773abf00 "$support/evidence/candidate.sha256"
          cd "$support/candidate"
          uv --config-file uv.toml export --frozen --no-dev --no-emit-project \
            --output-file "$support/browser-constraints.txt"
          uv --config-file uv.toml venv "$support/browser-env"
          control_wheel="$(cat "$support/control.wheel-path")"
          uv --config-file uv.toml pip install --compile-bytecode \
            --python "$support/browser-env/bin/python" \
            --constraints "$support/browser-constraints.txt" "$control_wheel"
          uv --config-file uv.toml pip check --python "$support/browser-env/bin/python"
          npm ci
          uv --config-file uv.toml run --frozen python -c \
            'import sys; from pathlib import Path; from devtools.bench_serving import build_project_corpus; print(build_project_corpus(Path(sys.argv[1]), 10))' \
            "$support/project-10"
          test -z "$(git status --porcelain)"
          cp "$support/project-10/.bench-corpus.json" "$support/evidence/corpus.json"
      - name: Trace exact interaction endpoints across A/A and A/B
        shell: bash
        run: |
          set -euo pipefail
          support="$RUNNER_TEMP/mb-release-comparison"
          results="$support/evidence"
          driver="$GITHUB_WORKSPACE/.github/release-diagnostics/interaction-endpoints"
          (cd "$driver" && sha256sum capture-frame-trace.cjs frame-trace-hook.cjs PROTOCOL.md) > "$results/frame-driver.sha256"
          export TMPDIR="$support/tmp" UV_CACHE_DIR="$support/uv" CARGO_TARGET_DIR="$support/cargo"
          export XDG_CACHE_HOME="$support/cache" XDG_CONFIG_HOME="$support/config"
          cd "$support/candidate"
          bench=(uv --config-file uv.toml run --frozen python explorations/performance-loop/run.py)
          ledger=explorations/performance-loop/results/runs.jsonl
          pending=explorations/performance-loop/results/pending.json
          capture_probe="$support/timed-profile-probe.js"
          node - "$PWD/explorations/performance-loop/probe.js" "$capture_probe" <<'JAVASCRIPT'
          const fs = require("node:fs");
          const [input, output] = process.argv.slice(2);
          let source = fs.readFileSync(input, "utf8");
          const snapshot = "  const perf = profiler ? profiler.snapshot() : { raw_measure: [], label_totals: [] };";
          const origin = "    measurement_origin: location.origin,";
          if (source.split(snapshot).length !== 2 || source.split(origin).length !== 2) throw Error("Profile probe anchors changed");
          source = source.replace(snapshot, "  const snapshotStarted = performance.now();\n" + snapshot + "\n  const snapshotFinished = performance.now();");
          source = source.replace(origin, origin + "\n    diagnostic_snapshot: {started_ms: snapshotStarted, finished_ms: snapshotFinished},");
          fs.writeFileSync(output, source);
          JAVASCRIPT
          sha256sum "$capture_probe" > "$results/timed-profile-probe.sha256"
          control_wheel="$(cat "$support/control.wheel-path")"
          candidate_wheel="$(cat "$support/candidate.wheel-path")"
          {
            uname -srmo
            lscpu | grep -E '^(CPU\(s\)|Model name|Architecture):'
            node --version
            google-chrome --version
            printf 'ImageOS=%s ImageVersion=%s\n' "${ImageOS:-unknown}" "${ImageVersion:-unknown}"
            printf 'control=%s\ncandidate=%s\n' "$CONTROL_SHA" "$CANDIDATE_SHA"
            printf 'diagnostic_driver_commit=%s\n' "$(git -C "$GITHUB_WORKSPACE" rev-parse HEAD)"
          } > "$results/host.txt"

          wait_for_idle() {
            local attempt
            for attempt in {1..24}; do
              if awk '$1 < 1.1 {pass=1} END {exit !pass}' /proc/loadavg; then
                cat /proc/loadavg >> "$results/load-before-runs.txt"
                return 0
              fi
              sleep 5
            done
            printf 'Unable to reach 1-minute load below 1.1.\n' >&2
            return 1
          }

          "${bench[@]}" count "$support/project-10" > "$results/count.txt"
          count="$(awk '/^files / {gsub(/,/, "", $2); print $2}' "$results/count.txt")"
          [[ "$count" =~ ^[1-9][0-9]*$ ]]

          launch() {
            local mode="$1" condition="$2" ref="$CANDIDATE_SHA" wheel="$candidate_wheel" expected label
            if [[ "$condition" == control ]]; then
              ref="$CONTROL_SHA"
              wheel="$control_wheel"
            fi
            label="frame-trace-${CANDIDATE_SHA:0:12}-$mode-$condition"
            uv --config-file uv.toml pip install --no-deps --compile-bytecode \
              --reinstall-package metabrowser --python "$support/browser-env/bin/python" "$wheel"
            uv --config-file uv.toml pip check --python "$support/browser-env/bin/python"
            expected="$(basename "$wheel" | cut -d- -f2)"
            test "$("$support/browser-env/bin/metab" --version)" = "metab $expected"
            "${bench[@]}" serve --metab "$support/browser-env/bin/metab" \
              --artifact "$wheel" --build-ref "$ref" \
              --tree "$support/project-10" --files "$count" --exp exp-142 --label "$label"
          }

          capture() {
            local block="$1" mode="$2" condition="$3" slot="$4" attempt="$5"
            local stem="$results/b$block-$mode-$condition-attempt$attempt"
            local corpus profile_url origin probe ready=0 capture_status=0 record_status=0 state=refused
            capture_admitted=0
            wait_for_idle
            launch "$mode" "$condition" > "$stem.serve.log" 2>&1
            corpus="$(jq -er .corpus_fingerprint_baseline "$pending")"
            profile_url="$(jq -er .url "$pending")"
            origin="$(jq -er .measurement_origin "$pending")"
            for probe in {1..15}; do
              if curl --silent --show-error --fail --output /dev/null --max-time 2 "$origin/api/routes"; then ready=1; break; fi
              sleep 0.05
            done
            test "$ready" = 1
            jq -n --arg mode "$mode" --arg condition "$condition" --arg pending "$PWD/$pending" \
              --arg corpus "$corpus" --argjson pair "$block" --argjson slot "$slot" \
              '{mode:$mode,condition:$condition,pending:$pending,corpus_fingerprint:$corpus,pair:$pair,slot:$slot}' \
              > "$stem.context.json"
            FRAME_TRACE_CONTEXT="$stem.context.json" \
              xvfb-run -a -s '-screen 0 1920x1200x24' node "$driver/capture-frame-trace.cjs" \
                --headed --chrome "$(command -v google-chrome)" --width 1600 --height 1040 \
                --probe "$capture_probe" --url "$profile_url" --output "$stem.json" \
                > "$stem.log" 2>&1 || capture_status=$?
            if (( capture_status == 0 )); then
              jq 'del(.diagnostic_snapshot)' "$stem.json" > "$support/record.json"
              "${bench[@]}" record --json-file "$support/record.json" >> "$stem.log" 2>&1 || record_status=$?
              if grep -q '^recorded ' "$stem.log" &&
                 jq -e 'select(.status == "retained" and .clock_alignment.status == "aligned")' "$stem.json.frame-trace.json" > /dev/null; then
                state=recorded
              fi
            fi
            printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
              "$block" "$mode" "$condition" "$slot" "$attempt" "$state" "$capture_status" "$record_status" >> "$results/capture-manifest.tsv"
            if [[ "$state" != recorded ]]; then
              "${bench[@]}" fingerprint --timeout 120 > "$stem.fingerprint.log" 2>&1
            else
              capture_admitted=1
            fi
          }

          wait_for_idle
          launch ab control > "$results/serve-warmup.log" 2>&1
          "${bench[@]}" fingerprint >> "$results/serve-warmup.log" 2>&1
          printf 'block\tmode\tcondition\tslot\tattempt\tstate\tcapture_exit\trecord_exit\n' > "$results/capture-manifest.tsv"
          printf 'block\tmode\tattempt\tstate\n' > "$results/pair-manifest.tsv"
          failures=0
          for block in {1..2}; do
            modes=(ab aa)
            if (( block % 2 == 0 )); then modes=(aa ab); fi
            for mode in "${modes[@]}"; do
              if [[ "$mode" == ab ]]; then
                sides=(control candidate)
              else
                sides=(candidate-a candidate-b)
              fi
              if (( block % 2 == 0 )); then sides=("${sides[1]}" "${sides[0]}"); fi
              pair_completed=0
              for attempt in 1 2; do
                admitted=0
                for slot in 1 2; do
                  capture "$block" "$mode" "${sides[slot - 1]}" "$slot" "$attempt"
                  admitted=$((admitted + capture_admitted))
                done
                state=refused
                if (( admitted == 2 )); then state=recorded; pair_completed=1; fi
                printf '%s\t%s\t%s\t%s\n' "$block" "$mode" "$attempt" "$state" >> "$results/pair-manifest.tsv"
                if (( pair_completed == 1 )); then break; fi
              done
              if (( pair_completed == 0 )); then failures=$((failures + 1)); fi
            done
          done
          jq -c --arg prefix "frame-trace-${CANDIDATE_SHA:0:12}-" 'select(.label | startswith($prefix))' \
            "$ledger" > "$results/browser-ledger.jsonl"
          printf 'failed_pairs=%s\n' "$failures" > "$results/status.txt"
          test "$failures" = 0
      - name: Upload diagnostic evidence
        if: always()
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: cli-0150-exp-142-${{ env.CANDIDATE_SHA }}
          path: ${{ runner.temp }}/mb-release-comparison/evidence
          if-no-files-found: warn
          retention-days: 7
