# Copy to .github/workflows/agenticweb-lint.yml in your repository.
# Validates local agent-facing manifests (llms.txt, AGENTS.md, robots.txt, /.well-known/*)
# against published specifications via https://agenticweb.wiki/mcp before merge.
name: Agentic Web Manifest Lint

on:
  pull_request:
    paths:
      - "**/llms.txt"
      - "**/AGENTS.md"
      - "**/robots.txt"
      - "**/auth.md"
      - "**/okf/index.md"
      - "**/.well-known/ard.json"
      - "**/.well-known/ai-catalog.json"
      - "**/.well-known/mcp/server-card.json"
      - "**/mcp/server-card"
      - "**/.well-known/agent-card.json"
      - "**/.well-known/agent-skills/index.json"
      - "**/.well-known/api-catalog"
      - "**/.well-known/security.txt"
  workflow_dispatch:

jobs:
  lint-manifests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Validate agent-facing manifests via agenticweb.wiki/mcp
        run: |
          python3 - <<'PY'
          import json, os, pathlib, sys, urllib.request

          CANDIDATES = [
              ("llms-txt", ["llms.txt", "public/llms.txt", "static/llms.txt"]),
              ("agents-md", ["AGENTS.md", "public/AGENTS.md", "static/AGENTS.md"]),
              ("ai-crawler-tokens-robots", ["robots.txt", "public/robots.txt", "static/robots.txt"]),
              ("auth-md", ["auth.md", "public/auth.md", "static/auth.md"]),
              ("okf", ["okf/index.md", "public/okf/index.md", "static/okf/index.md"]),
              ("ard", [".well-known/ard.json", "public/.well-known/ard.json", "static/.well-known/ard.json"]),
              ("ai-catalog-well-known-file", [".well-known/ai-catalog.json", "public/.well-known/ai-catalog.json", "static/.well-known/ai-catalog.json"]),
              ("mcp-server-cards", [".well-known/mcp/server-card.json", "mcp/server-card", "public/.well-known/mcp/server-card.json"]),
              ("a2a", [".well-known/agent-card.json", "public/.well-known/agent-card.json"]),
              ("anthropic-agent-skills-format", [".well-known/agent-skills/index.json", "public/.well-known/agent-skills/index.json"]),
              ("api-catalog-rfc9727", [".well-known/api-catalog", "public/.well-known/api-catalog"]),
              ("security-txt", [".well-known/security.txt", "public/.well-known/security.txt"]),
          ]

          repo = os.environ.get("GITHUB_REPOSITORY", "local/repo")
          failed = 0
          checked = 0

          for spec_id, paths in CANDIDATES:
              for rel in paths:
                  p = pathlib.Path(rel)
                  if not p.is_file():
                      continue
                  checked += 1
                  payload = json.dumps({
                      "jsonrpc": "2.0",
                      "id": checked,
                      "method": "tools/call",
                      "params": {
                          "name": "validate_manifest",
                          "arguments": {"id": spec_id, "content": p.read_text(encoding="utf-8", errors="replace")},
                      },
                  }).encode("utf-8")
                  req = urllib.request.Request(
                      "https://agenticweb.wiki/mcp",
                      data=payload,
                      headers={
                          "Content-Type": "application/json",
                          "Accept": "application/json",
                          "Mcp-Method": "tools/call",
                          "Mcp-Name": "validate_manifest",
                          "User-Agent": f"agenticweb-ci-linter/1.0 ({repo})",
                      },
                      method="POST",
                  )
                  with urllib.request.urlopen(req, timeout=15) as resp:
                      raw_body = resp.read().decode("utf-8")
                  if raw_body.lstrip().startswith("event:") or "\ndata:" in raw_body:
                      data_lines = [ln[5:].strip() for ln in raw_body.splitlines() if ln.startswith("data:")]
                      rpc = json.loads(data_lines[-1])
                  else:
                      rpc = json.loads(raw_body)
                  if rpc.get("error"):
                      print(f"[FAIL] {rel} ({spec_id})")
                      print(f"  ERROR: {rpc['error'].get('message') or rpc['error']}")
                      failed += 1
                      break
                  res = rpc.get("result") or {}
                  txt = ((res.get("content") or [{}])[0]).get("text") or ""
                  if res.get("isError"):
                      print(f"[FAIL] {rel} ({spec_id})")
                      print(f"  ERROR: {txt or 'MCP tool returned isError'}")
                      failed += 1
                      break
                  report = json.loads(txt)
                  status = "PASS" if report.get("valid") else "FAIL"
                  print(f"[{status}] {rel} ({spec_id})")
                  for err in report.get("errors", []):
                      print(f"  ERROR: {err}")
                  for warn in report.get("warnings", []):
                      print(f"  WARN:  {warn}")
                  if not report.get("valid"):
                      failed += 1
                  break

          if checked == 0:
              print("No local agent-facing manifests found to validate.")
          if failed > 0:
              sys.exit(1)
          PY
