name: Knip — Unused Code Detection

# Knip scans for unused files, exports, dependencies, and types across src/**
# and the hand-written scripts in scripts/**. Runs on every PR and on pushes
# to main. Currently warning-only (continue-on-error: true) to keep the gate
# permissive while the baseline stabilises; flip to blocking once findings
# stay clean for two consecutive PR cycles.
#
# See WORKFLOWS.md § Knip / Unused Code Detection for the full contract.

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

permissions:
  contents: read

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

jobs:
  knip:
    name: Knip Scan
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
    steps:
      - name: Harden Runner
        uses: step-security/harden-runner@a5ad31d6a139d249332a2605b85202e8c0b78450 # v2.19.1
        with:
          egress-policy: audit

      - name: Checkout repository
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Setup Node.js
        uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: '25'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build TypeScript (so knip can resolve compiled scripts/**)
        run: npm run build

      - name: Run Knip
        id: knip
        continue-on-error: true
        shell: bash
        run: |
          set +e
          npm run knip 2>&1 | tee knip-output.txt
          status=${PIPESTATUS[0]}
          echo "status=$status" >> "$GITHUB_OUTPUT"
          exit "$status"

      - name: Write step summary
        if: always()
        run: |
          {
            echo "## 🔍 Knip — Unused Code Report"
            echo ""
            if [ "${{ steps.knip.outputs.status }}" = "0" ]; then
              echo "✅ No unused code, exports, or dependencies detected."
            else
              echo "⚠️ Knip detected unused code (warning-only mode)."
              echo ""
              echo "<details><summary>Full report</summary>"
              echo ""
              echo '```'
              cat knip-output.txt
              echo '```'
              echo ""
              echo "</details>"
            fi
            echo ""
            echo "_See [WORKFLOWS.md](${{ github.server_url }}/${{ github.repository }}/blob/main/WORKFLOWS.md) § Knip for triage guidance._"
          } >> "$GITHUB_STEP_SUMMARY"

      - name: Upload Knip report artifact
        if: always()
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: knip-report
          path: knip-output.txt
          retention-days: 14
          if-no-files-found: ignore
