---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Audit CopeCheck's public index surface against the stored SEO policy.\"\"\" from __future__ import annotations import argparse import json import re import sys from html import unescape from."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-05-25T16:35:00Z"
site: "main"
source_path: "copecheck/tools/audit_index_surface.py"
---

# !/usr/bin/env python3

Source path: `copecheck/tools/audit_index_surface.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-05-25T16:35:00Z`

```py
#!/usr/bin/env python3
"""Audit CopeCheck's public index surface against the stored SEO policy."""
from __future__ import annotations

import argparse
import json
import re
import sys
from html import unescape
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin, urlparse
from urllib.request import Request, urlopen

BASE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(BASE))

import db  # noqa: E402


def fetch(url: str, timeout: int = 20) -> tuple[int, str, str]:
    req = Request(url, headers={"User-Agent": "CopeCheckIndexAudit/1.0"})
    try:
        with urlopen(req, timeout=timeout) as response:
            return response.status, response.geturl(), response.read().decode("utf-8", errors="replace")
    except HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        return exc.code, url, body
    except URLError as exc:
        return 0, url, str(exc)


def has_noindex(html: str) -> bool:
    return bool(re.search(r'<meta\s+name=["\']robots["\'][^>]+noindex', html, re.I))


def sitemap_locs(xml: str) -> list[str]:
    return [unescape(match) for match in re.findall(r"<loc>(.*?)</loc>", xml, flags=re.I | re.S)]


def path_key(url: str) -> str:
    parsed = urlparse(url)
    path = parsed.path or "/"
    return path.rstrip("/") if path != "/" else path


def db_noindex_paths(limit: int) -> list[str]:
    try:
        db.init()
        db.init_instant()
        return [f"/v/{row['slug']}" for row in db.noindex_articles(limit=limit)]
    except Exception:
        return []


def db_indexed_samples() -> dict[str, list[str]]:
    samples = {"articles": [], "submissions": [], "instants": []}
    try:
        db.init()
        db.init_instant()
        for row in db.sitemap_articles(limit=3):
            samples["articles"].append(f"/v/{row['slug']}")
        for row in db.sitemap_submissions(limit=3):
            samples["submissions"].append(f"/verdict/{row['id']}")
        for row in db.sitemap_instant_scores(limit=3):
            samples["instants"].append(f"/instant/{row['slug']}")
    except Exception:
        pass
    return samples


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--base", default="https://www.copecheck.com")
    parser.add_argument("--max-sitemap", type=int, default=700)
    parser.add_argument("--sample-noindex", type=int, default=12)
    args = parser.parse_args()

    base = args.base.rstrip("/")
    errors: list[str] = []
    warnings: list[str] = []

    robots_url = f"{base}/robots.txt"
    status, _, robots = fetch(robots_url)
    robots_status = status
    if status != 200:
        errors.append(f"robots.txt returned {status}")
    for blocked in ("Disallow: /v", "Disallow: /verdict", "Disallow: /instant"):
        if blocked.lower() in robots.lower():
            errors.append(f"robots.txt blocks indexable corpus path: {blocked}")

    sitemap_url = f"{base}/sitemap.xml"
    status, _, xml = fetch(sitemap_url)
    sitemap_status = status
    if status != 200:
        errors.append(f"sitemap.xml returned {status}")
        locs = []
    else:
        locs = sitemap_locs(xml)
    sitemap_paths = {path_key(loc) for loc in locs}

    for loc in locs[:args.max_sitemap]:
        status, final_url, body = fetch(loc)
        if status != 200:
            errors.append(f"sitemap URL returned {status}: {loc}")
            continue
        content_type_xml = loc.endswith(".xml") or loc.endswith(".txt")
        if not content_type_xml and has_noindex(body):
            errors.append(f"sitemap URL is noindex: {loc}")
        if final_url and path_key(final_url) != path_key(loc) and "www.copecheck.com" in loc:
            warnings.append(f"sitemap URL redirected: {loc} -> {final_url}")

    for path in db_noindex_paths(args.sample_noindex):
        if path in sitemap_paths:
            errors.append(f"stored noindex page appears in sitemap: {path}")
        url = urljoin(base + "/", path.lstrip("/"))
        status, _, body = fetch(url)
        if status != 200:
            errors.append(f"noindex sample returned {status}: {path}")
        elif not has_noindex(body):
            errors.append(f"stored noindex page lacks noindex meta: {path}")

    samples = db_indexed_samples()
    for group, paths in samples.items():
        for path in paths:
            url = urljoin(base + "/", path.lstrip("/"))
            status, _, body = fetch(url)
            if status != 200:
                errors.append(f"indexed {group} sample returned {status}: {path}")
            elif has_noindex(body):
                errors.append(f"indexed {group} sample has noindex meta: {path}")

    result = {
        "base": base,
        "robots_status": robots_status,
        "sitemap_status": sitemap_status,
        "sitemap_urls": len(locs),
        "checked_sitemap_urls": min(len(locs), args.max_sitemap),
        "sampled_indexed": {k: len(v) for k, v in samples.items()},
        "sampled_noindex": len(db_noindex_paths(args.sample_noindex)),
        "warnings": warnings[:20],
        "errors": errors[:40],
    }
    print(json.dumps(result, indent=2, sort_keys=True))
    return 1 if errors else 0


if __name__ == "__main__":
    raise SystemExit(main())
```
