# 2-Minute GitHub Actions BYOV Verifier Setup

Turn any GitHub repository (TypeScript, Python, Rust, Go, Solidity/Foundry, C++, or polyglot) into an airlocked multiplayer Caisson workspace using your own GitHub Actions runners — **zero Docker image builds, zero Modal cache baking, and $0 platform compute cost**.

## Step 1 — Commit `.github/workflows/caisson-verify.yml`

Create `.github/workflows/caisson-verify.yml` on your default branch with the exact template below:

```yaml
# .github/workflows/caisson-verify.yml
# Caisson 1-File GitHub Actions BYOV Webhook Verifier (Epic 8 / L3-1)
#
# 2-Minute Setup:
#   1. Commit this file to `.github/workflows/caisson-verify.yml` on your default branch.
#   2. (Optional) Set repository variable `CAISSON_TEST_COMMAND` (e.g. `npm test`, `pytest`,
#      `cargo test`, `go test ./...`, `forge test`) or edit `DEFAULT_TEST_COMMAND` below.
#   3. Create a fine-grained GitHub PAT with `Contents: Read & Write` (required for
#      `repository_dispatch`) and register your workspace at https://caisson.tools/new.
#
# Security guarantees:
#   - Minimal permissions (`contents: read`) — cannot push to branches or read repo secrets.
#   - Masks the single-use Caisson `callback_token` before any command runs.
#   - Rejects symlinks, `..` traversal, `.github/` edits, and workspace `protected_paths`.
#   - Overlays frozen acceptance tests AFTER candidate submission files so tests cannot be weakened.
#   - Non-zero test exit codes NEVER emit `status: "pass"`.

name: Caisson BYOV Verifier

on:
  repository_dispatch:
    types: [caisson_verify]

permissions:
  contents: read

concurrency:
  group: caisson-verify-${{ github.event.client_payload.run_id }}
  cancel-in-progress: false

env:
  # Override via GitHub repository variable `CAISSON_TEST_COMMAND` or edit this default:
  DEFAULT_TEST_COMMAND: ""

jobs:
  verify:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - name: Mask single-use callback token & validate payload
        id: init
        env:
          RUN_ID: ${{ github.event.client_payload.run_id }}
          BUNDLE_URL: ${{ github.event.client_payload.bundle_url }}
          CALLBACK_URL: ${{ github.event.client_payload.callback_url }}
          CALLBACK_TOKEN: ${{ github.event.client_payload.callback_token }}
        run: |
          set -euo pipefail
          if [ -n "${CALLBACK_TOKEN}" ]; then
            echo "::add-mask::${CALLBACK_TOKEN}"
          fi
          if [ -z "${RUN_ID}" ] || [ -z "${BUNDLE_URL}" ] || [ -z "${CALLBACK_URL}" ] || [ -z "${CALLBACK_TOKEN}" ]; then
            echo "Missing required Caisson client_payload fields (run_id, bundle_url, callback_url, callback_token)."
            exit 1
          fi
          echo "start_ms=$(date +%s%3N)" >> "$GITHUB_OUTPUT"

      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Fetch Caisson bundle & apply safe overlay
        id: overlay
        env:
          BUNDLE_URL: ${{ github.event.client_payload.bundle_url }}
          CALLBACK_TOKEN: ${{ github.event.client_payload.callback_token }}
          PROTECTED_PATHS_JSON: ${{ toJSON(github.event.client_payload.protected_paths) }}
        run: |
          set -euo pipefail
          BUNDLE_DIR="${RUNNER_TEMP}/caisson-bundle"
          LOG_FILE="${RUNNER_TEMP}/caisson-verify.log"
          rm -rf "${BUNDLE_DIR}"
          mkdir -p "${BUNDLE_DIR}"
          : > "${LOG_FILE}"

          curl -fsSL \
            -H "Authorization: Bearer ${CALLBACK_TOKEN}" \
            -H "Accept: application/gzip" \
            "${BUNDLE_URL}" \
            -o "${RUNNER_TEMP}/bundle.tar.gz"

          tar -xzf "${RUNNER_TEMP}/bundle.tar.gz" -C "${BUNDLE_DIR}"

          python3 - "${BUNDLE_DIR}" "${PWD}" <<'PY'
          import json
          import os
          import shutil
          import sys
          from pathlib import Path

          bundle_dir = Path(sys.argv[1]).resolve()
          repo_root = Path(sys.argv[2]).resolve()
          submission_dir = bundle_dir / "submission"
          target_dir = bundle_dir / "target"
          deps_dir = bundle_dir / "deps"

          try:
              protected = json.loads(os.environ.get("PROTECTED_PATHS_JSON") or "[]")
          except Exception:
              protected = []
          if not isinstance(protected, list):
              protected = []
          protected = list(dict.fromkeys([
              ".git",
              ".github/",
              "workspace.yaml",
              "env/",
              "spec/",
              *[str(p) for p in protected if isinstance(p, str) and p.strip()],
          ]))

          def is_protected(rel: str) -> bool:
              norm = rel.replace("\\", "/").lstrip("/")
              for pref in protected:
                  p = pref.replace("\\", "/").lstrip("/")
                  if p.endswith("/"):
                      if norm.startswith(p):
                          return True
                  else:
                      if norm == p or norm.startswith(p + "/"):
                          return True
              return False

          if not submission_dir.is_dir():
              raise SystemExit("Bundle missing submission/ directory")

          violations = []
          copied_files = []
          for root, dirs, files in os.walk(submission_dir):
              root_path = Path(root)
              for d in list(dirs):
                  if (root_path / d).is_symlink():
                      raise SystemExit(f"REJECTED: symlink directory in submission: {d}")
              for fname in files:
                  src = root_path / fname
                  if src.is_symlink():
                      raise SystemExit(f"REJECTED: symlink file in submission: {fname}")
                  rel = src.relative_to(submission_dir).as_posix()
                  if rel.startswith("/") or ".." in Path(rel).parts:
                      raise SystemExit(f"REJECTED: unsafe submission path: {rel}")
                  if is_protected(rel):
                      violations.append(rel)
                      continue
                  dest = (repo_root / rel).resolve()
                  if not str(dest).startswith(str(repo_root) + os.sep):
                      raise SystemExit(f"REJECTED: path escapes repo root: {rel}")
                  dest.parent.mkdir(parents=True, exist_ok=True)
                  shutil.copy2(src, dest)
                  copied_files.append(rel)

          if violations:
              raise SystemExit(f"REJECTED [protected_path]: {', '.join(violations)}")

          # Overlay frozen acceptance tests / target spec AFTER submission files so tests are immutable.
          manifest_path = bundle_dir / "manifest.json"
          manifest = json.loads(manifest_path.read_text("utf-8")) if manifest_path.is_file() else {}
          target_spec_path = manifest.get("target_spec_path")
          if target_dir.is_dir():
              for root, _, files in os.walk(target_dir):
                  for fname in files:
                      src = Path(root) / fname
                      if src.is_symlink():
                          continue
                      rel = src.relative_to(target_dir).as_posix()
                      frozen_dest = repo_root / ".caisson_target" / rel
                      frozen_dest.parent.mkdir(parents=True, exist_ok=True)
                      shutil.copy2(src, frozen_dest)
                      if isinstance(target_spec_path, str) and target_spec_path and not target_spec_path.startswith("/") and ".." not in Path(target_spec_path).parts and Path(target_spec_path).name == fname:
                          repo_spec_dest = (repo_root / target_spec_path).resolve()
                          if str(repo_spec_dest).startswith(str(repo_root) + os.sep):
                              repo_spec_dest.parent.mkdir(parents=True, exist_ok=True)
                              shutil.copy2(src, repo_spec_dest)

          print(f"Overlay applied ({len(copied_files)} files): {', '.join(copied_files)}")
          if deps_dir.is_dir():
              print(f"Mounted dependencies available at CAISSON_DEPS_DIR={deps_dir}")
          PY

          if [ -d "${BUNDLE_DIR}/deps" ]; then
            echo "CAISSON_DEPS_DIR=${BUNDLE_DIR}/deps" >> "$GITHUB_ENV"
          fi
          echo "CAISSON_TARGET_DIR=${PWD}/.caisson_target" >> "$GITHUB_ENV"
          echo "overlay_ok=true" >> "$GITHUB_OUTPUT"

      - name: Run repository CI / acceptance tests
        id: verify_cmd
        if: steps.overlay.outputs.overlay_ok == 'true'
        env:
          CONFIGURED_CMD: ${{ vars.CAISSON_TEST_COMMAND || env.DEFAULT_TEST_COMMAND }}
        run: |
          set +e
          LOG_FILE="${RUNNER_TEMP}/caisson-verify.log"
          CMD="${CONFIGURED_CMD}"

          if [ -z "${CMD}" ]; then
            if [ -f package.json ]; then
              if [ -f package-lock.json ]; then npm ci >> "${LOG_FILE}" 2>&1; else npm install >> "${LOG_FILE}" 2>&1; fi
              CMD="npm test"
            elif [ -f Cargo.toml ]; then
              CMD="cargo test"
            elif [ -f go.mod ]; then
              CMD="go test ./..."
            elif [ -f foundry.toml ]; then
              CMD="forge test"
            elif [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f requirements.txt ]; then
              CMD="pytest"
            else
              echo "No test command configured. Set repository variable CAISSON_TEST_COMMAND." >> "${LOG_FILE}"
              echo "exit_code=2" >> "$GITHUB_OUTPUT"
              echo "test_command=unconfigured" >> "$GITHUB_OUTPUT"
              exit 0
            fi
          fi

          echo "$ ${CMD}" >> "${LOG_FILE}"
          bash -o pipefail -c "${CMD}" >> "${LOG_FILE}" 2>&1
          EXIT_CODE=$?
          echo "exit_code=${EXIT_CODE}" >> "$GITHUB_OUTPUT"
          echo "test_command=${CMD}" >> "$GITHUB_OUTPUT"
          # Do not fail the step here so the callback step always receives exact exit_code & logs.
          exit 0

      - name: Post canonical VerifierResult callback to Caisson
        if: always() && env.CALLBACK_URL != '' && env.CALLBACK_TOKEN != ''
        env:
          RUN_ID: ${{ github.event.client_payload.run_id }}
          CALLBACK_URL: ${{ github.event.client_payload.callback_url }}
          CALLBACK_TOKEN: ${{ github.event.client_payload.callback_token }}
          OVERLAY_OK: ${{ steps.overlay.outputs.overlay_ok }}
          TEST_EXIT_CODE: ${{ steps.verify_cmd.outputs.exit_code }}
          TEST_COMMAND: ${{ steps.verify_cmd.outputs.test_command }}
          START_MS: ${{ steps.init.outputs.start_ms }}
          GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          set -euo pipefail
          LOG_FILE="${RUNNER_TEMP}/caisson-verify.log"
          PAYLOAD_FILE="${RUNNER_TEMP}/verifier-result.json"

          python3 - "${LOG_FILE}" "${PAYLOAD_FILE}" <<'PY'
          import json
          import os
          import sys
          import time
          from pathlib import Path

          log_path = Path(sys.argv[1])
          out_path = Path(sys.argv[2])

          overlay_ok = os.environ.get("OVERLAY_OK") == "true"
          raw_exit = os.environ.get("TEST_EXIT_CODE", "")
          test_cmd = os.environ.get("TEST_COMMAND", "")
          start_ms = int(os.environ.get("START_MS") or "0")
          now_ms = int(time.time() * 1000)
          duration_ms = max(0, now_ms - start_ms) if start_ms > 0 else 0

          raw_logs = log_path.read_text("utf-8", errors="replace") if log_path.is_file() else ""
          # Bound logs to <= 60 KiB (VerifierResultSchema enforces max 65536 chars)
          if len(raw_logs) > 60000:
              raw_logs = "...[truncated]...\n" + raw_logs[-59950:]

          if not overlay_ok:
              status = "fail"
              score = 0.0
              exit_code = -1
              logs = raw_logs or "Bundle download or protected-path overlay validation failed."
              deterministic = True
          elif raw_exit == "0":
              status = "pass"
              score = 1.0
              exit_code = 0
              logs = raw_logs or "VERIFIED: repository CI/test command passed."
              deterministic = True
          elif raw_exit.isdigit() or (raw_exit.startswith("-") and raw_exit[1:].isdigit()):
              status = "fail"
              score = 0.0
              exit_code = int(raw_exit)
              logs = raw_logs or f"Test command failed with exit code {exit_code}."
              deterministic = True
          else:
              status = "error"
              score = 0.0
              exit_code = -1
              logs = raw_logs or "GitHub Actions runner terminated before test command completed."
              deterministic = False

          result = {
              "status": status,
              "score": score,
              "metrics": {
                  "duration_ms": duration_ms,
                  "exit_code": exit_code,
                  "test_command": test_cmd,
                  "github_run_id": os.environ.get("GITHUB_RUN_ID", ""),
                  "github_run_url": os.environ.get("GITHUB_RUN_URL", ""),
              },
              "logs": logs,
              "verifier_version": "github-actions-byov@v1",
              "deterministic": deterministic,
          }
          out_path.write_text(json.dumps(result), "utf-8")
          PY

          curl -fsSL -X POST "${CALLBACK_URL}" \
            -H "Authorization: Bearer ${CALLBACK_TOKEN}" \
            -H "Content-Type: application/json" \
            --data-binary "@${PAYLOAD_FILE}"
```

