Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(page): linear anchor check, URL comparison by normal form, robots directive grammar, served size

Agrici Daniel55ef5525a80b
diff --git a/scripts/page_checks.py b/scripts/page_checks.py
index 372180c..e4ddde2 100644
--- a/scripts/page_checks.py
+++ b/scripts/page_checks.py
@@ -66,6 +66,7 @@ import json
import os
import re
import sys
+import unicodedata
from typing import Optional
from urllib.parse import unquote, urljoin, urlparse, urlunparse
@@ -246,6 +247,10 @@ DEPRECATED_TAGS = ("acronym", "applet", "basefont", "big", "blink", "center", "d
"isindex", "marquee", "nobr", "noframes", "spacer", "strike", "tt")
GENERIC_ANCHORS = frozenset({"click here", "read more", "learn more", "here", "more", "link", "this page",
"details", "view", "website", "continue", "go"})
+# Link text longer than this is not compared with GENERIC_ANCHORS. The longest generic
+# phrase is 10 characters, so only a link padded with punctuation could be missed, and the
+# cap keeps the work per link fixed however long the page makes its link text.
+GENERIC_ANCHOR_MAX_CHARS = 200
_CHROME_TAGS = ("nav", "header", "footer", "aside")
_CHROME_ROLES = ("navigation", "banner", "contentinfo", "complementary", "menubar")
_CHROME_MARKERS = ("navbar", "topbar", "top-bar", "site-header", "site-footer", "main-nav", "footer-nav",
@@ -256,11 +261,24 @@ _MIXED_CONTENT_TAGS = ("img", "script", "iframe", "source", "video", "audio", "e
_SKIPPED_LINK_SCHEMES = ("#", "javascript:", "data:", "mailto:", "tel:", "sms:")
_ROBOTS_META_NAMES = ("robots", "googlebot")
_ROBOTS_VALUED_DIRECTIVES = ("max-snippet", "max-image-preview", "max-video-preview", "unavailable_after")
+# User agents whose rules decide Google Search indexing: none named (every crawler) or Googlebot.
+_ROBOTS_GENERAL_AGENTS = ("", "googlebot")
_TRACKING_KEYS = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid", "_ga", "ref"})
_PLACEHOLDER_RE = re.compile(r"\blorem ipsum\b|\bdolor sit amet\b|\bconsectetur adipiscing\b", re.I)
_WORD_RE = re.compile(r"[^\W\d_][\w'-]*", re.UNICODE)
_TRACKING_PARAM_RE = re.compile(r"^(utm_|fbclid$|gclid$|msclkid$|mc_)", re.I)
+_PERCENT_ESCAPE_RE = re.compile(r"%([0-9A-Fa-f]{2})")
+_NON_ASCII_BYTES_RE = re.compile(rb"[\x80-\xff]+")
+# RFC 3986 unreserved characters: their percent-encoded and literal forms are the same URL.
+_URL_UNRESERVED = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
+# A DNS name is at most 253 characters. A longer host is compared as written, not IDNA encoded.
+HOST_MAX_CHARS = 253
+# A crawler name in "googlebot: noindex" is one token, unlike the pieces of a comma-split
+# date in "unavailable_after: Wed, 03 Nov 2026 15:00:00 GMT".
+_CRAWLER_NAME_RE = re.compile(r"[a-z][a-z0-9_.-]*")
+# Rules for other named crawlers are listed as a fact, at most this many.
+ROBOTS_OTHER_AGENTS_MAX = 10
_UTF8_ALIASES = {"utf8": "utf-8", "utf-8": "utf-8", "unicode-1-1-utf-8": "utf-8"}
_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f-\x9f​-‏
-‮⁦-⁩]")
# Scripts written without spaces between words: Han, Hiragana, Katakana, Thai, Lao, Myanmar
@@ -313,6 +331,23 @@ def _sample(values: list[str], each: int = 60) -> str:
return shown + (f" (+{len(values) - 5} more)" if len(values) > 5 else "")
+def _is_generic_anchor(anchor: str) -> bool:
+ """Whether link text is a generic phrase once surrounding punctuation is dropped.
+
+ The ends are walked character by character: a regex with an unbounded run
+ before ``$`` rescans the run from every position, which is quadratic on a
+ long run of punctuation.
+ """
+ if len(anchor) > GENERIC_ANCHOR_MAX_CHARS:
+ return False
+ start, end = 0, len(anchor)
+ while start < end and not anchor[start].isalnum():
+ start += 1
+ while end > start and not anchor[end - 1].isalnum():
+ end -= 1
+ return anchor[start:end].lower() in GENERIC_ANCHORS
+
+
def tokenize(text: str) -> list[str]:
text = (text or "").replace("’", "'").replace("‘", "'")
return [w.lower().strip("'-") for w in _WORD_RE.findall(text) if w.strip("'-")]
@@ -335,8 +370,49 @@ def words_measurable(text: str, lang: str = "") -> bool:
return not letters or len(_UNSPACED_SCRIPT_RE.findall(text)) / letters < UNSPACED_SCRIPT_RATIO
+def _one_escape_spelling(part: str) -> str:
+ """One spelling for the percent-encoding of a path or query (RFC 3986, section 6.2.2).
+
+ "%c3%a9", "%C3%A9" and a literal "é" all become "%C3%A9", and the escape of
+ an unreserved character becomes the character ("%7E" is "~"). Escapes of
+ reserved characters keep their meaning: "%2F" stays apart from "/", "%26"
+ from "&" and "%20" from "+". Each escape is read once, so "%2541" is not "A".
+ """
+ def spell(match: re.Match) -> str:
+ char = chr(int(match.group(1), 16))
+ return char if char in _URL_UNRESERVED else match.group(0).upper()
+
+ part = _PERCENT_ESCAPE_RE.sub(spell, part)
+ if part.isascii():
+ return part
+ raw = part.encode("utf-8", "surrogatepass")
+ return _NON_ASCII_BYTES_RE.sub(lambda m: b"%" + m.group(0).hex("%").upper().encode("ascii"), raw).decode("ascii")
+
+
+def _idna_host(host: str) -> str:
+ """Host in the ASCII form browsers send: lower case, Unicode labels as Punycode.
+
+ "bücher.de" and "BÜCHER.DE" become "xn--bcher-kva.de". The mapping is the
+ UTS 46 one browsers use (NFKC and lower case, then Punycode), not the IDNA
+ 2003 codec in the standard library, which would turn "straße.de" into the
+ separate domain "strasse.de". A host or label that cannot be encoded is
+ returned lower-cased as written, so the comparison never raises.
+ """
+ host = host.lower()
+ if host.isascii() or len(host) > HOST_MAX_CHARS:
+ return host
+ try:
+ mapped = unicodedata.normalize("NFKC", unicodedata.normalize("NFKC", host).lower())
+ labels = [label if label.isascii() else "xn--" + label.encode("punycode").decode("ascii")
+ for label in mapped.replace("。", ".").split(".")] # the ideographic full stop
+ except (UnicodeError, ValueError):
+ return host
+ return ".".join(labels)
+
+
def canonicalize_url(url: str) -> Optional[str]:
- """Published form of a URL: lower-case host, no fragment, no tracking parameters."""
+ """Comparison form of a URL: IDNA lower-case host, no fragment, no tracking parameters,
+ one spelling for percent-encoding. Returns None for anything that is not an http(s) URL."""
if not url or any(c.isspace() for c in url):
return None
try:
@@ -347,12 +423,12 @@ def canonicalize_url(url: str) -> Optional[str]:
scheme = parsed.scheme.lower()
if scheme not in ("http", "https") or not parsed.hostname:
return None
- host = parsed.hostname.lower().rstrip(".")
+ host = _idna_host(parsed.hostname).rstrip(".")
if ":" in host:
host = f"[{host}]"
default_port = 443 if scheme == "https" else 80
netloc = f"{host}:{port}" if port and port != default_port else host
- path = re.sub(r"/{2,}", "/", parsed.path or "/")
+ path = _one_escape_spelling(re.sub(r"/{2,}", "/", parsed.path or "/"))
kept = []
for pair in parsed.query.split("&"):
if not pair:
@@ -360,8 +436,8 @@ def canonicalize_url(url: str) -> Optional[str]:
key = unquote(pair.split("=", 1)[0]).lower()
if key.startswith("utm_") or key in _TRACKING_KEYS:
continue
- kept.append(pair)
- return urlunparse((scheme, netloc, path, parsed.params, "&".join(kept), ""))
+ kept.append(_one_escape_spelling(pair))
+ return urlunparse((scheme, netloc, path, _one_escape_spelling(parsed.params), "&".join(kept), ""))
def url_match_key(url: str) -> str:
@@ -386,22 +462,43 @@ def _charset_of(content_type: str) -> str:
return _norm_charset(m.group(1)) if m else ""
-def _robots_directives(value: str) -> set[str]:
- """Directive words of a robots meta or X-Robots-Tag value.
+def _robots_rules(value: str) -> list[tuple[str, str]]:
+ """(user agent, directive) pairs of one robots meta or X-Robots-Tag value.
+
+ The grammar is an optional user agent, then comma-separated directives,
+ some of which carry a value::
+
+ [googlebot:] noindex, max-snippet: 50, unavailable_after: <date>
- "googlebot: noindex, nofollow" yields {"noindex", "nofollow"}. Valued
- directives such as "max-image-preview: none" are skipped, so their value is
- never read as the "none" directive.
+ The user agent is "" when the rule names none. A named one holds until the
+ next, because a server joins several headers into one with commas. A valued
+ directive is dropped with its value, so the "none" in "max-image-preview:
+ none" is never read as the "none" directive, with or without a user agent
+ in front. A piece that is neither (the rest of a date that has commas) is
+ dropped too.
"""
- out: set[str] = set()
+ rules: list[tuple[str, str]] = []
+ agent = ""
for part in (value or "").lower().split(","):
- name, sep, rest = part.strip().partition(":")
- if sep:
- if name.strip() in _ROBOTS_VALUED_DIRECTIVES:
- continue
- part = rest
- out.update(part.split())
- return out
+ name, sep, rest = (piece.strip() for piece in part.partition(":"))
+ if sep and name not in _ROBOTS_VALUED_DIRECTIVES and _CRAWLER_NAME_RE.fullmatch(name):
+ agent = name
+ name, sep, rest = (piece.strip() for piece in rest.partition(":"))
+ if not sep:
+ rules.extend((agent, word) for word in name.split())
+ return rules
+
+
+def _robots_directives(value: str) -> set[str]:
+ """Directives of a robots value that apply to Google Search.
+
+ "googlebot: noindex, nofollow" and "noindex, nofollow" both yield
+ {"noindex", "nofollow"}. A rule for another named crawler ("otherbot:
+ noindex") yields nothing: it does not keep the page out of Google, so it is
+ never reported as a noindex or nofollow finding. ``run_checks`` lists such
+ rules in the ``x_robots_other_agents`` fact instead, with no severity.
+ """
+ return {directive for agent, directive in _robots_rules(value) if agent in _ROBOTS_GENERAL_AGENTS}
def _document_base(soup, page_url: str) -> str:
@@ -660,8 +757,19 @@ def run_checks(html: str, page_url: str, headers: Optional[dict] = None,
for _name, content in robots_metas:
meta_directives |= _robots_directives(content)
meta_robots = "; ".join(f"{name}: {content}" for name, content in robots_metas)
- x_robots = hdrs.get("x-robots-tag", "").strip()
- header_directives = _robots_directives(x_robots)
+ # Each X-Robots-Tag header is read on its own, so a user agent named in one does not
+ # reach into the next. Headers a server or client has already joined with commas cannot
+ # be told apart again: what follows a named crawler is read as that crawler's.
+ x_robots_values: list[str] = []
+ for key, value in (headers or {}).items():
+ if str(key).lower() == "x-robots-tag":
+ x_robots_values.extend(map(str, value) if isinstance(value, (list, tuple)) else [str(value)])
+ x_robots = ", ".join(x_robots_values).strip()
+ header_rules = [rule for value in x_robots_values for rule in _robots_rules(value)]
+ header_directives = {directive for agent, directive in header_rules if agent in _ROBOTS_GENERAL_AGENTS}
+ # A rule for another named crawler is a fact, not a finding: it does not block Google Search.
+ other_agent_rules = list(dict.fromkeys(f"{agent}: {directive}" for agent, directive in header_rules
+ if agent not in _ROBOTS_GENERAL_AGENTS))
if meta_directives & {"noindex", "none"}:
add("noindex", f"meta {meta_robots}")
if header_directives & {"noindex", "none"}:
@@ -786,7 +894,7 @@ def run_checks(html: str, page_url: str, headers: Optional[dict] = None,
links_total += 1
if is_https and scheme == "http":
insecure_links.append(full)
- if re.sub(r"^[\W_]+|[\W_]+$", "", anchor.lower()) in GENERIC_ANCHORS and not _in_chrome_zone(a):
+ if _is_generic_anchor(anchor) and not _in_chrome_zone(a):
generic_anchors.append(f"\"{anchor}\" to {full}")
if links_without_text:
add("links-without-text", f"{len(links_without_text)} link(s): {_sample(links_without_text)}",
@@ -897,6 +1005,7 @@ def run_checks(html: str, page_url: str, headers: Optional[dict] = None,
"canonical_note": canonical_note,
"meta_robots": _trim(meta_robots) or None,
"x_robots_tag": _trim(x_robots) or None,
+ "x_robots_other_agents": [_trim(rule, 100) for rule in other_agent_rules[:ROBOTS_OTHER_AGENTS_MAX]],
"hreflang_count": len(hreflang),
"lang": _trim(lang, 35) or None,
"has_doctype": has_doctype,
@@ -1020,7 +1129,11 @@ def _from_url(url: str, timeout: int) -> dict:
status = page.get("status_code")
if page.get("content") is None or (isinstance(status, int) and status >= 400):
raise _InputError(f"HTTP {status} from {page.get('url')}: no page to check")
- result = run_checks(page["content"], page["url"], page.get("headers") or {})
+ # The size as served: the raw body bytes fetch_page.py read. The UTF-8 size of the
+ # decoded text, the fallback inside run_checks, doubles a single-byte Cyrillic page.
+ content_bytes = page.get("content_bytes")
+ served = content_bytes if isinstance(content_bytes, int) and not isinstance(content_bytes, bool) else None
+ result = run_checks(page["content"], page["url"], page.get("headers") or {}, html_bytes=served)
out = {"url": result.pop("url"), "source": "url", "status_code": status, **result}
if page.get("url") != url or page.get("redirect_chain"):
out["facts"]["requested_url"] = _trim(url)
diff --git a/skills/seo-page/SKILL.md b/skills/seo-page/SKILL.md
index cbadfaf..2a9bdf2 100644
--- a/skills/seo-page/SKILL.md
+++ b/skills/seo-page/SKILL.md
@@ -31,8 +31,10 @@ then use `--file`.
The JSON holds `facts` (lengths and counts), `findings` (each with a stable
`id`, a `severity`, a `message` and the `evidence` that triggered it),
-`not_checked`, `thresholds`, and a `summary` count per severity. It covers
-47 checks:
+`not_checked`, `thresholds`, and a `summary` count per severity. An
+`X-Robots-Tag` rule addressed to a crawler other than Googlebot is not a
+finding; it is listed in `facts.x_robots_other_agents`, so mention it when the
+user cares about that crawler. It covers 47 checks:
| Area | Finding ids |
|------|-------------|
diff --git a/tests/test_page_checks.py b/tests/test_page_checks.py
index fb3de62..17fcce7 100644
--- a/tests/test_page_checks.py
+++ b/tests/test_page_checks.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import json
import subprocess
import sys
+import time
from pathlib import Path
import pytest
@@ -428,6 +429,200 @@ def test_hostile_nesting_is_survived():
assert finding(deep_json, "invalid-jsonld")["count"] == 1
+HOSTILE_TEXT = {
+ "punctuation": "a" + "!" * 1_000_000 + "a",
+ "dashes": "a" + " -'" * 333_333 + "a",
+ "whitespace": "a" + " \n\t" * 333_333 + "a",
+}
+HOSTILE_PLACES = {
+ "anchor": lambda text: {"body": main_content(f'<a href="/beans">{text}</a>')},
+ "title": lambda text: {"title": text},
+ "description": lambda text: {"description": text},
+ "heading": lambda text: {"body": main_content(h1=f"<h1>{text}</h1>")},
+}
+
+
[email protected]("place", sorted(HOSTILE_PLACES))
[email protected]("kind", sorted(HOSTILE_TEXT))
+def test_one_megabyte_of_hostile_text_costs_linear_time(place, kind):
+ parts = HOSTILE_PLACES[place](HOSTILE_TEXT[kind])
+ started = time.perf_counter()
+ result = run(**parts)
+ elapsed = time.perf_counter() - started
+ assert elapsed < 2, f"{place} with 1 MB of {kind} took {elapsed:.1f} s"
+ assert "summary" in result
+ assert all(len(item["evidence"]) <= page_checks.EVIDENCE_MAX_CHARS for item in result["findings"])
+
+
+# One megabyte aimed at each remaining regex and parser that reads page-controlled text.
+HOSTILE_ELSEWHERE = {
+ "comments before the doctype": {"doctype": "<!----> " * 20_000 + "<!--" + "-" * 1_000_000},
+ "content-type meta": {"charset": '<meta http-equiv="content-type" content="text/html; '
+ + "charset" + " " * 500_000 + "charset=" + " " * 500_000 + ';">'},
+ "robots meta": {"head": '<meta name="robots" content="' + "a: b: c , " * 100_000 + '">'},
+ "x-robots-tag header": {"headers": {**HEADERS, "X-Robots-Tag": "bot: unavailable_after: 1, 2:" * 40_000}},
+ "content-type header": {"headers": {"Content-Type": "text/html; charset" + " " * 1_000_000 + "x"}},
+ "canonical escapes": {"canonical": "https://example.com/" + "%c3%a9é%" * 125_000},
+ "canonical slashes": {"canonical": "https://example.com/" + "/a/" * 333_333},
+ "image srcset": {"body": main_content('<img alt="x" srcset="' + " ," * 500_000 + '">')},
+ "visible text": {"body": main_content("<p>" + "lorem ipsu " * 90_000 + "</p>")},
+ "json-ld": {"head": '<script type="application/ld+json">' + '{"a":' * 150_000 + "</script>"},
+}
+
+
[email protected]("target", sorted(HOSTILE_ELSEWHERE))
+def test_one_megabyte_aimed_at_each_other_pattern_costs_linear_time(target):
+ started = time.perf_counter()
+ result = run(**HOSTILE_ELSEWHERE[target])
+ elapsed = time.perf_counter() - started
+ assert elapsed < 2, f"1 MB of {target} took {elapsed:.1f} s"
+ assert "summary" in result
+
+
+def test_generic_anchor_ignores_surrounding_punctuation_up_to_the_cap():
+ def generic(anchor: str) -> bool:
+ return "generic-anchor-text" in ids(run(body=main_content(f'<a href="/beans">{anchor}</a>')))
+
+ assert generic("&raquo; Click here! &laquo;")
+ assert generic("__Read More__")
+ assert generic("here" + "!" * (page_checks.GENERIC_ANCHOR_MAX_CHARS - 4))
+ assert not generic("click here for the roasting chart")
+ assert not generic("!!!")
+ # Longer than the cap is not examined: no real generic link is padded that far.
+ assert not generic("here" + "!" * (page_checks.GENERIC_ANCHOR_MAX_CHARS - 3))
+
+
+# ---------------------------------------------------------------------------
+# URL spellings: the same page under another encoding is not another page
+# ---------------------------------------------------------------------------
+
+
+def url_verdict(page_url: str, other: str) -> tuple[str, set[str]]:
+ """Canonical, hreflang and og:url all name ``other`` on a page served at ``page_url``."""
+ result = run(url=page_url, canonical=other, og=OG.replace(f'content="{URL}"', f'content="{page_url}"'),
+ head=f'<link rel="alternate" hreflang="en" href="{other}">')
+ url_findings = {"canonical-points-elsewhere", "hreflang-missing-self", "og-url-differs-from-canonical"}
+ return result["facts"]["canonical_status"], ids(result) & url_findings
+
+
[email protected](("page_url", "other"), [
+ ("https://example.com/caf%C3%A9/", "https://example.com/caf%c3%a9/"), # WordPress writes lower-case hex
+ ("https://example.com/caf%C3%A9/", "https://example.com/café/"),
+ ("https://example.com/café", "https://example.com/caf%c3%a9/"),
+ ("https://example.com/s?q=caf%C3%A9", "https://example.com/s?q=caf%c3%a9"),
+ ("https://example.com/s?q=caf%C3%A9", "https://example.com/s?q=café"),
+ ("https://example.com/%7Eroaster/a%2Fb", "https://example.com/~roaster/a%2fb"),
+ ("https://xn--bcher-kva.de/guide", "https://bücher.de/guide"),
+ ("https://xn--bcher-kva.de/guide", "https://BÜCHER.DE/guide"),
+ ("https://XN--BCHER-KVA.de/guide", "https://bücher.de/guide/"),
+ ("https://xn--strae-oqa.de/", "https://straße.de/"),
+ ("https://例え.jp/コーヒー", "https://xn--r8jz45g.jp/%E3%82%B3%E3%83%BC%E3%83%92%E3%83%BC"),
+])
+def test_equivalent_url_spellings_are_the_same_page(page_url, other):
+ assert url_verdict(page_url, other) == ("self", set())
+ assert url_verdict(other, page_url) == ("self", set())
+
+
[email protected](("page_url", "other"), [
+ ("https://example.com/caf%C3%A9", "https://example.com/cafe"), # another path
+ ("https://example.com/caf%C3%A9", "https://example.com/caf%C3%A8"),
+ ("https://example.com/caf%C3%A9", "https://example.com/Caf%C3%A9"), # path case is real
+ ("https://example.com/caf%E9", "https://example.com/café"), # Latin-1 escape: other bytes
+ ("https://example.com/a%2Fb", "https://example.com/a/b"), # an escaped slash is not a slash
+ ("https://example.com/a%20b", "https://example.com/a+b"),
+ ("https://example.com/a%2541", "https://example.com/aA"), # decoded once, never twice
+ ("https://example.com/s?q=1", "https://example.com/s?q=2"), # another query
+ ("https://example.com/s?q=caf%C3%A9", "https://example.com/s?q=cafe"),
+ ("https://example.com/s?q=a%26b", "https://example.com/s?q=a&b"),
+ ("https://example.com/page", "http://example.com/page"), # http versus https
+ ("https://example.com/page", "https://example.com:8443/page"),
+ ("https://bücher.de/", "https://bucher.de/"), # another host
+ ("https://straße.de/", "https://strasse.de/"), # two registrable domains
+ ("https://xn--bcher-kva.de/", "https://xn--bcher-kva.com/"),
+])
+def test_real_url_differences_stay_different(page_url, other):
+ expected = ("other", {"canonical-points-elsewhere", "hreflang-missing-self", "og-url-differs-from-canonical"})
+ assert url_verdict(page_url, other) == expected
+ assert url_verdict(other, page_url) == expected
+
+
+def test_url_comparison_never_raises_on_a_malformed_url_or_host():
+ long_label = "https://" + "ü" * 70 + ".de/" # a label over 63 characters is not valid IDNA
+ long_host = "https://" + "ü." * 400_000 + "de/"
+ bad_urls = ["", "http://[bad", "https://example.com:port/", "https://exa mple.com/", long_label, long_host,
+ "https://a..ü.de/", "https://.ü./", "https://xn--.de/", "https://ü\udcff.de/x",
+ "https://example.com/\ud800", "https://example.com/%", "https://example.com/%zz%c3%",
+ "https://example.com/" + "%c3" * 400_000, "https://example。com/", "https://ü@:x/"]
+ started = time.perf_counter()
+ for bad in bad_urls:
+ assert isinstance(page_checks.url_match_key(bad), str)
+ assert page_checks.url_match_key(bad) == page_checks.url_match_key(bad)
+ if bad.isprintable():
+ result = run(canonical=bad, head=f'<link rel="alternate" hreflang="de" href="{bad}">')
+ assert "summary" in result
+ assert time.perf_counter() - started < 10
+ # A host that cannot be encoded is still compared, as written.
+ assert url_verdict(long_label + "x", long_label + "x/") == ("self", set())
+ assert url_verdict(long_label, long_label.replace("ü", "u"))[0] == "other"
+
+
+# ---------------------------------------------------------------------------
+# Robots grammar: [user-agent:] directive[: value], directive[: value], ...
+# ---------------------------------------------------------------------------
+
+ROBOTS_IDS = {"noindex", "noindex-header", "nofollow"}
+
+
[email protected](("value", "expected"), [
+ ("googlebot: max-image-preview: none", set()), # "none" is the value of max-image-preview
+ ("max-image-preview: none", set()),
+ ("max-video-preview: -1, max-snippet: 50", set()),
+ ("googlebot: none", {"noindex-header", "nofollow"}),
+ ("none", {"noindex-header", "nofollow"}),
+ ("noindex", {"noindex-header"}),
+ ("GoogleBot: NoIndex", {"noindex-header"}),
+ ("max-snippet: -1, noindex", {"noindex-header"}),
+ ("googlebot: max-snippet: -1, noindex", {"noindex-header"}),
+ ("otherbot: noindex", set()), # a rule for another crawler is not a page-wide noindex
+ ("otherbot: noindex, nofollow", set()), # the user agent holds for the whole group
+ ("otherbot: none", set()),
+ ("googlebot: nofollow, otherbot: noindex, nofollow", {"nofollow"}), # two headers joined by the server
+ ("otherbot: noindex, googlebot: max-image-preview: none, nofollow", {"nofollow"}),
+ ("unavailable_after: Wed, 03 Nov 2026 15:00:00 GMT, noindex", {"noindex-header"}),
+ ("otherbot: unavailable_after: Wed, 03 Nov 2026 15:00:00 GMT, noindex", set()),
+ ("unavailable_after: 2026-11-03T15:00:00+00:00", set()),
+ (["googlebot: max-image-preview: none", "otherbot: none"], set()), # several headers
+ (["otherbot: nofollow", "noindex"], {"noindex-header"}), # the scope ends with its header
+ (["otherbot: noindex", "googlebot: none"], {"noindex-header", "nofollow"}),
+])
+def test_x_robots_tag_grammar(value, expected):
+ result = run(headers={**HEADERS, "X-Robots-Tag": value})
+ assert ids(result) & ROBOTS_IDS == expected
+
+
+def test_a_rule_for_another_named_crawler_is_a_fact_not_a_finding():
+ result = run(headers={**HEADERS, "X-Robots-Tag": "bingbot: noindex, nofollow, max-snippet: 5"})
+ assert result["findings"] == []
+ assert result["facts"]["x_robots_other_agents"] == ["bingbot: noindex", "bingbot: nofollow"]
+ assert run()["facts"]["x_robots_other_agents"] == []
+ assert run(headers={**HEADERS, "X-Robots-Tag": "googlebot: noindex"})["facts"]["x_robots_other_agents"] == []
+ flood = run(headers={**HEADERS, "X-Robots-Tag": ", ".join(f"bot{'x' * 300}{i}: noindex" for i in range(500))})
+ assert len(json.dumps(flood["facts"]["x_robots_other_agents"])) < 1500
+
+
[email protected](("content", "expected"), [
+ ("max-image-preview: none", set()),
+ ("index, follow, max-video-preview: -1, max-image-preview: none", set()),
+ ("max-snippet: -1, noindex", {"noindex"}),
+ ("max-image-preview: none, none", {"noindex", "nofollow"}),
+ ("unavailable_after: Wed, 03 Nov 2026 15:00:00 GMT, nofollow", {"nofollow"}),
+ ("otherbot: noindex", set()),
+])
+def test_meta_robots_grammar(content, expected):
+ assert ids(run(head=f'<meta name="robots" content="{content}">')) & ROBOTS_IDS == expected
+ assert ids(run(head=f'<meta name="googlebot" content="{content}">')) & ROBOTS_IDS == expected
+
+
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
@@ -507,6 +702,35 @@ def test_cli_url_mode_uses_the_safe_fetcher(capsys, monkeypatch):
assert out["facts"]["redirects"] == 1 and out["facts"]["requested_url"].startswith("http://")
+def test_cli_url_mode_measures_the_bytes_served_not_the_decoded_text(capsys, monkeypatch):
+ import fetch_page
+
+ # 1.1 MB of windows-1251 Cyrillic: one byte per letter as served, two per letter in UTF-8.
+ html = build(charset='<meta charset="windows-1251">', body=main_content("<p>" + "ж" * 1_100_000 + "</p>"))
+ served = len(html.encode("cp1251"))
+ as_utf8 = len(html.encode("utf-8"))
+ assert served < page_checks.HTML_MAX_BYTES < as_utf8
+ page = {"url": URL, "status_code": 200, "content": html, "too_large": False, "error": None,
+ "headers": {"Content-Type": "text/html; charset=windows-1251"}, "redirect_chain": []}
+
+ def fetched(**extra) -> dict:
+ monkeypatch.setattr(fetch_page, "fetch_page", lambda url, timeout=30, **_k: {**page, **extra})
+ code, out = cli(capsys, "--url", URL)
+ assert code == 0
+ return out
+
+ out = fetched(content_bytes=served)
+ assert out["facts"]["html_bytes"] == served
+ assert "html-over-2mb" not in ids(out)
+ over = fetched(content_bytes=page_checks.HTML_MAX_BYTES + 1)
+ assert "html-over-2mb" in ids(over)
+ # A fetch result without a usable byte count falls back to the UTF-8 size of the text.
+ for extra in ({}, {"content_bytes": None}, {"content_bytes": "1100000"}, {"content_bytes": True}):
+ fallback = fetched(**extra)
+ assert fallback["facts"]["html_bytes"] == as_utf8
+ assert "html-over-2mb" in ids(fallback)
+
+
@pytest.mark.parametrize(("page", "needle"), [
({"url": URL, "status_code": None, "content": None, "headers": {}, "error": "Connection error: refused"}, "refused"),
({"url": URL, "status_code": 404, "content": "<html>gone</html>", "headers": {}, "error": None}, "HTTP 404"),