name: AgentStack skill security check

on:
  pull_request:
    paths:
      - "**/SKILL.md"
      - ".github/workflows/agentstack-check.yml"
  workflow_dispatch:
    inputs:
      external-check:
        description: "Send SKILL.md contents to AgentStack's hosted checker (public repositories only)"
        required: false
        type: boolean
        default: false

permissions:
  contents: read

jobs:
  scan-skills:
    runs-on: ubuntu-latest
    steps:
      # actions/checkout v4.4.0
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
      # actions/setup-node v4.4.0
      - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
        with:
          node-version: "22"
      - name: Scan SKILL.md files locally
        env:
          EXTERNAL_CHECK: ${{ inputs.external-check || 'false' }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          AGENTSTACK_API_URL: https://agentstack.dev
        run: |
          node <<'NODE'
          const fs = require("node:fs");
          const path = require("node:path");
          const { spawnSync } = require("node:child_process");

          function walk(directory) {
            const files = [];
            for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
              if (entry.name === ".git" || entry.name === "node_modules") continue;
              const fullPath = path.join(directory, entry.name);
              if (entry.isDirectory()) files.push(...walk(fullPath));
              else if (entry.isFile() && entry.name.toLowerCase() === "skill.md") files.push(fullPath);
            }
            return files;
          }

          async function assertPublicRepository() {
            const repository = process.env.GITHUB_REPOSITORY;
            const token = process.env.GITHUB_TOKEN;
            if (!repository || !token) throw new Error("External check aborted: repository visibility could not be verified.");

            const response = await fetch(`https://api.github.com/repos/${repository}`, {
              headers: {
                Accept: "application/vnd.github+json",
                Authorization: `Bearer ${token}`,
                "X-GitHub-Api-Version": "2022-11-28",
                "User-Agent": "AgentStack-Skill-Checker",
              },
            });
            if (!response.ok) throw new Error(`External check aborted: GitHub repository visibility check failed (HTTP ${response.status}).`);

            const metadata = await response.json();
            if (metadata.private !== false || metadata.visibility !== "public") {
              console.warn("::warning::External check disabled: SKILL.md content will not be sent because the repository is not public.");
              throw new Error("External check aborted for a private or non-public repository.");
            }
          }

          async function main() {
            const externalCheck = process.env.EXTERNAL_CHECK === "true";
            if (externalCheck) {
              console.warn("External check enabled: only matched SKILL.md files will be sent to AgentStack after public visibility is verified.");
              await assertPublicRepository();
            }

            const skills = walk(process.cwd());
            if (!skills.length) {
              console.log("No SKILL.md files found; nothing to scan.");
              return;
            }

            let blocked = false;
            const githubToken = process.env.GITHUB_TOKEN;
            delete process.env.GITHUB_TOKEN;

            for (const file of skills) {
              const cliPackage = "git+https://github.com/nithincodesx/AgentStack.git";
              const local = spawnSync("npx", ["--yes", "--package", cliPackage, "agentstack-check", file], { stdio: "inherit" });
              if (local.error) throw local.error;
              if (local.status === 1) blocked = true;
              else if (local.status !== 0) throw new Error(`Local AgentStack CLI failed for ${file} with status ${local.status}.`);

              if (externalCheck) {
                const skillMd = fs.readFileSync(file, "utf8");
                const response = await fetch(`${process.env.AGENTSTACK_API_URL}/api/check`, {
                  method: "POST",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify({ skillMd }),
                });
                if (!response.ok) throw new Error(`Hosted checker returned HTTP ${response.status} for ${file}: ${await response.text()}`);
                const report = await response.json();
                console.log(`Hosted report for ${file}: ${report.score}/100 (${report.grade}) — ${report.verdict}`);
                if (report.verdict === "Do Not Install") blocked = true;
              }
            }
            if (blocked) process.exitCode = 1;
          }

          main().catch((error) => {
            console.error(error instanceof Error ? error.message : String(error));
            process.exitCode = 2;
          });
          NODE