## Step 2 — Configure Your Test Command (Optional)

In GitHub (**Settings → Secrets and variables → Actions → Variables**), add `CAISSON_TEST_COMMAND` (for example `npm test`, `pytest -q`, `cargo test`, `go test ./...`, or `forge test`), or edit `DEFAULT_TEST_COMMAND` directly in the YAML file.

If left blank, the workflow automatically detects `package.json`, `Cargo.toml`, `go.mod`, `foundry.toml`, or `pyproject.toml`.

## Step 3 — Create a Fine-Grained GitHub PAT

Create a fine-grained Personal Access Token scoped **only** to your repository with **Contents: Read & Write** (required by GitHub to invoke `POST /repos/{owner}/{repo}/dispatches`).

## Step 4 — Create Workspace & Invite Teammates

- **Web Wizard:** Open [https://caisson.tools/new](https://caisson.tools/new), select **Bring Your Own Repo (GitHub Actions BYOV)**, enter `owner/repo` + PAT, and generate scoped Teammate Invite Cards in 1 click.
- **Remote CLI:**
  ```bash
  npx -y caisson-cli workspace create \
    --url https://api.caisson.tools --token <YOUR_CAISSON_KEY> \
    --slug my-repo --title "My Repo Multiplayer" \
    --merge-target repo_root --verifier-type webhook \
    --github-repo owner/repo --github-token <GITHUB_PAT> \
    --env "node:22-ts:5.8" --protected-path "tests/" --protected-path ".github/"
  ```

## Dispatch Payload & Security Invariants

Caisson dispatches `event_type: "caisson_verify"` to `POST https://api.github.com/repos/{owner}/{repo}/dispatches` with:
- `client_payload.run_id`, `bundle_url` (`/v1/runs/:runId/bundle?format=tar.gz`), `callback_url`, single-use `callback_token`, and `protected_paths`.
- The workflow runs with `permissions: { contents: read }`, masks `callback_token`, rejects symlinks/traversal/`.github/`/protected-path mutations, overlays frozen acceptance tests *after* submission files, and posts canonical `VerifierResult` JSON to `/v1/verifications/:runId/callback`.
