# CI workflow — builds, tests, and gates merges to main
name: CI

on:
  push:
    branches: [main]
    paths-ignore:
      - '.github/workflows/ai-triage.yml'
      - '.github/workflows/build-native.yml'
      - '.github/workflows/cleanup-dev-versions.yml'
      - 'LICENSE'
  pull_request:
    branches: [main]
    paths-ignore:
      - '.github/workflows/ai-triage.yml'
      - '.github/workflows/build-native.yml'
      - '.github/workflows/cleanup-dev-versions.yml'
      - 'LICENSE'

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

jobs:
  detect-changes:
    timeout-minutes: 2
    runs-on: blacksmith-4vcpu-ubuntu-2404
    outputs:
      docs-only: ${{ steps.check.outputs.docs-only }}
      portability-changed: ${{ steps.check.outputs.portability-changed }}
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Check if only documentation changed
        id: check
        env:
          PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
          PUSH_BEFORE_SHA: ${{ github.event.before }}
          EVENT_NAME: ${{ github.event_name }}
          HEAD_SHA: ${{ github.sha }}
        run: |
          if [ "$EVENT_NAME" = "pull_request" ]; then
            BASE="$PR_BASE_SHA"
          else
            BASE="$PUSH_BEFORE_SHA"
          fi
          FILES=$(git diff --name-only "$BASE" "$HEAD_SHA" 2>/dev/null || git diff --name-only HEAD~1)
          echo "Changed files:"
          echo "$FILES"
          NON_DOCS=$(echo "$FILES" | grep -vE '\.(md|markdown)$' | grep -vE '^docs/' | grep -vE '^LICENSE$' || true)
          if [ -z "$NON_DOCS" ]; then
            echo "docs-only=true" >> "$GITHUB_OUTPUT"
            echo "::notice::Only documentation files changed — skipping build/test"
          else
            echo "docs-only=false" >> "$GITHUB_OUTPUT"
            echo "Non-docs files changed:"
            echo "$NON_DOCS"
          fi
          PORTABILITY=$(echo "$NON_DOCS" | grep -E '^(src/|packages/|native/|scripts/|web/|package\.json$|package-lock\.json$|web/package-lock\.json$|tsconfig[^/]*\.json$|packages/.*/tsconfig\.json$)' || true)
          if [ -n "$PORTABILITY" ]; then
            echo "portability-changed=true" >> "$GITHUB_OUTPUT"
            echo "Portability-relevant files changed:"
            echo "$PORTABILITY"
          else
            echo "portability-changed=false" >> "$GITHUB_OUTPUT"
            echo "::notice::No portability-relevant changes detected — skipping portability matrix jobs"
          fi

  docs-check:
    timeout-minutes: 5
    runs-on: blacksmith-4vcpu-ubuntu-2404
    needs: detect-changes
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Scan documentation for prompt injection
        run: bash scripts/docs-prompt-injection-scan.sh --diff origin/main

  lint:
    timeout-minutes: 5
    needs: detect-changes
    runs-on: blacksmith-4vcpu-ubuntu-2404
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 2

      - name: Scan for hardcoded secrets
        run: bash scripts/secret-scan.sh --diff origin/main

      - name: Scan for base64-encoded secrets
        run: bash scripts/base64-scan.sh --diff origin/main

      - name: Ensure .sf/ is not checked in
        run: |
          if [ -d ".sf" ]; then
            echo "::error::.sf/ directory must not be checked in"
            exit 1
          fi

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '26.1'

      - name: Validate skill references
        run: node scripts/check-skill-references.mjs

      - name: Require tests with source changes
        if: github.event_name == 'pull_request'
        env:
          PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
        run: bash scripts/require-tests.sh

      - name: Detect copy-paste duplication
        run: npx jscpd --diff origin/main --threshold 0.05 --ignore '**/*.test.ts' --ignore '**/*.test.mjs' --ignore 'node_modules/**' --ignore 'dist/**' --ignore 'web/**'

  build:
    timeout-minutes: 15
    needs: detect-changes
    if: needs.detect-changes.outputs.docs-only != 'true'
    runs-on: blacksmith-4vcpu-ubuntu-2404

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

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '26.1'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Install web host dependencies
        run: npm --prefix web ci

      - name: Cache Next.js build
        uses: useblacksmith/cache@v5
        with:
          path: web/.next/cache
          key: nextjs-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}-${{ hashFiles('web/app/**', 'web/components/**', 'web/lib/**', 'web/hooks/**') }}
          restore-keys: |
            nextjs-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}-
            nextjs-${{ runner.os }}-

      - name: Build core
        run: npm run build:core

      - name: Build web host
        run: npm run build:web-host

      - name: Typecheck extensions
        run: npm run typecheck:extensions

      - name: Validate package is installable
        run: npm run validate-pack

      - name: Run unit tests
        run: npx vitest run --config vitest.config.ts 2>&1 | tee .artifacts/test-timing.txt

      - name: Upload test timing artifact
        uses: actions/upload-artifact@v4
        with:
          name: test-timing
          path: .artifacts/test-timing.txt
          retention-days: 7

      - name: Run package tests
        run: npm run test:packages

      - name: Check test coverage thresholds
        run: npm run test:coverage

  integration-tests:
    timeout-minutes: 15
    needs: detect-changes
    if: needs.detect-changes.outputs.docs-only != 'true'
    runs-on: blacksmith-4vcpu-ubuntu-2404

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

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '26.1'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      # Integration tests need core compiled artifacts:
      # - dist/loader.js and packages/pi-coding-agent/dist/** from `npm run build:core`
      # - web/node_modules/.bin/next for tests that shell `build:web-host` at runtime
      # Duplicating the core build here (instead of sharing artifacts via needs: build)
      # preserves wall-clock parallelism with the build job — see PR #4093.
      - name: Install web host dependencies
        run: npm --prefix web ci

      - name: Cache Next.js build
        uses: useblacksmith/cache@v5
        with:
          path: web/.next/cache
          key: nextjs-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}-${{ hashFiles('web/app/**', 'web/components/**', 'web/lib/**', 'web/hooks/**') }}
          restore-keys: |
            nextjs-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}-
            nextjs-${{ runner.os }}-

      - name: Build core
        run: npm run build:core

      - name: Run integration tests
        run: npm run test:integration

  windows-portability:
    timeout-minutes: 25
    needs: detect-changes
    if: >-
      needs.detect-changes.outputs.docs-only != 'true' &&
      needs.detect-changes.outputs.portability-changed == 'true'
    runs-on: blacksmith-4vcpu-windows-2025

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

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '26.1'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build core
        run: npm run build:core

      - name: Typecheck extensions
        run: npm run typecheck:extensions

      - name: Run package tests
        run: npm run test:packages

      - name: Run Windows portability tests
        run: >-
          node --import ./src/resources/extensions/sf/tests/resolve-ts.mjs
          --experimental-strip-types --test
          src/tests/windows-portability.test.ts
          src/resources/extensions/sf/tests/validate-directory.test.ts
          src/tests/integration/web-mode-windows-hide.test.ts

  rtk-portability:
    timeout-minutes: 20
    needs: detect-changes
    if: >-
      needs.detect-changes.outputs.docs-only != 'true' &&
      needs.detect-changes.outputs.portability-changed == 'true'
    strategy:
      fail-fast: false
      matrix:
        include:
          - label: linux
            os: blacksmith-4vcpu-ubuntu-2404
          - label: windows
            os: blacksmith-4vcpu-windows-2025
          - label: macos
            os: macos-15
    runs-on: ${{ matrix.os }}

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

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '26.1'
          cache: 'npm'

      - name: Install dependencies
        env:
          PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1'
        run: npm ci

      - name: Validate managed RTK install
        run: >-
          node --experimental-strip-types --input-type=module -e
          "const mod = await import('./src/rtk.ts');
          const path = mod.getManagedRtkPath(process.platform);
          if (!mod.validateRtkBinary(path)) {
            console.error('Managed RTK validation failed:', path);
            process.exit(1);
          }
          console.log('Managed RTK validated at', path);"

      - name: Run RTK-focused portability tests
        run: >-
          node --import ./src/resources/extensions/sf/tests/resolve-ts.mjs
          --experimental-strip-types --experimental-test-isolation=process --test
          src/tests/rtk.test.ts
          src/tests/rtk-execution-seams.test.ts
          src/tests/postinstall.test.ts
          src/tests/app-smoke.test.ts
          src/resources/extensions/sf/tests/custom-verification.test.ts
          src/resources/extensions/sf/tests/verification-gate.test.ts

      - name: Generate RTK benchmark evidence
        if: matrix.label == 'linux'
        run: node scripts/rtk-benchmark.mjs --output .artifacts/rtk-benchmark.md

      - name: Upload RTK benchmark artifact
        if: matrix.label == 'linux'
        uses: actions/upload-artifact@v4
        with:
          name: rtk-benchmark-linux
          path: .artifacts/rtk-benchmark.md
