CI: Enable sccache GCS remote caching with multilevel disk cache

Enable remote Google Cloud Storage caching (gs://eigen-gitlab-ci-cache)
for sccache on GitLab SaaS runners using short-lived OAuth access tokens
vended from GitLab CI/CD variables (EIGEN_GCS_CACHE_TOKEN_RW on protected
master and EIGEN_GCS_CACHE_TOKEN_RO on Merge Requests).

- Configure SCCACHE_MULTILEVEL_CHAIN="disk,gcs" so builds hit local
  disk cache (L0) first, fall through to GCS (L1) on miss, and write
  to both disk and GCS on master (read-only GCS on MRs).
- Spawn a loopback credential process on 127.0.0.1 with readiness
  probing to serve the OAuth token to SCCACHE_GCS_CREDENTIALS_URL,
  with automatic teardown on exit.
- Purge stale .ccache/ when sccache runs (and vice versa) to prevent
  duplicate cache archives from exceeding the 5 GB runner upload cap.
- Cache .sccache/ in GitLab runner cache across Linux and Windows builds.
diff --git a/ci/build.linux.gitlab-ci.yml b/ci/build.linux.gitlab-ci.yml
index 27e6a53..c5a5e4d 100644
--- a/ci/build.linux.gitlab-ci.yml
+++ b/ci/build.linux.gitlab-ci.yml
@@ -75,12 +75,13 @@
         - .ccache-bin/
         - .sccache-bin/
       when: always
-    # Compiler object cache pool holding .ccache/.
+    # Compiler object cache pool holding .ccache/ and .sccache/.
     - key: "$EIGEN_CI_CCACHE_POOL$EIGEN_CI_CCACHE_SCOPE-ccache"
       fallback_keys:
         - "$EIGEN_CI_CCACHE_POOL-ccache"
       paths:
         - .ccache/
+        - .sccache/
       policy: $EIGEN_CI_CCACHE_POLICY
       # Push the cache even when the build fails: the retry pipeline after a
       # compile error is exactly where cache hits matter most.
diff --git a/ci/build.windows.gitlab-ci.yml b/ci/build.windows.gitlab-ci.yml
index e40d276..9c52fdf 100644
--- a/ci/build.windows.gitlab-ci.yml
+++ b/ci/build.windows.gitlab-ci.yml
@@ -65,6 +65,7 @@
     - key: "$EIGEN_CI_CCACHE_POOL-ccache"
       paths:
         - .ccache/
+        - .sccache/
       policy: $EIGEN_CI_CCACHE_POLICY
       when: always
 
diff --git a/ci/scripts/build.linux.script.sh b/ci/scripts/build.linux.script.sh
index 35c9b47..352c3d6 100755
--- a/ci/scripts/build.linux.script.sh
+++ b/ci/scripts/build.linux.script.sh
@@ -33,26 +33,63 @@
   . "${rootdir}/ci/scripts/install_compiler_cache.sh"
 
   if [[ "${EIGEN_CI_SCCACHE:-on}" != "off" && -n "${sccache_bin}" ]]; then
-    export SCCACHE_GCS_BUCKET="${EIGEN_CI_SCCACHE_GCS_BUCKET:-eigen-gitlab-ci-cache}"
-    if [[ "${CI_COMMIT_REF_PROTECTED}" == "true" ]]; then
-      export SCCACHE_GCS_RW_MODE="READ_WRITE"
-    else
-      export SCCACHE_GCS_RW_MODE="READ_ONLY"
-    fi
+    export SCCACHE_DIR="${CI_PROJECT_DIR}/.sccache"
+    export SCCACHE_CACHE_SIZE="${CCACHE_MAXSIZE:-4G}"
     export SCCACHE_BASEDIRS="${rootdir}"
     export SCCACHE_SERVER_PORT="$((4226 + (${CI_JOB_ID:-0} % 10000)))"
 
+    # Remote GCS caching via short-lived OAuth token injected from GitLab CI/CD variables:
+    # EIGEN_GCS_CACHE_TOKEN_RW (protected branch / master) or EIGEN_GCS_CACHE_TOKEN_RO (MRs)
+    gcs_token="${EIGEN_GCS_CACHE_TOKEN_RW:-${EIGEN_GCS_CACHE_TOKEN_RO:-}}"
+    sccache_cred_server_pid=""
+    if [[ -n "${gcs_token}" ]]; then
+      export SCCACHE_GCS_BUCKET="${EIGEN_CI_SCCACHE_GCS_BUCKET:-eigen-gitlab-ci-cache}"
+      export SCCACHE_MULTILEVEL_CHAIN="disk,gcs"
+      if [[ -n "${EIGEN_GCS_CACHE_TOKEN_RW}" ]]; then
+        export SCCACHE_GCS_RW_MODE="READ_WRITE"
+      else
+        export SCCACHE_GCS_RW_MODE="READ_ONLY"
+      fi
+      cred_port="$((8200 + (${CI_JOB_ID:-0} % 1000)))"
+      python3 -c "
+import http.server, json, sys
+token = sys.argv[1]
+class H(http.server.BaseHTTPRequestHandler):
+    def do_GET(self):
+        self.send_response(200)
+        self.send_header('Content-Type', 'application/json')
+        self.end_headers()
+        self.wfile.write(json.dumps({'access_token': token, 'token_type': 'Bearer', 'expires_in': 3600}).encode())
+    def log_message(self, *a): pass
+http.server.HTTPServer(('127.0.0.1', int(sys.argv[2])), H).serve_forever()
+" "${gcs_token}" "${cred_port}" &
+      sccache_cred_server_pid=$!
+      export SCCACHE_GCS_CREDENTIALS_URL="http://127.0.0.1:${cred_port}/token"
+      trap '[[ -n "${sccache_cred_server_pid}" ]] && kill "${sccache_cred_server_pid}" 2>/dev/null || true' EXIT
+
+      # Wait up to 1 second for local credential server to be ready
+      for _ in {1..20}; do
+        if curl -s "http://127.0.0.1:${cred_port}/token" >/dev/null 2>&1; then break; fi
+        sleep 0.05
+      done
+    fi
+
     if "${sccache_bin}" --start-server >/dev/null 2>&1; then
       compiler_launcher="sccache"
       "${sccache_bin}" --zero-stats >/dev/null 2>&1 || true
       launchers="-DCMAKE_C_COMPILER_LAUNCHER=${sccache_bin} -DCMAKE_CXX_COMPILER_LAUNCHER=${sccache_bin}"
+      # Incompatible cache formats: purge restored .ccache/ so the uploaded cache
+      # archive only holds .sccache/ and stays strictly below the 5 GB runner cap.
+      rm -rf "${rootdir}/.ccache"
     else
       echo "Notice: sccache server failed to start (check GCS credentials/network); falling back to ccache."
+      [[ -n "${sccache_cred_server_pid}" ]] && kill "${sccache_cred_server_pid}" 2>/dev/null || true
     fi
   fi
 
   if [[ -z "${compiler_launcher}" && -n "${ccache_bin}" ]]; then
     compiler_launcher="ccache"
+    rm -rf "${rootdir}/.sccache"
     launchers="-DCMAKE_C_COMPILER_LAUNCHER=${ccache_bin} -DCMAKE_CXX_COMPILER_LAUNCHER=${ccache_bin}"
     # Log stats per job via CCACHE_STATSLOG rather than global --zero-stats /
     # --show-stats so concurrent jobs sharing a host CCACHE_DIR do not reset or
@@ -71,6 +108,7 @@
   if [[ "${compiler_launcher}" == "sccache" && -n "${sccache_bin}" ]]; then
     "${sccache_bin}" --show-stats 2>&1 || true
     "${sccache_bin}" --stop-server >/dev/null 2>&1 || true
+    [[ -n "${sccache_cred_server_pid}" ]] && kill "${sccache_cred_server_pid}" 2>/dev/null || true
   elif [[ "${compiler_launcher}" == "ccache" && -n "${ccache_bin}" ]]; then
     if [[ -n "${CCACHE_STATSLOG}" ]]; then
       "${ccache_bin}" --show-log-stats
diff --git a/ci/scripts/build.windows.script.ps1 b/ci/scripts/build.windows.script.ps1
index 2a3755e..d5924d5 100644
--- a/ci/scripts/build.windows.script.ps1
+++ b/ci/scripts/build.windows.script.ps1
@@ -85,13 +85,51 @@
 
   # 1. Try starting sccache server if available
   if ($sccache_exe) {
-    $env:SCCACHE_GCS_BUCKET = if ($env:EIGEN_CI_SCCACHE_GCS_BUCKET) { $env:EIGEN_CI_SCCACHE_GCS_BUCKET } else { "eigen-gitlab-ci-cache" }
-    $env:SCCACHE_GCS_RW_MODE = if ($env:CI_COMMIT_REF_PROTECTED -eq "true") { "READ_WRITE" } else { "READ_ONLY" }
+    $env:SCCACHE_DIR = Join-Path $env:CI_PROJECT_DIR ".sccache"
+    $env:SCCACHE_CACHE_SIZE = if ($env:EIGEN_CI_CCACHE_MAXSIZE) { $env:EIGEN_CI_CCACHE_MAXSIZE } else { "4G" }
     # Rewrite paths relative to rootdir for cross-runner / cross-directory cache hits.
     $env:SCCACHE_BASEDIRS = $rootdir
     # Isolate daemon port per runner slot to avoid port collisions and process cross-kill.
     $env:SCCACHE_SERVER_PORT = [string](4226 + ([int]($env:CI_JOB_ID ? $env:CI_JOB_ID : 0) % 10000))
 
+    $gcs_token = if ($env:EIGEN_GCS_CACHE_TOKEN_RW) { $env:EIGEN_GCS_CACHE_TOKEN_RW } else { $env:EIGEN_GCS_CACHE_TOKEN_RO }
+    $cred_server_job = $null
+    if ($gcs_token) {
+      $env:SCCACHE_GCS_BUCKET = if ($env:EIGEN_CI_SCCACHE_GCS_BUCKET) { $env:EIGEN_CI_SCCACHE_GCS_BUCKET } else { "eigen-gitlab-ci-cache" }
+      $env:SCCACHE_MULTILEVEL_CHAIN = "disk,gcs"
+      if ($env:EIGEN_GCS_CACHE_TOKEN_RW) {
+        $env:SCCACHE_GCS_RW_MODE = "READ_WRITE"
+      } else {
+        $env:SCCACHE_GCS_RW_MODE = "READ_ONLY"
+      }
+      $cred_port = [string](8200 + ([int]($env:CI_JOB_ID ? $env:CI_JOB_ID : 0) % 1000))
+      $cred_server_job = Start-Job -ScriptBlock {
+        param($tok, $p)
+        $listener = New-Object System.Net.HttpListener
+        $listener.Prefixes.Add("http://127.0.0.1:$p/")
+        $listener.Start()
+        while ($listener.IsListening) {
+          $ctx = $listener.GetContext()
+          $resp = $ctx.Response
+          $resp.ContentType = "application/json"
+          $body = [System.Text.Encoding]::UTF8.GetBytes("{`"access_token`":`"$tok`",`"token_type`":`"Bearer`",`"expires_in`":3600}")
+          $resp.ContentLength64 = $body.Length
+          $resp.OutputStream.Write($body, 0, $body.Length)
+          $resp.Close()
+        }
+      } -ArgumentList $gcs_token, $cred_port
+      $env:SCCACHE_GCS_CREDENTIALS_URL = "http://127.0.0.1:$cred_port/token"
+
+      # Wait up to 1 second for local credential server to be ready
+      for ($i = 0; $i -lt 20; $i++) {
+        try {
+          $res = Invoke-WebRequest -Uri "http://127.0.0.1:$cred_port/token" -UseBasicParsing -TimeoutSec 1
+          if ($res.StatusCode -eq 200) { break }
+        } catch {}
+        Start-Sleep -Milliseconds 50
+      }
+    }
+
     & $sccache_exe --start-server | Out-Null
     if ($LASTEXITCODE -eq 0) {
       $compiler_launcher = "sccache"
@@ -99,14 +137,24 @@
       $sccache_cmake = $sccache_exe -replace '\\', '/'
       $launchers = "-DCMAKE_C_COMPILER_LAUNCHER=${sccache_cmake}",
                    "-DCMAKE_CXX_COMPILER_LAUNCHER=${sccache_cmake}"
+      # Incompatible cache formats: purge restored .ccache\ so the uploaded cache
+      # archive only holds .sccache\ and stays strictly below the 5 GB runner cap.
+      $old_ccache = Join-Path $rootdir ".ccache"
+      if (Test-Path $old_ccache) { Remove-Item -Recurse -Force $old_ccache }
     } else {
       Write-Warning "sccache server failed to start (check GCS credentials/network); falling back to ccache."
+      if ($cred_server_job) {
+        Stop-Job $cred_server_job -ErrorAction SilentlyContinue
+        Remove-Job $cred_server_job -ErrorAction SilentlyContinue
+      }
     }
   }
 
   # 2. Fall back to ccache if sccache is unavailable or failed to start
   if ((-not $compiler_launcher) -and $ccache_exe) {
     $compiler_launcher = "ccache"
+    $old_sccache = Join-Path $rootdir ".sccache"
+    if (Test-Path $old_sccache) { Remove-Item -Recurse -Force $old_sccache }
     # EIGEN_CI_CCACHE_* provide the YAML fallback defaults.  A runner may explicitly
     # set standard CCACHE_* variables (e.g. to a persistent host directory) in
     # config.toml without being overridden by the YAML template.
@@ -204,6 +252,10 @@
 if ($compiler_launcher -eq "sccache" -and $sccache_exe) {
   & $sccache_exe --show-stats
   & $sccache_exe --stop-server | Out-Null
+  if ($cred_server_job) {
+    Stop-Job $cred_server_job -ErrorAction SilentlyContinue
+    Remove-Job $cred_server_job -ErrorAction SilentlyContinue
+  }
 } elseif ($compiler_launcher -eq "ccache" -and $ccache_exe) {
   & $ccache_exe --show-log-stats
   if (Test-Path $env:CCACHE_STATSLOG) {