# Example: Add a trust gate to your GitHub Actions CI pipeline.
#
# This step evaluates whether an AI-generated change should be auto-merged
# or requires human review based on confidence scoring.
#
# Add this step to any workflow that uses AI-generated code (Copilot,
# Claude Code, Cursor, etc.)

name: Trust Gate

on:
  pull_request:
    branches: [main]

jobs:
  trust-gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv pip install cognilateral-trust

      - name: Evaluate PR trust
        run: |
          # Score based on PR characteristics
          # - AI-generated PRs start at 0.6 confidence
          # - Irreversible changes (migrations, deletes) get flagged
          # - Changes touching external APIs get flagged

          CONFIDENCE=0.6
          FLAGS=""

          # Check for irreversible patterns
          if git diff --name-only origin/main | grep -qE "migration|delete|drop"; then
            FLAGS="$FLAGS --irreversible"
          fi

          # Check for external system changes
          if git diff --name-only origin/main | grep -qE "api_key|webhook|deploy|infra"; then
            FLAGS="$FLAGS --external"
          fi

          echo "Evaluating trust: confidence=$CONFIDENCE flags=$FLAGS"
          RESULT=$(trust-check $CONFIDENCE $FLAGS --json)
          echo "$RESULT" | jq .

          VERDICT=$(echo "$RESULT" | jq -r .verdict)
          if [ "$VERDICT" = "ESCALATE" ]; then
            echo "::warning::Trust gate: ESCALATE — this PR needs human review"
            REASONS=$(echo "$RESULT" | jq -r '.reasons | join(", ")')
            echo "Reasons: $REASONS"
            # Don't fail the build — just flag it
            echo "TRUST_VERDICT=ESCALATE" >> "$GITHUB_ENV"
          else
            echo "Trust gate: ACT — confidence sufficient for auto-merge"
            echo "TRUST_VERDICT=ACT" >> "$GITHUB_ENV"
          fi

      - name: Comment trust evaluation on PR
        if: env.TRUST_VERDICT == 'ESCALATE'
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '**Trust Gate: ESCALATE**\nThis PR contains changes that need human review before merging.\nRun `trust-check` locally for details.'
            })
