name: CI

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

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Free up disk space
        run: |
          sudo rm -rf /usr/share/dotnet
          sudo rm -rf /usr/local/share/boost
          sudo rm -rf /usr/local/lib/android
          sudo rm -rf /opt/ghc
          sudo rm -rf /opt/hostedtoolcache/CodeQL
          sudo docker image prune --all --force || true
          df -h /
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - name: Cache HF models
        # Tests that warm the embedder (doctor, etc.) download the default
        # model from HuggingFace; repeated CI runs trip HF's 429 rate limit.
        # Bump the key suffix when the default model changes.
        uses: actions/cache@v4
        with:
          path: ~/.cache/huggingface
          key: hf-models-embeddinggemma-300m-v1
      - name: Build
        run: cargo build --verbose
      - name: Run tests
        run: cargo test --verbose

  clippy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy
      - uses: Swatinem/rust-cache@v2
      - name: Clippy
        run: cargo clippy --all-targets -- -D warnings

  fmt:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 2
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt
      - name: Format check
        run: cargo fmt --check
      - name: Comment provenance check
        if: github.event_name == 'pull_request'
        # On pull_request, HEAD is the PR merge commit; HEAD^1 is the base tip,
        # so this diff is exactly the PR's net effect.
        run: |
          git diff HEAD^1 HEAD -- '*.rs' \
            | python3 scripts/check_comment_provenance.py
      - name: Daemon request-path cwd check
        # Whole-tree invariant (not diff-based): daemon request handlers must
        # resolve their filesystem target from the served-project root in
        # BatchContext, never from process cwd. Runs on push and PR.
        run: python3 scripts/check_daemon_cwd.py

  msrv:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@1.96.0
      - uses: Swatinem/rust-cache@v2
      - name: Check MSRV
        run: cargo check --verbose
