name: agents-md-guard

on:
  pull_request_target:
    types:
      - opened
      - synchronize
      - reopened

permissions:
  contents: read
  issues: write
  pull-requests: write

jobs:
  close-when-agents-md-changed:
    runs-on: ubuntu-latest
    steps:
      - name: Detect AGENTS.md changes and close PR
        uses: actions/github-script@v7
        with:
          script: |
            const prNumber = context.payload.pull_request.number;
            const { owner, repo } = context.repo;

            const files = await github.paginate(github.rest.pulls.listFiles, {
              owner,
              repo,
              pull_number: prNumber,
              per_page: 100,
            });

            const touchesAgentsMd = (path) =>
              typeof path === "string" &&
              (path === "AGENTS.md" || path.endsWith("/AGENTS.md"));

            const touched = files.filter(
              (f) => touchesAgentsMd(f.filename) || touchesAgentsMd(f.previous_filename),
            );

            if (touched.length === 0) {
              core.info("No AGENTS.md changes detected.");
              return;
            }

            const changedList = touched
              .map((f) =>
                f.previous_filename && f.previous_filename !== f.filename
                  ? `- ${f.previous_filename} -> ${f.filename}`
                  : `- ${f.filename}`,
              )
              .join("\n");

            const body = [
              "This repository does not allow modifying `AGENTS.md` in pull requests.",
              "",
              "Detected changes:",
              changedList,
              "",
              "Please revert these changes and open a new PR without touching `AGENTS.md`.",
            ].join("\n");

            try {
              await github.rest.issues.createComment({
                owner,
                repo,
                issue_number: prNumber,
                body,
              });
            } catch (error) {
              core.warning(`Failed to comment on PR #${prNumber}: ${error.message}`);
            }

            await github.rest.pulls.update({
              owner,
              repo,
              pull_number: prNumber,
              state: "closed",
            });

            core.setFailed("PR modifies AGENTS.md");
