name: Test and Build

on:
  push:
    branches: [master]
    paths:
      - '**.rs'
      - 'Cargo.toml'
      - 'Cargo.lock'
      - 'Justfile'
      - 'just/**'
      - '.agents/**'
      - '.github/workflows/**'
      - 'README.md'
      - 'docs/**'
      - 'openspec/**'
      - 'scripts/**'
      - 'tests/**'
      - 'tools/**'
  pull_request:
    branches: [master]
    paths:
      - '**.rs'
      - 'Cargo.toml'
      - 'Cargo.lock'
      - 'Justfile'
      - 'just/**'
      - '.agents/**'
      - '.github/workflows/**'
      - 'README.md'
      - 'docs/**'
      - 'openspec/**'
      - 'scripts/**'
      - 'tests/**'
      - 'tools/**'

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

permissions:
  contents: read

env:
  CARGO_INCREMENTAL: 0
  CARGO_TERM_COLOR: always

jobs:
  test:
    name: Test and Build
    # WHY: Avoid duplicate CI for merge commits already checked on PR branches, while still checking direct pushes to master.
    if: >-
      github.event_name != 'push' || (
        !startsWith(github.event.head_commit.message, 'Merge pull request ') &&
        !contains(github.event.head_commit.message, '(#')
      )
    strategy:
      matrix:
        os: [macos-latest, ubuntu-latest, windows-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9 # master
        with:
          toolchain: stable
          components: clippy, rustfmt

      - name: Cache Rust build outputs
        uses: Swatinem/rust-cache@v2
        with:
          shared-key: ci-${{ matrix.os }}-stable-default

      - name: Install just
        uses: taiki-e/install-action@just

      - name: Check types
        run: cargo check --workspace --locked

      - name: Check formatting
        run: just fmt-check

      - name: Run Clippy
        run: just lint

      - name: Run AST lint
        run: just ast-lint

      - name: Run tests
        run: just test

      - name: Validate OpenSpec
        if: matrix.os == 'ubuntu-latest'
        run: just openspec-check
