# .github/workflows/routine-guard.yml - Agents Finance template (MIT-0), v1.0, 31 October 2026
# Runs routine_run_guard.py on every routine output JSON added or changed in a pull request.
# Make the "routine-guard / guard" check required in your branch protection so a BLOCK cannot be merged.
# Expected layout:
#   finance-close/policy.json
#   finance-close/tools/routine_run_guard.py
#   finance-close/runs/*.json        <- what the routine writes
name: routine-guard

on:
  pull_request:
    paths:
      - "finance-close/runs/**.json"
      - "finance-close/policy.json"
      - "finance-close/tools/routine_run_guard.py"

permissions:
  contents: read

jobs:
  guard:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Check routine outputs changed in this pull request
        env:
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
        run: |
          set -euo pipefail
          mapfile -t files < <(git diff --name-only --diff-filter=AMR "$BASE_SHA" HEAD -- 'finance-close/runs/*.json')
          if [ "${#files[@]}" -eq 0 ]; then
            echo "No routine outputs changed."
            exit 0
          fi
          # Use the guard and the policy from the base branch, so a pull request
          # cannot weaken the rules it is checked against.
          git show "$BASE_SHA:finance-close/tools/routine_run_guard.py" > "$RUNNER_TEMP/guard.py"
          git show "$BASE_SHA:finance-close/policy.json" > "$RUNNER_TEMP/policy.json"
          status=0
          for f in "${files[@]}"; do
            python3 "$RUNNER_TEMP/guard.py" "$f" "$RUNNER_TEMP/policy.json" --log guard-log.jsonl || status=1
          done
          if ! git diff --quiet "$BASE_SHA" HEAD -- finance-close/policy.json finance-close/tools/; then
            echo "::warning::This pull request changes the guard or the policy. A person must review that change separately."
          fi
          exit "$status"

      - name: Keep the guard log with the pull request
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: routine-guard-log
          path: guard-log.jsonl
          if-no-files-found: ignore
