diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a6344aac8c09253b3b630fb776ae94478aa0275b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,35 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2a585e0cdc808ad58d7ebcf5900f07d702738b92 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.venv/ +__pycache__/ +*.pyc \ No newline at end of file diff --git a/DockerFile b/DockerFile new file mode 100644 index 0000000000000000000000000000000000000000..118f84148cf3ff05913210abc5a0a31eae797a06 --- /dev/null +++ b/DockerFile @@ -0,0 +1,6 @@ +FROM python:3.11-slim +WORKDIR /app +COPY backend/ ./backend/ +RUN pip install --no-cache-dir -r backend/requirements.txt +EXPOSE 7860 +CMD ["python", "-m", "uvicorn", "app.main:app", "--app-dir", "backend", "--host", "0.0.0.0", "--port", "7860"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7c7aa4e23598128ea54dec43b40d053b2fc2e077 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +--- +title: MachineRead - Preview +emoji: 🔍 +colorFrom: green +colorTo: gray +sdk: docker +app_port: 7860 +pinned: false +license: mit +short_description: Free Features Preview of MachineRead Project +--- diff --git a/backend/.cache/entity_lookup.sqlite3 b/backend/.cache/entity_lookup.sqlite3 new file mode 100644 index 0000000000000000000000000000000000000000..1294ab0f229c5bb23c689acfc68480a9fa118dd1 Binary files /dev/null and b/backend/.cache/entity_lookup.sqlite3 differ diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/agent_readiness.py b/backend/app/agent_readiness.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1a62ec71da2f65dc51b11b5ff3920c106c0afb --- /dev/null +++ b/backend/app/agent_readiness.py @@ -0,0 +1,497 @@ +import asyncio +import json +from dataclasses import dataclass +from urllib.parse import urlparse + +from app.audit_context import AuditContext +from app.benchmarks import build_agent_benchmark_comparison +from app.checks.llms_txt import agent_text_access, best_sitemap +from app.checks.robots import content_signal_tokens, explicit_ai_bot_count +from app.fetching import FetchResult, fetch_url, make_root_url +from app.models import AgentReadinessCategory, AgentReadinessSummary + +_LINK_HEADER_TOKENS = ( + "api-catalog", + "oauth-authorization-server", + "oauth-protected-resource", + "mcp", + "agent", + "webmcp", + "auth.md", +) + +_JSON_SURFACES: tuple[tuple[str, tuple[str, ...], str, str, str, tuple[str, ...]], ...] = ( + ( + "Web Bot Auth directory", + ("/.well-known/http-message-signatures-directory",), + "application/json, */*;q=0.5", + "Bot Access Control", + "core", + ("keys",), + ), + ( + "API Catalog", + ("/.well-known/api-catalog", "/.well-known/api-catalog.json", "/api-catalog.json"), + "application/linkset+json, application/json, */*;q=0.5", + "Protocol Discovery", + "protocols", + ("linkset", "api-catalog"), + ), + ( + "OAuth/OIDC discovery metadata", + ( + "/.well-known/oauth-authorization-server", + "/.well-known/openid-configuration", + ), + "application/json, */*;q=0.5", + "Protocol Discovery", + "account_auth", + ("issuer",), + ), + ( + "OAuth Protected Resource metadata", + ("/.well-known/oauth-protected-resource",), + "application/json, */*;q=0.5", + "Protocol Discovery", + "account_auth", + ("resource", "authorization_servers"), + ), + ( + "MCP Server Card", + ( + "/.well-known/mcp/server-card.json", + "/.well-known/mcp.json", + "/.well-known/mcp/server-cards.json", + ), + "application/json, */*;q=0.5", + "Protocol Discovery", + "protocols", + ("name",), + ), + ( + "A2A Agent Card", + ( + "/.well-known/agent-card.json", + "/.well-known/a2a-agent.json", + "/.well-known/agent.json", + ), + "application/json, */*;q=0.5", + "Protocol Discovery", + "protocols", + ("name",), + ), + ( + "Agent Skills index", + ( + "/.well-known/agent-skills/index.json", + "/.well-known/skills/index.json", + "/.well-known/agent-skills.json", + ), + "application/json, */*;q=0.5", + "Protocol Discovery", + "protocols", + ("skills",), + ), + ( + "WebMCP manifest", + ("/.well-known/webmcp.json", "/.well-known/webmcp"), + "application/json, */*;q=0.5", + "Protocol Discovery", + "protocols", + ("name", "tools"), + ), + ( + "ARD static catalog", + ("/.well-known/ai-catalog.json",), + "application/json, */*;q=0.5", + "Protocol Discovery", + "protocols", + ("specVersion", "entries"), + ), + ( + "x402 payment metadata", + ("/.well-known/x402", "/.well-known/x402.json"), + "application/json, */*;q=0.5", + "Commerce", + "commerce", + ("accepts", "resource"), + ), + ( + "MPP commerce metadata", + ("/.well-known/mpp.json",), + "application/json, */*;q=0.5", + "Commerce", + "commerce", + ("version", "manifest"), + ), + ( + "UCP commerce metadata", + ("/.well-known/ucp.json",), + "application/json, */*;q=0.5", + "Commerce", + "commerce", + ("version", "manifest"), + ), + ( + "ACP commerce metadata", + ("/.well-known/acp.json",), + "application/json, */*;q=0.5", + "Commerce", + "commerce", + ("version", "manifest"), + ), +) + +# Top-level keys that, taken alone, indicate a soft-404 / generic error +# response rather than a real discovery document. Bodies whose only +# top-level keys come from this set are rejected by ``_looks_like_json`` +# to prevent SPA/CDN error pages from passing protocol probes. +_ERROR_ONLY_KEYS: frozenset[str] = frozenset({"error", "message", "status", "code"}) + +_AUTH_MD_PATHS = ("/auth.md", "/.well-known/auth.md") +_DNS_PREFIXES = ("_index._agents", "_a2a._agents", "_mcp._agents") +_DNS_TYPES = ("SVCB", "HTTPS", "TXT") + + +@dataclass(frozen=True) +class ProbeResult: + label: str + category: str + passed: bool + included: bool = True + + +def _looks_like_json( + response: FetchResult, + require_keys: list[str] | tuple[str, ...] | None = None, +) -> bool: + """Decide whether ``response`` looks like a real JSON discovery document. + + Beyond the basic content-type + parseable-JSON gate, two shape checks + protect against soft-404 bodies: + + 1. **Error-only rejection** — if the parsed body is a dict whose + top-level keys are all members of ``_ERROR_ONLY_KEYS`` (e.g. + ``{"error": "not found"}``), the body is treated as a generic error + envelope rather than a discovery document. + 2. **Surface-specific required keys** — when ``require_keys`` is + supplied, the dict must contain at least one of those keys to be + considered a valid document for the probed surface (e.g. an MCP + card must have ``name``, OAuth metadata must have ``issuer``). + JSON arrays and scalars are rejected when ``require_keys`` is set. + """ + content_type = response.headers.get("content-type", "").lower() + if "json" not in content_type and "linkset" not in content_type: + return False + try: + parsed = json.loads(response.text) + except json.JSONDecodeError: + return False + if not isinstance(parsed, (dict, list)): + return False + if isinstance(parsed, list): + # Lists cannot satisfy dict-shape requirements; only return True + # when no shape validation was requested. + return require_keys is None + # Error-only rejection: every top-level key is a generic error field. + if parsed and set(parsed).issubset(_ERROR_ONLY_KEYS): + return False + if require_keys: + return any(key in parsed for key in require_keys) + return True + + +def _looks_like_auth_md(response: FetchResult) -> bool: + sample = response.text.strip()[:3000].lower() + if len(sample) < 20: + return False + return response.text.lstrip().startswith("#") or ("auth" in sample and "agent" in sample) + + +def _has_agent_link_header(context: AuditContext) -> bool: + if not context.homepage.ok: + return False + link_header = context.homepage.headers.get("link", "").lower() + return any(token in link_header for token in _LINK_HEADER_TOKENS) + + +def _dns_candidates(context: AuditContext) -> list[str]: + hostname = urlparse(context.url).hostname + if not hostname: + return [] + + roots = [] + for root in (hostname, hostname.removeprefix("www.")): + if root not in roots: + roots.append(root) + + return [ + f"{prefix}.{root}" + for root in roots + for prefix in _DNS_PREFIXES + ] + + +# RCODE values from dnspython that indicate the name does not exist. +# NXDOMAIN (3) means "no such name" — we can stop probing other record +# types and other prefixes for the same base name. Empty domain (5) +# similarly indicates an unreachable name and short-circuits cleanly. +_NXDOMAIN_RCODES = {3, 5} + + +async def _has_dns_aid(context: AuditContext) -> bool: + try: + import dns.asyncresolver + import dns.exception + except ImportError: + return False + + resolver = dns.asyncresolver.Resolver() + resolver.lifetime = 2 + resolver.timeout = 2 + + for candidate in _dns_candidates(context): + base_name = candidate.split(".", 1)[1] if "." in candidate else candidate + for record_type in _DNS_TYPES: + try: + answers = await resolver.resolve(candidate, record_type) + except dns.resolver.NoNameservers: + # No working nameserver — treat as inconclusive, keep going. + continue + except dns.exception.Timeout: + continue + except dns.resolver.NXDOMAIN as exc: + # NXDOMAIN on the base name → skip remaining record types + # and prefixes rooted at the same name. Sub-prefix lookups + # under an NXDOMAIN apex are guaranteed to fail. + if base_name == candidate.split(".", 1)[1] and exc.rcode() in _NXDOMAIN_RCODES: + break + continue + except dns.resolver.NoAnswer: + # Name exists but no records of this type — try next type. + continue + except Exception: + continue + if answers: + return True + return False + + +async def _json_surface_available( + context: AuditContext, + paths: tuple[str, ...], + accept: str, + require_keys: tuple[str, ...] | None = None, +) -> bool: + responses = await asyncio.gather( + *[fetch_url(make_root_url(context.url, path), accept=accept) for path in paths] + ) + return any( + response.ok and _looks_like_json(response, require_keys) + for response in responses + ) + + +async def _auth_md_available(context: AuditContext) -> bool: + responses = await asyncio.gather( + *[ + fetch_url(make_root_url(context.url, path), accept="text/markdown, text/plain, */*;q=0.5") + for path in _AUTH_MD_PATHS + ] + ) + return any(response.ok and _looks_like_auth_md(response) for response in responses) + + +def _scope_included(scope: str, include_protocols: bool, include_account_auth: bool, include_ecommerce: bool) -> bool: + if scope == "core": + return True + if scope == "protocols": + return include_protocols + if scope == "account_auth": + return include_account_auth + if scope == "commerce": + return include_ecommerce + return False + + +# Core probes that are always part of the default-scope strict-agent lens +# and do not depend on any optional scope flag. These 7 names mirror the +# unconditional ``ProbeResult(...)`` entries constructed in +# ``build_agent_readiness_summary``. ``auth.md`` is added separately below +# because it is gated by ``include_account_auth`` via +# ``ProbeResult(included=include_account_auth)``. +_CORE_PROBES: tuple[str, ...] = ( + "robots.txt published", + "valid sitemap discovery", + "agent discovery Link headers", + "DNS-AID records", + "llms.txt or Markdown negotiation", + "AI-specific robots.txt rules", + "Content Signals in robots.txt", +) + + +def _scope_probe_labels( + include_protocols: bool, + include_account_auth: bool, + include_ecommerce: bool, +) -> list[str]: + """Enumerate the strict-agent probe labels for the resolved scope. + + Mirrors the probe list constructed by ``build_agent_readiness_summary`` + so consumers can rely on ``len(passed) + len(missing) == max`` in both + the success and degraded-fallback paths. + """ + labels: list[str] = list(_CORE_PROBES) + # Web Bot Auth directory is the single core JSON surface. + labels.extend(label for (label, _, _, _, scope, _) in _JSON_SURFACES if scope == "core") + if include_account_auth: + # The hardcoded ``auth.md`` probe is gated by include_account_auth + # in ``build_agent_readiness_summary``. + labels.append("auth.md") + labels.extend( + label + for (label, _, _, _, scope, _) in _JSON_SURFACES + if scope != "core" + and _scope_included(scope, include_protocols, include_account_auth, include_ecommerce) + ) + return labels + + +def _category_summaries(probes: list[ProbeResult]) -> list[AgentReadinessCategory]: + categories = [ + "Discoverability", + "Content Accessibility", + "Bot Access Control", + "Protocol Discovery", + "Commerce", + ] + summaries: list[AgentReadinessCategory] = [] + for category in categories: + category_probes = [probe for probe in probes if probe.category == category] + included = [probe for probe in category_probes if probe.included] + passed = [probe.label for probe in included if probe.passed] + missing = [probe.label for probe in included if not probe.passed] + excluded = [probe.label for probe in category_probes if not probe.included] + earned = len(passed) + maximum = len(included) + score = round((earned / maximum) * 100) if maximum else 0 + summaries.append( + AgentReadinessCategory( + name=category, + earned=earned, + max=maximum, + score=score, + passed=passed, + missing=missing, + excluded=excluded, + ) + ) + return summaries + + +async def build_agent_readiness_summary( + context: AuditContext, + include_protocols: bool = False, + include_account_auth: bool = False, + include_ecommerce: bool = False, +) -> AgentReadinessSummary: + sitemap_valid, _, _, _, _ = await best_sitemap(context) + text_access_available, _ = await agent_text_access(context) + json_surface_results = [False for _ in _JSON_SURFACES] + json_surface_tasks = [] + json_surface_indices = [] + for index, (_, paths, accept, _, scope, require_keys) in enumerate(_JSON_SURFACES): + if _scope_included(scope, include_protocols, include_account_auth, include_ecommerce): + json_surface_tasks.append( + _json_surface_available(context, paths, accept, require_keys) + ) + json_surface_indices.append(index) + if json_surface_tasks: + json_surface_found = await asyncio.gather(*json_surface_tasks) + for index, found in zip(json_surface_indices, json_surface_found, strict=True): + json_surface_results[index] = found + + auth_md_available = await _auth_md_available(context) if include_account_auth else False + + probes = [ + ProbeResult( + "robots.txt published", + "Discoverability", + context.robots.ok and bool(context.robots.text.strip()), + ), + ProbeResult("valid sitemap discovery", "Discoverability", sitemap_valid), + ProbeResult("agent discovery Link headers", "Discoverability", _has_agent_link_header(context)), + ProbeResult("DNS-AID records", "Discoverability", await _has_dns_aid(context)), + ProbeResult("llms.txt or Markdown negotiation", "Content Accessibility", text_access_available), + ProbeResult( + "AI-specific robots.txt rules", + "Bot Access Control", + explicit_ai_bot_count(context.robots.text) > 0 if context.robots.ok else False, + ), + ProbeResult( + "Content Signals in robots.txt", + "Bot Access Control", + bool(content_signal_tokens(context.robots.text)) if context.robots.ok else False, + ), + ProbeResult( + "auth.md", + "Bot Access Control", + auth_md_available, + included=include_account_auth, + ), + ] + probes.extend( + ProbeResult( + label, + category, + passed, + included=_scope_included(scope, include_protocols, include_account_auth, include_ecommerce), + ) + for (label, _, _, category, scope, _), passed in zip(_JSON_SURFACES, json_surface_results, strict=True) + ) + + included_probes = [probe for probe in probes if probe.included] + passed = [probe.label for probe in included_probes if probe.passed] + missing = [probe.label for probe in included_probes if not probe.passed] + excluded = [probe.label for probe in probes if not probe.included] + earned = len(passed) + maximum = len(included_probes) + score = round((earned / maximum) * 100) if maximum else 0 + + if score >= 70: + label = "Strong agent-native readiness" + elif score >= 40: + label = "Developing agent-native readiness" + elif score > 0: + label = "Limited agent-native readiness" + else: + label = "Limited agent-native readiness" + + return AgentReadinessSummary( + score=score, + earned=earned, + max=maximum, + label=label, + categories=_category_summaries(probes), + passed=passed, + missing=missing, + not_checked=[ + *[f"{label} excluded by audit scope." for label in excluded], + "WebMCP runtime tool registration requires browser instrumentation and is available in advanced coverage.", + "Verified crawler IP treatment, live search rankings, live index coverage, and model citation share require external or authenticated data.", + ], + benchmark=build_agent_benchmark_comparison( + score, + earned, + maximum, + include_protocols, + include_account_auth, + include_ecommerce, + ), + caveat=( + "This strict lens follows explicit agent-native discovery signals selected for " + "this audit scope. A site can score well on SEO basics or general crawlability " + "while still scoring low here if it has not published relevant agent-specific surfaces." + ), + ) diff --git a/backend/app/audit_context.py b/backend/app/audit_context.py new file mode 100644 index 0000000000000000000000000000000000000000..cea87c1588f5c564729a88d67515929406fe095f --- /dev/null +++ b/backend/app/audit_context.py @@ -0,0 +1,21 @@ +import asyncio +from dataclasses import dataclass + +from app.fetching import FetchResult, fetch_url, make_root_url + + +@dataclass(frozen=True) +class AuditContext: + url: str + homepage: FetchResult + robots: FetchResult + sitemap: FetchResult + + +async def build_audit_context(url: str) -> AuditContext: + homepage, robots, sitemap = await asyncio.gather( + fetch_url(url), + fetch_url(make_root_url(url, "/robots.txt")), + fetch_url(make_root_url(url, "/sitemap.xml")), + ) + return AuditContext(url=url, homepage=homepage, robots=robots, sitemap=sitemap) diff --git a/backend/app/benchmarks.py b/backend/app/benchmarks.py new file mode 100644 index 0000000000000000000000000000000000000000..b97b2ff5867419dec33fd9d73793608554057577 --- /dev/null +++ b/backend/app/benchmarks.py @@ -0,0 +1,860 @@ +"""Per-check benchmark peer profiles (schema v2). + +Peer profiles are stored per-check rather than as pre-baked per-scope +variants. A single peer record captures the results of one full-scope +audit run (essentials_checks for the 13 included groups plus the +agent_passed probe labels). Peer scores are then recomputed at query +time from the user's chosen scope: + +- ``peer_essentials`` sums score/max over the 13 groups, applying the + SAME exclusion rule as ``_checked_points`` (rows with + ``state == "locked"`` OR ``evidence_level == "unknown"`` contribute + to neither numerator nor denominator). +- ``peer_agent`` counts how many of the passed labels match the + current scope's probe list (``_scope_probe_labels``). Labels in + ``agent_passed`` that are no longer present in the current probe + list are silently ignored, so profile snapshots survive probe-list + evolution. + +The public tree ships a hand-curated ``_SAMPLE_BENCHMARK_SEEDS`` for +the demo experience. The private deploy refreshes the on-disk snapshot +monthly via ``scripts/refresh_benchmarks.py``. +""" +import json +import os +from dataclasses import dataclass +from pathlib import Path +from statistics import median +from typing import Any + +from app.models import ( + AgentBenchmarkComparison, + BenchmarkComparison, + BenchmarkEntry, + CheckResult, + PillarScores, +) +from app.rubric import ESSENTIALS_CHECKED_MAX, ESSENTIALS_CHECK_GROUPS + +# ``_scope_probe_labels`` is imported lazily inside ``peer_agent`` to break +# the import cycle: ``app.agent_readiness`` imports ``build_agent_benchmark_comparison`` +# from this module, so a top-level import here would deadlock on the +# partially-initialized module. + +SCHEMA_VERSION = 2 +BENCHMARK_SNAPSHOT_DATE = "2026-07-17" # fallback only when no file is loaded +BENCHMARK_BASIS = "Essentials evidence score from the MachineRead audit" +AGENT_BENCHMARK_BASIS = "Agent-native readiness score from the MachineRead audit" +BENCHMARK_CAVEAT = ( + "Benchmark peers are scored under the same selected Essentials scope using bounded " + "public HTTP, DNS, and page evidence. Comparable scores do not imply comparable AI " + "exposure, search traffic, ecommerce conversion, ranking strength, backlinks, social " + "traction, real Google/Bing/Brave index coverage, Core Web Vitals field data, or live " + "model citation share. " + f"The current Essentials denominator is {ESSENTIALS_CHECKED_MAX} checked points across " + f"{len(ESSENTIALS_CHECK_GROUPS)} included check groups; each group may aggregate " + "several underlying signals. Review agent-native readiness separately for explicit " + "agent discovery." +) +AGENT_BENCHMARK_CAVEAT = ( + "This benchmark compares explicit agent-native discovery and protocol signals under " + "the same selected audit scope. Low scores are common among current large sites, but " + "that should be read as market immaturity rather than evidence that missing surfaces " + "are irrelevant. Stored profile earned counts are normalized to the current scope " + "denominator when the strict probe list changes." +) + +BenchmarkProfile = dict[str, Any] + + +@dataclass(frozen=True) +class _CheckSnapshot: + """Immutable per-check snapshot stored in a loaded v2 profile. + + The on-disk JSON keeps keys ``score``, ``max``, ``state``, and + ``evidence_level`` (per the public schema); after validation we + freeze each entry into this dataclass so the runtime never + mutates the snapshot. + """ + + score: int + max_score: int + state: str + evidence_level: str + + +_DEFAULT_BENCHMARK_PROFILE_PATH = ( + Path(__file__).resolve().parents[1] / "private_data" / "benchmark_profiles.json" +) + + +# --- Validation (eager, at load time) ------------------------------------- + +def _validate_profile( + profile: dict, + valid_check_names: set[str], + rubric_max: dict[str, int], +) -> None: + """Raise ValueError if profile is malformed. Failure is loud at startup.""" + for key in ("name", "category", "group", "size", "url", "essentials_checks", "agent_passed"): + if key not in profile: + raise ValueError(f"profile missing required key {key!r}") + for key in ("name", "category", "group", "size", "url"): + if not isinstance(profile[key], str): + raise ValueError( + f"profile {profile.get('name')!r}: {key!r} must be a string, " + f"got {type(profile[key]).__name__}" + ) + checks = profile["essentials_checks"] + if not isinstance(checks, dict): + raise ValueError(f"profile {profile['name']!r}: essentials_checks must be a dict") + actual = set(checks.keys()) + if actual != valid_check_names: + missing = valid_check_names - actual + extra = actual - valid_check_names + problems = [] + if missing: + problems.append(f"missing {sorted(missing)}") + if extra: + problems.append(f"unknown {sorted(extra)}") + raise ValueError( + f"profile {profile['name']!r}: essentials_checks keys: {'; '.join(problems)}" + ) + for check_name, entry in checks.items(): + if not isinstance(entry, dict): + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}] must be a dict" + ) + for key in ("score", "max", "state", "evidence_level"): + if key not in entry: + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}] " + f"missing {key!r}" + ) + if not isinstance(entry["score"], int) or isinstance(entry["score"], bool): + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}].score " + f"must be an int" + ) + if not isinstance(entry["max"], int) or isinstance(entry["max"], bool): + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}].max " + f"must be an int" + ) + if entry["max"] != rubric_max[check_name]: + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}].max " + f"is {entry['max']}, rubric says {rubric_max[check_name]}" + ) + if not (0 <= entry["score"] <= entry["max"]): + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}].score " + f"{entry['score']} not in [0, {entry['max']}]" + ) + if entry["state"] not in ("pass", "partial", "fail", "warn", "locked"): + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}].state " + f"{entry['state']!r} unknown" + ) + if entry["evidence_level"] not in ("verified", "inferred", "unknown"): + raise ValueError( + f"profile {profile['name']!r}: essentials_checks[{check_name!r}].evidence_level " + f"{entry['evidence_level']!r} unknown" + ) + agent_passed = profile["agent_passed"] + if not isinstance(agent_passed, list): + raise ValueError(f"profile {profile['name']!r}: agent_passed must be a list") + for i, label in enumerate(agent_passed): + if not isinstance(label, str): + raise ValueError( + f"profile {profile['name']!r}: agent_passed[{i}] must be a string, " + f"got {type(label).__name__}" + ) + + +def _coerce_entry(entry: Any) -> _CheckSnapshot: + """Accept either a loaded ``_CheckSnapshot`` or a raw dict with + ``score``/``max``/``state``/``evidence_level`` keys. Used by + ``_check_payload`` so that ad-hoc test profiles (dict shape) and + loaded profiles (frozen shape) both work. + """ + if isinstance(entry, _CheckSnapshot): + return entry + return _CheckSnapshot( + score=int(entry["score"]), + max_score=int(entry["max"]), + state=entry["state"], + evidence_level=entry["evidence_level"], + ) + + +def _check_payload(profile: dict) -> list[CheckResult]: + """Project a v2 profile's essentials_checks into CheckResult-like rows so + peer_essentials can reuse the existing _checked_points rule. + """ + pillar_by_check = {g.check_name: g.pillar for g in ESSENTIALS_CHECK_GROUPS} + label_by_check = {g.check_name: g.label for g in ESSENTIALS_CHECK_GROUPS} + rows = [] + for check_name, entry in profile["essentials_checks"].items(): + snap = _coerce_entry(entry) + rows.append( + CheckResult( + pillar=pillar_by_check[check_name], + check_name=check_name, + label=label_by_check[check_name], + state=snap.state, + score=snap.score, + max_score=snap.max_score, + finding="", + fix="", + effort="low", + evidence_level=snap.evidence_level, + ) + ) + return rows + + +def peer_essentials(profile: dict) -> tuple[int, int, PillarScores]: + """Sum score/max over the 13 groups, applying the SAME exclusion rule + as ``_checked_points()`` (rows with ``state == 'locked'`` OR + ``evidence_level == 'unknown'`` contribute to neither numerator nor + denominator). Returns ``(checked_score, checked_max, pillar_scores)``. + """ + rows = _check_payload(profile) + checked_score, checked_max = _checked_points(rows) + by_pillar = {"off_site": 0, "scrapability": 0, "seo": 0} + pillar_by_check = {g.check_name: g.pillar for g in ESSENTIALS_CHECK_GROUPS} + for row in rows: + if row.state == "locked" or row.evidence_level == "unknown": + continue + by_pillar[pillar_by_check[row.check_name]] += row.score + return checked_score, checked_max, PillarScores(**by_pillar) + + +def peer_agent( + profile: dict, + include_protocols: bool, + include_account_auth: bool, + include_ecommerce: bool, +) -> tuple[int, int]: + """Count how many probes the peer passed in the current scope. + Labels in ``agent_passed`` that no longer exist in + ``_scope_probe_labels`` are silently ignored (robust to probe-list + evolution). + """ + from app.agent_readiness import _scope_probe_labels # lazy: break import cycle + + labels = _scope_probe_labels(include_protocols, include_account_auth, include_ecommerce) + passed = set(profile["agent_passed"]) + earned = sum(1 for label in labels if label in passed) + return earned, len(labels) + + +# --- _agent_max_for_scope (KEEP — used by tests) --------------------------- + +def _agent_max_for_scope( + include_protocols: bool = False, + include_account_auth: bool = False, + include_ecommerce: bool = False, +) -> int: + return 8 + (6 if include_protocols else 0) + (3 if include_account_auth else 0) + ( + 4 if include_ecommerce else 0 + ) + + +# --- Scope-key helper (KEEP for legacy tests + label display) -------------- + +def benchmark_scope_key( + include_protocols: bool = False, + include_account_auth: bool = False, + include_ecommerce: bool = False, +) -> str: + """Label-only display helper. v2 stores one profile per peer; this key + is preserved for tests and UI display that asserts on the variant + shape. It is no longer used by the benchmarks comparison path. + """ + return f"p{int(include_protocols)}_a{int(include_account_auth)}_c{int(include_ecommerce)}" + + +# --- Sample seeds (12 fictional peers, v2 profile dicts) ------------------ + +# Each peer's per-check scores were chosen so the sum over kept rows equals +# the v1 checked_score for the corresponding peer. agent_passed labels were +# distributed so commerce/API peers include protocol-scope probes while +# corporate/editorial peers do not. + +_BASE_CORE_LABELS = ( + "robots.txt published", + "valid sitemap discovery", + "agent discovery Link headers", + "DNS-AID records", + "llms.txt or Markdown negotiation", + "AI-specific robots.txt rules", + "Content Signals in robots.txt", +) +_PROTOCOL_LABELS = ( + "API Catalog", + "MCP Server Card", + "A2A Agent Card", + "Agent Skills index", + "WebMCP manifest", + "ARD static catalog", +) +_AUTH_LABEL = ("auth.md",) + + +def _seed_profile( + *, + name: str, + category: str, + group: str, + size: str, + url: str, + check_scores: dict[str, int], + agent_passed: list[str], +) -> dict[str, Any]: + """Build a v2 profile dict from per-check score map and passed label list.""" + by_check = {g.check_name: g for g in ESSENTIALS_CHECK_GROUPS} + essentials_checks: dict[str, dict[str, Any]] = {} + for check_name, group_obj in by_check.items(): + max_score = group_obj.max_score + score = check_scores[check_name] + if score == max_score: + state = "pass" + elif score > 0: + state = "partial" + else: + state = "fail" + essentials_checks[check_name] = { + "score": score, + "max": max_score, + "state": state, + "evidence_level": "verified", + } + return { + "name": name, + "category": category, + "group": group, + "size": size, + "url": url, + "essentials_checks": essentials_checks, + "agent_passed": list(agent_passed), + } + + +def _commerce_passed(base_earned: int, *, with_protocols: bool = False) -> list[str]: + """Return a plausible agent_passed list for a commerce-style peer.""" + passed = list(_BASE_CORE_LABELS[: min(len(_BASE_CORE_LABELS), base_earned)]) + if with_protocols and base_earned > len(_BASE_CORE_LABELS): + slots = base_earned - len(_BASE_CORE_LABELS) + passed.extend(_PROTOCOL_LABELS[:slots]) + return passed + + +def _editorial_passed(base_earned: int) -> list[str]: + """Return a plausible agent_passed list for an editorial/corporate peer.""" + return list(_BASE_CORE_LABELS[: min(len(_BASE_CORE_LABELS), base_earned)]) + + +# v1 totals per peer (off_site, scrapability, seo) -> rebuilt here as per-check +# distributions that sum to the same totals. Sample-only; the private deploy +# regenerates real data via scripts/refresh_benchmarks.py. +_SAMPLE_BENCHMARK_SEEDS: list[dict] = [ + # Commerce enterprise, strong scrapability + _seed_profile( + name="Example Retail Enterprise", + category="Major retailer", + group="ecommerce", + size="enterprise", + url="https://example.com/retail", + check_scores={ + "social": 1, "wikipedia": 4, + "robots_txt": 6, "bot_access": 6, "html_structure": 4, + "schema_ld": 5, "llms_txt": 0, "ssr": 2, "machine_surfaces": 2, + "pagespeed": 2, "canonical": 5, "indexing": 4, "search_discovery": 3, + }, + agent_passed=_commerce_passed(3, with_protocols=False), + ), + # Commerce enterprise, balanced + _seed_profile( + name="Example Consumer Brand", + category="Major consumer brand", + group="ecommerce", + size="enterprise", + url="https://example.com/consumer", + check_scores={ + "social": 2, "wikipedia": 3, + "robots_txt": 5, "bot_access": 5, "html_structure": 3, + "schema_ld": 4, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 2, "canonical": 5, "indexing": 4, "search_discovery": 3, + }, + agent_passed=_commerce_passed(2, with_protocols=False), + ), + # Commerce enterprise, strong on protocol surfaces (API catalog etc.) + _seed_profile( + name="Example Commerce Platform", + category="Commerce platform", + group="ecommerce", + size="enterprise", + url="https://example.com/platform", + check_scores={ + "social": 2, "wikipedia": 4, + "robots_txt": 6, "bot_access": 6, "html_structure": 4, + "schema_ld": 5, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3, + }, + agent_passed=_commerce_passed(5, with_protocols=True), + ), + # Specialty DTC product, mid-tier + _seed_profile( + name="Example Product Studio", + category="Niche DTC product", + group="ecommerce", + size="specialty", + url="https://example.com/product", + check_scores={ + "social": 1, "wikipedia": 3, + "robots_txt": 5, "bot_access": 5, "html_structure": 4, + "schema_ld": 4, "llms_txt": 0, "ssr": 4, "machine_surfaces": 2, + "pagespeed": 3, "canonical": 5, "indexing": 4, "search_discovery": 3, + }, + agent_passed=_commerce_passed(3, with_protocols=False), + ), + # Niche beauty brand, mid-tier + _seed_profile( + name="Example Beauty Brand", + category="Niche beauty brand", + group="ecommerce", + size="specialty", + url="https://example.com/beauty", + check_scores={ + "social": 1, "wikipedia": 3, + "robots_txt": 5, "bot_access": 5, "html_structure": 4, + "schema_ld": 4, "llms_txt": 0, "ssr": 4, "machine_surfaces": 2, + "pagespeed": 3, "canonical": 5, "indexing": 4, "search_discovery": 2, + }, + agent_passed=_commerce_passed(3, with_protocols=False), + ), + # Specialty commerce, weak + _seed_profile( + name="Example Outdoor Shop", + category="Specialty commerce", + group="ecommerce", + size="specialty", + url="https://example.com/outdoor", + check_scores={ + "social": 1, "wikipedia": 1, + "robots_txt": 3, "bot_access": 3, "html_structure": 2, + "schema_ld": 2, "llms_txt": 0, "ssr": 2, "machine_surfaces": 2, + "pagespeed": 1, "canonical": 3, "indexing": 2, "search_discovery": 2, + }, + agent_passed=_commerce_passed(1, with_protocols=False), + ), + # Boutique commerce, strong SEO + _seed_profile( + name="Example Paper Goods", + category="Boutique product", + group="ecommerce", + size="boutique", + url="https://example.com/paper", + check_scores={ + "social": 2, "wikipedia": 2, + "robots_txt": 4, "bot_access": 4, "html_structure": 2, + "schema_ld": 3, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3, + }, + agent_passed=_commerce_passed(2, with_protocols=False), + ), + # Boutique commerce, weak + _seed_profile( + name="Example Desk Goods", + category="Boutique product", + group="ecommerce", + size="boutique", + url="https://example.com/desk", + check_scores={ + "social": 1, "wikipedia": 1, + "robots_txt": 2, "bot_access": 2, "html_structure": 1, + "schema_ld": 1, "llms_txt": 0, "ssr": 1, "machine_surfaces": 1, + "pagespeed": 1, "canonical": 2, "indexing": 1, "search_discovery": 0, + }, + agent_passed=_commerce_passed(1, with_protocols=False), + ), + # Major technology brand (corporate), mid-tier + _seed_profile( + name="Example Technology Company", + category="Major technology brand", + group="corporate", + size="enterprise", + url="https://example.com/technology", + check_scores={ + "social": 1, "wikipedia": 3, + "robots_txt": 6, "bot_access": 6, "html_structure": 4, + "schema_ld": 4, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 2, "canonical": 5, "indexing": 4, "search_discovery": 3, + }, + agent_passed=_editorial_passed(3), + ), + # Developer platform, strong on protocols + _seed_profile( + name="Example Developer Platform", + category="Developer platform", + group="corporate", + size="specialty", + url="https://example.com/developer", + check_scores={ + "social": 2, "wikipedia": 4, + "robots_txt": 6, "bot_access": 6, "html_structure": 4, + "schema_ld": 5, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3, + }, + agent_passed=_BASE_CORE_LABELS + _PROTOCOL_LABELS, + ), + # Software company (boutique), mid-tier + _seed_profile( + name="Example Software Studio", + category="Software company", + group="corporate", + size="boutique", + url="https://example.com/software", + check_scores={ + "social": 2, "wikipedia": 2, + "robots_txt": 5, "bot_access": 5, "html_structure": 3, + "schema_ld": 3, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 2, "canonical": 3, "indexing": 4, "search_discovery": 2, + }, + agent_passed=_editorial_passed(2), + ), + # Professional services / SaaS, strong on protocols + _seed_profile( + name="Example Scheduling Service", + category="SaaS service", + group="services", + size="specialty", + url="https://example.com/scheduling", + check_scores={ + "social": 2, "wikipedia": 4, + "robots_txt": 6, "bot_access": 6, "html_structure": 4, + "schema_ld": 5, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2, + "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3, + }, + agent_passed=_BASE_CORE_LABELS + _PROTOCOL_LABELS, + ), +] + + +def _sample_benchmark_profiles() -> list[dict]: + """Return v2 profile dicts for the bundled sample seeds (validation happens + at loader time so the runtime never sees malformed sample data). + """ + return [dict(seed) for seed in _SAMPLE_BENCHMARK_SEEDS] + + +# --- Loader (parses v2 envelope) ------------------------------------------- + +def _configured_benchmark_profile_path() -> Path | None: + configured_path = os.getenv("MACHINEREAD_BENCHMARK_PROFILE_PATH") + if configured_path: + return Path(configured_path).expanduser() + return None + + +def _load_benchmark_profiles() -> tuple[BenchmarkProfile, ...]: + """Parse v2 envelope. Eager validation. Fail loud on malformed input. + + Returns an immutable tuple of dicts so callers cannot mutate the + snapshot at runtime. + """ + configured_path = _configured_benchmark_profile_path() + if configured_path: + if not configured_path.exists(): + raise FileNotFoundError(f"Benchmark profile file not found: {configured_path}") + payload = json.loads(configured_path.read_text(encoding="utf-8")) + elif _DEFAULT_BENCHMARK_PROFILE_PATH.exists(): + payload = json.loads(_DEFAULT_BENCHMARK_PROFILE_PATH.read_text(encoding="utf-8")) + else: + return tuple(_sample_benchmark_profiles()) + + # Detect v1 (bare list) shape and refuse to migrate + if isinstance(payload, list): + raise ValueError( + "Benchmark profile file is in the deprecated v1 (bare list) format. " + "Run `python scripts/refresh_benchmarks.py --peers " + "scripts/benchmark_peers.sample.json --out ` to migrate." + ) + if not isinstance(payload, dict): + raise ValueError( + f"Benchmark profile file: expected object, got {type(payload).__name__}" + ) + if payload.get("schema_version") != SCHEMA_VERSION: + raise ValueError( + f"Benchmark profile file: schema_version {payload.get('schema_version')!r} " + f"!= required {SCHEMA_VERSION}" + ) + profiles = payload.get("profiles") + if not isinstance(profiles, list): + raise ValueError("Benchmark profile file: 'profiles' must be a list") + + valid_check_names = {g.check_name for g in ESSENTIALS_CHECK_GROUPS} + rubric_max = {g.check_name: g.max_score for g in ESSENTIALS_CHECK_GROUPS} + validated: list[BenchmarkProfile] = [] + for profile in profiles: + _validate_profile(profile, valid_check_names, rubric_max) + validated.append({ + "name": profile["name"], + "category": profile["category"], + "group": profile["group"], + "size": profile["size"], + "url": profile["url"], + "essentials_checks": { + k: _CheckSnapshot( + score=int(v["score"]), + max_score=int(v["max"]), + state=v["state"], + evidence_level=v["evidence_level"], + ) + for k, v in profile["essentials_checks"].items() + }, + "agent_passed": tuple(profile["agent_passed"]), + }) + return tuple(validated) + + +_BENCHMARK_PROFILES: tuple[BenchmarkProfile, ...] = _load_benchmark_profiles() + + +def _loaded_snapshot_date() -> str: + """Read the snapshot date from the loaded profile file, or fall back to + the bundled constant. The bundled sample seeds have no file on disk, + so they fall back. + """ + configured_path = _configured_benchmark_profile_path() + if configured_path and configured_path.exists(): + payload = json.loads(configured_path.read_text(encoding="utf-8")) + if isinstance(payload, dict): + return str(payload.get("snapshot_date") or BENCHMARK_SNAPSHOT_DATE) + if _DEFAULT_BENCHMARK_PROFILE_PATH.exists(): + payload = json.loads(_DEFAULT_BENCHMARK_PROFILE_PATH.read_text(encoding="utf-8")) + if isinstance(payload, dict): + return str(payload.get("snapshot_date") or BENCHMARK_SNAPSHOT_DATE) + return BENCHMARK_SNAPSHOT_DATE + + +# --- Entry construction at query time ------------------------------------- + +def _entries( + include_protocols: bool, + include_account_auth: bool, + include_ecommerce: bool, +) -> list[BenchmarkEntry]: + """Build BenchmarkEntry per profile for the current scope. + + Replaces the v1 ``_entries_for_scope(scope_key)`` which keyed off + pre-baked per-scope variants. Scope is now derived from the three + booleans at call time. + """ + entries: list[BenchmarkEntry] = [] + for profile in _BENCHMARK_PROFILES: + checked_score, checked_max, pillar_scores = peer_essentials(profile) + agent_earned, agent_max = peer_agent( + profile, include_protocols, include_account_auth, include_ecommerce + ) + free_evidence_score = ( + round((checked_score / checked_max) * 100) if checked_max else 0 + ) + agent_readiness_score = ( + round((agent_earned / agent_max) * 100) if agent_max else 0 + ) + entries.append( + BenchmarkEntry( + name=profile["name"], + category=profile["category"], + group=profile["group"], + size=profile["size"], + url=profile["url"], + overall_score=checked_score, + free_evidence_score=free_evidence_score, + checked_score=checked_score, + checked_max=checked_max, + agent_readiness_score=agent_readiness_score, + agent_readiness_earned=agent_earned, + agent_readiness_max=agent_max, + pillar_scores=pillar_scores, + ) + ) + return entries + + +# --- _checked_points (KEEP) and free_evidence_score (KEEP) ----------------- + +def _checked_points(checks: list[CheckResult]) -> tuple[int, int]: + # Exclude paid-tier locked rows AND inconclusive (warn/unknown-evidence) rows. + # Warn-state fallbacks (e.g. transient fetch failures from _fallback_check_result) + # carry evidence_level='unknown' and score=0/max_score=group.max_score. Keeping + # them in the denominator silently drags the Evidence score down even when the + # real site satisfied every other check. Treat them as out-of-scope for the + # benchmark the same way reserved/paid rows are excluded. + checked = [ + check + for check in checks + if check.state != "locked" and check.evidence_level != "unknown" + ] + return ( + sum(check.score for check in checked), + sum(check.max_score for check in checked), + ) + + +def free_evidence_score(checks: list[CheckResult]) -> int: + checked_score, checked_max = _checked_points(checks) + if not checked_max: + return 0 + return round((checked_score / checked_max) * 100) + + +# --- Percentile / position helpers (KEEP unchanged) ------------------------ + +def _percentile(score: int, entries: list[BenchmarkEntry]) -> int: + if not entries: + return 0 + at_or_below = sum(entry.free_evidence_score <= score for entry in entries) + return round((at_or_below / len(entries)) * 100) + + +def _agent_percentile(score: int, entries: list[BenchmarkEntry]) -> int: + if not entries: + return 0 + at_or_below = sum(entry.agent_readiness_score <= score for entry in entries) + return round((at_or_below / len(entries)) * 100) + + +def _position_label(score: int, entries: list[BenchmarkEntry]) -> str: + scores = sorted(entry.free_evidence_score for entry in entries) + lower_quartile = scores[len(scores) // 4] + upper_quartile = scores[(len(scores) * 3) // 4] + median_score = round(median(scores)) + + if score >= upper_quartile: + return "Near the top of this Essentials benchmark snapshot" + if score >= median_score: + return "Above the middle of this Essentials benchmark snapshot" + if score >= lower_quartile: + return "Within the middle of this Essentials benchmark snapshot" + return "Below most sites in this Essentials benchmark snapshot" + + +def _agent_position_label(score: int, entries: list[BenchmarkEntry]) -> str: + scores = sorted(entry.agent_readiness_score for entry in entries) + lower_quartile = scores[len(scores) // 4] + upper_quartile = scores[(len(scores) * 3) // 4] + median_score = round(median(scores)) + + if score >= upper_quartile: + return "Near the top of this strict agent-readiness snapshot" + if score >= median_score: + return "Above the middle of this strict agent-readiness snapshot" + if score >= lower_quartile: + return "Within the middle of this strict agent-readiness snapshot" + return "Below most sites in this strict agent-readiness snapshot" + + +# --- Public API: build_benchmark_comparison -------------------------------- + +def build_benchmark_comparison( + checks: list[CheckResult], + include_protocols: bool = False, + include_account_auth: bool = False, + include_ecommerce: bool = False, +) -> BenchmarkComparison: + snapshot_date = _loaded_snapshot_date() + entries = sorted( + _entries(include_protocols, include_account_auth, include_ecommerce), + key=lambda entry: (-entry.free_evidence_score, entry.name), + ) + if not entries: + return BenchmarkComparison( + score=0, + checked_score=0, + checked_max=0, + benchmark_count=0, + median_score=0, + percentile=0, + position_label="No peers available", + nearest=[], + entries=[], + basis=BENCHMARK_BASIS, + snapshot_date=snapshot_date, + caveat=BENCHMARK_CAVEAT, + ) + + checked_score, checked_max = _checked_points(checks) + score = free_evidence_score(checks) + nearest = sorted( + entries, + key=lambda entry: (abs(entry.free_evidence_score - score), -entry.free_evidence_score, entry.name), + )[:3] + + return BenchmarkComparison( + score=score, + checked_score=checked_score, + checked_max=checked_max, + benchmark_count=len(entries), + median_score=round(median(entry.free_evidence_score for entry in entries)), + percentile=_percentile(score, entries), + position_label=_position_label(score, entries), + nearest=nearest, + entries=entries, + basis=BENCHMARK_BASIS, + snapshot_date=snapshot_date, + caveat=BENCHMARK_CAVEAT, + ) + + +def build_agent_benchmark_comparison( + score: int, + earned: int, + maximum: int, + include_protocols: bool = False, + include_account_auth: bool = False, + include_ecommerce: bool = False, +) -> AgentBenchmarkComparison: + snapshot_date = _loaded_snapshot_date() + entries = sorted( + _entries(include_protocols, include_account_auth, include_ecommerce), + key=lambda entry: (-entry.agent_readiness_score, entry.name), + ) + if not entries: + return AgentBenchmarkComparison( + score=0, + earned=0, + max=0, + benchmark_count=0, + median_score=0, + percentile=0, + position_label="No peers available", + nearest=[], + entries=[], + basis=AGENT_BENCHMARK_BASIS, + snapshot_date=snapshot_date, + caveat=AGENT_BENCHMARK_CAVEAT, + ) + + nearest = sorted( + entries, + key=lambda entry: (abs(entry.agent_readiness_score - score), -entry.agent_readiness_score, entry.name), + )[:3] + + return AgentBenchmarkComparison( + score=score, + earned=earned, + max=maximum, + benchmark_count=len(entries), + median_score=round(median(entry.agent_readiness_score for entry in entries)), + percentile=_agent_percentile(score, entries), + position_label=_agent_position_label(score, entries), + nearest=nearest, + entries=entries, + basis=AGENT_BENCHMARK_BASIS, + snapshot_date=snapshot_date, + caveat=AGENT_BENCHMARK_CAVEAT, + ) diff --git a/backend/app/checks/__init__.py b/backend/app/checks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/checks/__pycache__/__init__.cpython-311.pyc b/backend/app/checks/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7085ba9554ea2eecf5d56b27a3b030112c42373e Binary files /dev/null and b/backend/app/checks/__pycache__/__init__.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/__init__.cpython-312.pyc b/backend/app/checks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ec0476f0dee85aa51405642a469d2d13e293735 Binary files /dev/null and b/backend/app/checks/__pycache__/__init__.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/ard_catalog.cpython-311.pyc b/backend/app/checks/__pycache__/ard_catalog.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acbfc94c4de503981c71a25eb2327023274b73b6 Binary files /dev/null and b/backend/app/checks/__pycache__/ard_catalog.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/ard_catalog.cpython-312.pyc b/backend/app/checks/__pycache__/ard_catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b22ad17feb2d6a4954dde1a678fba6b03cb3c7f Binary files /dev/null and b/backend/app/checks/__pycache__/ard_catalog.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/bot_access.cpython-311.pyc b/backend/app/checks/__pycache__/bot_access.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ed8168da5a0c7fa7414a0330a521deb43a90309 Binary files /dev/null and b/backend/app/checks/__pycache__/bot_access.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/bot_access.cpython-312.pyc b/backend/app/checks/__pycache__/bot_access.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76e03af4612cb5f535b9bb524a0d0015f56b9c94 Binary files /dev/null and b/backend/app/checks/__pycache__/bot_access.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/canonical.cpython-311.pyc b/backend/app/checks/__pycache__/canonical.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e63dd0939c6ed8c41e67cd1622edf5f0206fb4f Binary files /dev/null and b/backend/app/checks/__pycache__/canonical.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/canonical.cpython-312.pyc b/backend/app/checks/__pycache__/canonical.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b6ea768623307875aed4aba623f006d0363abe9 Binary files /dev/null and b/backend/app/checks/__pycache__/canonical.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/extraction_readiness.cpython-311.pyc b/backend/app/checks/__pycache__/extraction_readiness.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f2b21e2e279c827bb2453c5a1d17dc3f21972e9 Binary files /dev/null and b/backend/app/checks/__pycache__/extraction_readiness.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/extraction_readiness.cpython-312.pyc b/backend/app/checks/__pycache__/extraction_readiness.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f83b037b96a264fd002cd9313b0891a41a4e070 Binary files /dev/null and b/backend/app/checks/__pycache__/extraction_readiness.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/html_structure.cpython-311.pyc b/backend/app/checks/__pycache__/html_structure.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04446b48f12447337d7dae5bcef677d18783cfe1 Binary files /dev/null and b/backend/app/checks/__pycache__/html_structure.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/html_structure.cpython-312.pyc b/backend/app/checks/__pycache__/html_structure.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e984792fb73d8ef9d0b568f45ebcb7f382dc8796 Binary files /dev/null and b/backend/app/checks/__pycache__/html_structure.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/indexing.cpython-311.pyc b/backend/app/checks/__pycache__/indexing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2576131c9e5c53680439b4203c582b87b205ddb5 Binary files /dev/null and b/backend/app/checks/__pycache__/indexing.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/indexing.cpython-312.pyc b/backend/app/checks/__pycache__/indexing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e618c45ba63eb85935782c0408b813bcec5bcc33 Binary files /dev/null and b/backend/app/checks/__pycache__/indexing.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/llms_txt.cpython-311.pyc b/backend/app/checks/__pycache__/llms_txt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8cab51faaebe5433192e9dde57a4acdbcfab1f2 Binary files /dev/null and b/backend/app/checks/__pycache__/llms_txt.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/llms_txt.cpython-312.pyc b/backend/app/checks/__pycache__/llms_txt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5bc13b57087de7baece18f9c11b6482c099d692 Binary files /dev/null and b/backend/app/checks/__pycache__/llms_txt.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/locked.cpython-311.pyc b/backend/app/checks/__pycache__/locked.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e31b823ee317569acf9bf946e2e711db504b563e Binary files /dev/null and b/backend/app/checks/__pycache__/locked.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/locked.cpython-312.pyc b/backend/app/checks/__pycache__/locked.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddbe9b604cbb3d5d1c98f35573a23ad11f7e83a8 Binary files /dev/null and b/backend/app/checks/__pycache__/locked.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/machine_surfaces.cpython-311.pyc b/backend/app/checks/__pycache__/machine_surfaces.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37ed6cda7ca23c070505008a83fc0616cc11f7e1 Binary files /dev/null and b/backend/app/checks/__pycache__/machine_surfaces.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/machine_surfaces.cpython-312.pyc b/backend/app/checks/__pycache__/machine_surfaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd875c0c156c187f6bdb3332b081c665ed3e65d1 Binary files /dev/null and b/backend/app/checks/__pycache__/machine_surfaces.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/pagespeed.cpython-311.pyc b/backend/app/checks/__pycache__/pagespeed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4171db1cddfacde903c27208c5c8f9e8eb6118a Binary files /dev/null and b/backend/app/checks/__pycache__/pagespeed.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/pagespeed.cpython-312.pyc b/backend/app/checks/__pycache__/pagespeed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a44259b9534c9abab7cb083aff7b376d33c9433 Binary files /dev/null and b/backend/app/checks/__pycache__/pagespeed.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/robots.cpython-311.pyc b/backend/app/checks/__pycache__/robots.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..535fdf25a909da20f7e9d879333f94d6fddb62d7 Binary files /dev/null and b/backend/app/checks/__pycache__/robots.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/robots.cpython-312.pyc b/backend/app/checks/__pycache__/robots.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db9b818474b9cf0082bafd3bd494757f8eb3ada0 Binary files /dev/null and b/backend/app/checks/__pycache__/robots.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/schema_ld.cpython-311.pyc b/backend/app/checks/__pycache__/schema_ld.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65243401fef2212aa2d8a69a62977ff48c604ef0 Binary files /dev/null and b/backend/app/checks/__pycache__/schema_ld.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/schema_ld.cpython-312.pyc b/backend/app/checks/__pycache__/schema_ld.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9942ac6bed77662680d3fb2c9c7e91afc7738b9 Binary files /dev/null and b/backend/app/checks/__pycache__/schema_ld.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/search_blurb.cpython-311.pyc b/backend/app/checks/__pycache__/search_blurb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9b4daad640842ab1050e571656054b52e8dfb5f Binary files /dev/null and b/backend/app/checks/__pycache__/search_blurb.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/search_blurb.cpython-312.pyc b/backend/app/checks/__pycache__/search_blurb.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e85d2c40c4521fc29e23a45527e06beb7288b358 Binary files /dev/null and b/backend/app/checks/__pycache__/search_blurb.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/search_discovery.cpython-311.pyc b/backend/app/checks/__pycache__/search_discovery.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3407830e5a3819cdfae1e501379e86e4dad41107 Binary files /dev/null and b/backend/app/checks/__pycache__/search_discovery.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/search_discovery.cpython-312.pyc b/backend/app/checks/__pycache__/search_discovery.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..149dc38f3bb9961d634abba342d96990f7640f73 Binary files /dev/null and b/backend/app/checks/__pycache__/search_discovery.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/sitemap_analysis.cpython-311.pyc b/backend/app/checks/__pycache__/sitemap_analysis.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59d208509d7ee7560e323556d0c25bfc4707c6d4 Binary files /dev/null and b/backend/app/checks/__pycache__/sitemap_analysis.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/sitemap_analysis.cpython-312.pyc b/backend/app/checks/__pycache__/sitemap_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86e0e06432385be9f4c34e7d7a5c95a5c745f385 Binary files /dev/null and b/backend/app/checks/__pycache__/sitemap_analysis.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/social.cpython-311.pyc b/backend/app/checks/__pycache__/social.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0bd42b2d55ce3832e64af0ff63cf338240cc8d5 Binary files /dev/null and b/backend/app/checks/__pycache__/social.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/social.cpython-312.pyc b/backend/app/checks/__pycache__/social.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f68c1ca56d0556b1782f2ae51eb5c3725a032123 Binary files /dev/null and b/backend/app/checks/__pycache__/social.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/ssr.cpython-311.pyc b/backend/app/checks/__pycache__/ssr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c7a1035ac0eed93c80357e5877e84822d96e349 Binary files /dev/null and b/backend/app/checks/__pycache__/ssr.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/ssr.cpython-312.pyc b/backend/app/checks/__pycache__/ssr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9774cdcb3b612523ab4c452596541bad2735a943 Binary files /dev/null and b/backend/app/checks/__pycache__/ssr.cpython-312.pyc differ diff --git a/backend/app/checks/__pycache__/wikipedia.cpython-311.pyc b/backend/app/checks/__pycache__/wikipedia.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39fcdc6a64f14c155c4c8b43e6fee1a9c20ce49f Binary files /dev/null and b/backend/app/checks/__pycache__/wikipedia.cpython-311.pyc differ diff --git a/backend/app/checks/__pycache__/wikipedia.cpython-312.pyc b/backend/app/checks/__pycache__/wikipedia.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..625b977c04caef7934f3cc20184b0048920149df Binary files /dev/null and b/backend/app/checks/__pycache__/wikipedia.cpython-312.pyc differ diff --git a/backend/app/checks/ard_catalog.py b/backend/app/checks/ard_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..5f29731402660fa4387700f51095840400c2eece --- /dev/null +++ b/backend/app/checks/ard_catalog.py @@ -0,0 +1,204 @@ +"""Pure bounded validation for ARD static catalog payloads.""" + +from __future__ import annotations + +import json +import re +from datetime import datetime +from typing import Any +from urllib.parse import urlparse + +_MAX_PAYLOAD_BYTES = 500 * 1024 +_SEMVER_PATTERN = re.compile(r"^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$") +_URN_AIR_PATTERN = re.compile(r"^urn:air:[a-z0-9.-]+(?::[a-z0-9._/-]+)+$", re.IGNORECASE) +_HTTP_SCHEMES = {"http", "https"} + + +def _looks_like_semver(value: str) -> bool: + return bool(_SEMVER_PATTERN.fullmatch(value.strip())) + + +def _non_empty_string(value: Any) -> bool: + return isinstance(value, str) and bool(value.strip()) + + +def _domain_matches_audit(value: Any, audit_domain: str) -> bool: + if not _non_empty_string(value) or not audit_domain: + return False + candidate = value.strip().lower().rstrip(".") + parsed = urlparse(candidate if "://" in candidate else f"https://{candidate}") + hostname = (parsed.hostname or "").lower().rstrip(".") + normalized_audit_domain = audit_domain.lower().removeprefix("www.") + normalized_hostname = hostname.removeprefix("www.") + return normalized_hostname == normalized_audit_domain or normalized_hostname.endswith( + f".{normalized_audit_domain}" + ) + + +def _entry_identifier(entry: dict[str, Any]) -> Any: + return entry.get("identifier") or entry.get("urn") or entry.get("id") + + +def _is_domain_anchored_urn(value: Any, audit_domain: str) -> bool: + if not _non_empty_string(value): + return False + identifier = value.strip() + if not _URN_AIR_PATTERN.fullmatch(identifier): + return False + if not audit_domain: + return True + publisher = identifier.split(":", 3)[2].lower().removeprefix("www.") + normalized_audit_domain = audit_domain.lower().removeprefix("www.") + return publisher == normalized_audit_domain or publisher.endswith(f".{normalized_audit_domain}") + + +def _is_timestamp(value: Any) -> bool: + if not _non_empty_string(value): + return False + candidate = value.strip() + try: + datetime.fromisoformat(candidate.replace("Z", "+00:00")) + except ValueError: + return False + return True + + +def _has_capability_metadata(entry: dict[str, Any]) -> bool: + for key in ("capabilities", "tags"): + value = entry.get(key) + if isinstance(value, list) and any(_non_empty_string(item) for item in value): + return True + return False + + +def _check_entry(entry: Any, audit_domain: str) -> list[str]: + if not isinstance(entry, dict): + return ["entry is not a JSON object"] + + issues: list[str] = [] + identifier = _entry_identifier(entry) + if not _non_empty_string(identifier): + issues.append("entry is missing `identifier`") + elif not _is_domain_anchored_urn(identifier, audit_domain): + issues.append(f"entry identifier `{identifier}` is not a domain-anchored `urn:air` value") + + if not _non_empty_string(entry.get("displayName")): + issues.append("entry is missing `displayName`") + if not _non_empty_string(entry.get("mediaType") or entry.get("type")): + issues.append("entry is missing `mediaType`") + + has_url = "url" in entry + has_data = "data" in entry + if has_url == has_data: + issues.append("entry must declare exactly one of `url` or `data`") + elif has_url: + if not _non_empty_string(entry.get("url")): + issues.append("entry `url` must be a non-empty HTTP(S) URL") + else: + parsed_url = urlparse(entry["url"].strip()) + if parsed_url.scheme.lower() not in _HTTP_SCHEMES or not parsed_url.netloc: + issues.append("entry `url` must be an absolute HTTP(S) URL") + elif not isinstance(entry.get("data"), dict): + issues.append("entry `data` must be an embedded JSON object") + + if not _non_empty_string(entry.get("description")): + issues.append("entry is missing `description`") + if not _has_capability_metadata(entry): + issues.append("entry is missing non-empty `capabilities` or `tags`") + + queries = entry.get("representativeQueries") + if not isinstance(queries, list) or not queries or not all(_non_empty_string(query) for query in queries): + issues.append("entry is missing non-empty `representativeQueries`") + + updated = entry.get("updated") or entry.get("updatedAt") or entry.get("lastUpdated") + if not _is_timestamp(updated): + issues.append("entry is missing an ISO 8601 `updated` timestamp") + + return issues + + +def _result( + valid: bool, + spec_version: str | None, + entry_count: int, + has_trust_manifest: bool, + issues: list[str], +) -> dict[str, Any]: + return { + "valid": valid, + "spec_version": spec_version, + "entry_count": entry_count, + "has_trust_manifest": has_trust_manifest, + "issues": issues, + "sample_issues": issues[:5], + } + + +def ard_catalog_quality(text: str, audit_url: str | None = None) -> dict[str, Any]: + """Validate an ARD catalog body without network or provider calls.""" + if not isinstance(text, str): + return _result(False, None, 0, False, ["ARD catalog body is not text"]) + + payload_size = len(text.encode("utf-8")) + if payload_size > _MAX_PAYLOAD_BYTES: + return _result( + False, + None, + 0, + False, + [f"ARD catalog payload exceeds the 500 KiB limit ({payload_size} bytes)"], + ) + if not text.strip(): + return _result(False, None, 0, False, ["ARD catalog body is empty"]) + + try: + catalog = json.loads(text) + except json.JSONDecodeError as exc: + return _result(False, None, 0, False, [f"ARD catalog is not valid JSON: {exc.msg}"]) + + if not isinstance(catalog, dict): + return _result(False, None, 0, False, ["ARD catalog root must be a JSON object"]) + + issues: list[str] = [] + spec_version = catalog.get("specVersion") + if not _non_empty_string(spec_version): + issues.append("ARD catalog is missing `specVersion`") + spec_version_value = None + else: + spec_version_value = spec_version.strip() + if not _looks_like_semver(spec_version_value): + issues.append(f"ARD catalog `specVersion` `{spec_version_value}` is not semver-shaped") + + audit_domain = "" + if audit_url: + audit_domain = (urlparse(audit_url).hostname or "").strip(".").lower() + + host = catalog.get("host") + if not isinstance(host, dict): + issues.append("ARD catalog is missing `host` metadata") + else: + host_domain = host.get("domain") or host.get("hostname") or host.get("url") + if host_domain is None: + issues.append("ARD catalog host metadata is missing `domain`") + elif audit_domain and not _domain_matches_audit(host_domain, audit_domain): + issues.append(f"ARD catalog host domain `{host_domain}` does not match the audited host") + elif not audit_domain and not _non_empty_string(host_domain): + issues.append("ARD catalog host `domain` must be non-empty") + + entries = catalog.get("entries") + if not isinstance(entries, list): + issues.append("ARD catalog is missing an `entries` list") + entry_count = 0 + else: + entry_count = len(entries) + for index, entry in enumerate(entries): + issues.extend(f"entry[{index}]: {issue}" for issue in _check_entry(entry, audit_domain)) + + has_trust_manifest = "trustManifest" in catalog or ( + isinstance(host, dict) and "trustManifest" in host + ) or any(isinstance(entry, dict) and "trustManifest" in entry for entry in entries or []) + + return _result(not issues, spec_version_value, entry_count, has_trust_manifest, issues) + + +__all__ = ["ard_catalog_quality"] diff --git a/backend/app/checks/bot_access.py b/backend/app/checks/bot_access.py new file mode 100644 index 0000000000000000000000000000000000000000..57ae62f2ad7470616e69f5438a2715e16dcbd38a --- /dev/null +++ b/backend/app/checks/bot_access.py @@ -0,0 +1,397 @@ +import asyncio +from dataclasses import dataclass +from urllib.parse import urljoin, urlparse + +from bs4 import BeautifulSoup + +from app.audit_context import AuditContext +from app.crawler_registry import active_crawler_caveats, fetch_probe_names +from app.fetching import BOT_USER_AGENTS, BROWSER_USER_AGENT, FetchResult, fetch_url +from app.models import CheckResult + +_MATRIX_BOTS = fetch_probe_names() + +_BLOCK_SIGNATURES = ( + "just a moment", + "checking your browser", + "cf-chl", + "cloudflare ray id", + "verify you are human", + "access denied", + "datadome", + "perimeterx", + "akamai bot manager", +) +# Substrings that indicate a generic anti-bot challenge page. The classic +# ``captcha`` substring is intentionally NOT in this list: contact forms and +# many legitimate pages embed Google reCAPTCHA `` + """.replace("__VARIANT__", variant) + + +def _complete_visible_product_html( + schema: str, + *, + price: str = "99.00", + include_variant: bool = True, +) -> str: + details = " ".join(f"durable product detail {index}" for index in range(90)) + variant = ( + '' + if include_variant + else '' + ) + return f""" + Trail shoe{schema}
+

Trail shoe

+ Trail shoe +

{details}

+

${price} In stock

+

SKU: SHOE-1

+ {variant} +

Free shipping and delivery. Returns and refunds are available.

+
+ """ + + +class ExtractionReadinessTests(unittest.TestCase): + def test_reports_good_local_source_metrics(self) -> None: + markdown = "# Extraction guide\n\n" + "Useful Markdown text for agents. " * 20 + result = analyse_extraction_readiness( + ExtractionReadinessInput( + url="https://example.com", + raw_html=_good_html(), + markdown_responses=[_response(markdown)], + llms_txt="# Example\n\n- [Guide](https://example.com/guide)", + sitemap_xml=( + "https://example.com/" + "2026-07-01" + ), + ) + ) + + self.assertEqual(result.rendering_state, "readable") + self.assertGreaterEqual(result.main_content_words, 80) + self.assertGreater(result.cleaned_text_bytes, 0) + self.assertLess(result.boilerplate_ratio, 0.1) + self.assertLess(result.navigation_ratio, 0.1) + self.assertFalse(result.app_shell_risk) + self.assertEqual(result.markdown_alternates_checked, 1) + self.assertEqual(result.markdown_usable_count, 1) + self.assertTrue(result.llms_txt_valid) + self.assertTrue(result.sitemap_valid) + self.assertEqual(result.sitemap_url_count, 1) + self.assertTrue(result.sitemap_has_lastmod) + + def test_flags_boilerplate_heavy_html(self) -> None: + navigation = " ".join(f"navigation{index}" for index in range(180)) + html = f"
Small useful article.
" + + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", html) + ) + + self.assertGreater(result.boilerplate_ratio, 0.65) + self.assertGreater(result.navigation_ratio, 0.45) + self.assertTrue(any("boilerplate" in issue for issue in result.issues)) + self.assertTrue(any("navigation-heavy" in issue for issue in result.issues)) + + def test_detects_probable_app_shell(self) -> None: + html = "
Loading
" + + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", html) + ) + + self.assertEqual(result.rendering_state, "probable_js_shell") + self.assertTrue(result.app_shell_signals_present) + self.assertTrue(result.app_shell_risk) + self.assertTrue(any("app-shell risk" in issue for issue in result.issues)) + + def test_excludes_conservatively_hidden_main_content_from_metrics(self) -> None: + hidden_words = " ".join(f"hiddenword{index}" for index in range(120)) + html = f"
{hidden_words}

Loading

" + + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", html) + ) + + self.assertEqual(result.hidden_node_count, 1) + self.assertNotEqual(result.rendering_state, "readable") + self.assertLess(result.cleaned_text_words, 5) + self.assertTrue(any("External CSS" in caveat for caveat in result.caveats)) + + def test_accepts_and_rejects_already_fetched_markdown(self) -> None: + usable = "# Guide\n\n" + "Useful Markdown content with enough words for extraction. " * 12 + html_response = _response( + "Not Markdown", + content_type="text/html", + ) + + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _good_html(), + markdown_responses=(_response(usable), html_response), + ) + ) + + self.assertEqual(result.markdown_alternates_supplied, 2) + self.assertEqual(result.markdown_alternates_checked, 2) + self.assertEqual(result.markdown_usable_count, 1) + self.assertGreater(result.best_markdown_bytes, 0) + self.assertGreater(result.best_markdown_words, 0) + self.assertNotEqual(result.best_markdown_word_delta, 0) + self.assertGreater(result.best_markdown_to_raw_byte_ratio, 0) + self.assertGreater(result.best_markdown_to_main_word_ratio, 0) + + def test_caps_best_markdown_comparison_before_counting(self) -> None: + oversized_markdown = "# Guide\n\n" + ("boundedword " * 120_000) + + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _good_html(), + markdown_responses=(_response(oversized_markdown),), + ) + ) + + self.assertEqual(result.markdown_usable_count, 1) + self.assertLessEqual(result.best_markdown_bytes, 1024 * 1024) + self.assertGreater(result.best_markdown_token_coverage_ratio, 0) + self.assertTrue(any("Markdown alternate 1 exceeded 1 MiB" in item for item in result.caveats)) + + def test_equal_length_unrelated_markdown_is_not_praised_as_coverage(self) -> None: + unrelated = "# Astronomy\n\n" + ( + "galaxy telescope nebula observatory planet starlight comet orbit " * 50 + ) + + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _good_html(), + markdown_responses=(_response(unrelated),), + ) + ) + + self.assertLess(result.best_markdown_token_coverage_ratio, 0.5) + self.assertFalse(any("overlaps at least 80%" in item for item in result.positives)) + self.assertTrue(any("overlaps less than half" in item for item in result.issues)) + + def test_shorter_relevant_markdown_beats_longer_unrelated_alternate(self) -> None: + unrelated = "# Astronomy\n\n" + ( + "galaxy telescope nebula observatory planet starlight comet orbit " * 80 + ) + relevant = ( + "# Extraction guide\n\nUseful extraction word " + + " ".join(str(index) for index in range(90)) + ) + + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _good_html(), + markdown_responses=(_response(unrelated), _response(relevant)), + ) + ) + + self.assertEqual(result.markdown_usable_count, 2) + self.assertLess(result.best_markdown_words, len(unrelated.split())) + self.assertGreaterEqual(result.best_markdown_token_coverage_ratio, 0.8) + self.assertEqual(result.best_markdown_bytes, len(relevant.encode("utf-8"))) + self.assertFalse(any("overlaps less than half" in item for item in result.issues)) + + def test_distinguishes_llms_missing_empty_invalid_and_valid(self) -> None: + cases = ( + (None, False, False, False), + ("", True, False, False), + ("not a valid llms file because it has no title or link", True, True, False), + ("# Example\n\n[Guide](https://example.com/guide)", True, True, True), + ) + for content, supplied, present, valid in cases: + with self.subTest(content=content): + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(), llms_txt=content) + ) + self.assertEqual(result.llms_txt_supplied, supplied) + self.assertEqual(result.llms_txt_present, present) + self.assertEqual(result.llms_txt_valid, valid) + + def test_distinguishes_sitemap_shapes_missing_empty_and_malformed(self) -> None: + cases = ( + (None, False, False, False, 0, False, False), + ("", True, False, False, 0, False, False), + ("", True, True, False, 0, False, False), + ( + "https://example.com/2026-07-01", + True, + True, + True, + 1, + True, + False, + ), + ( + "https://example.com/products.xml", + True, + True, + True, + 1, + False, + True, + ), + ) + for content, supplied, present, valid, count, lastmod, is_index in cases: + with self.subTest(content=content): + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", _good_html(), sitemap_xml=content + ) + ) + self.assertEqual(result.sitemap_xml_supplied, supplied) + self.assertEqual(result.sitemap_xml_present, present) + self.assertEqual(result.sitemap_valid, valid) + self.assertEqual(result.sitemap_url_count, count) + self.assertEqual(result.sitemap_has_lastmod, lastmod) + self.assertEqual(result.sitemap_is_index, is_index) + + def test_collects_graph_nested_and_multiple_schema_types(self) -> None: + schema = """ + + + + """ + + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(schema)) + ) + + self.assertEqual( + result.schema_types, + ("Organization", "Thing", "Product", "Offer", "WebSite"), + ) + self.assertEqual(result.invalid_schema_count, 1) + self.assertTrue(result.product_schema_present) + self.assertTrue(result.offer_schema_present) + + def test_deep_and_malformed_json_ld_are_bounded_without_crashing(self) -> None: + # Malformed input: object-open followed by array-close with no + # matching object-close. Deep-but-valid JSON is exercised by the + # nested case below via the schema-traversal depth cap. + malformed_json = "{" + "]" * 50 + malformed = f'' + malformed_result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(malformed)) + ) + self.assertGreaterEqual(malformed_result.invalid_schema_count, 1) + + nested = '{"@type":"Product"}' + for _ in range(40): + nested = '{"child":' + nested + "}" + nested_html = f'' + nested_result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(nested_html)) + ) + self.assertTrue(nested_result.schema_traversal_truncated) + self.assertTrue(any("safety cap" in item for item in nested_result.caveats)) + + def test_json_ld_value_error_is_counted_as_invalid(self) -> None: + oversized_integer = "9" * 5000 + schema = ( + '" + ) + + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(schema)) + ) + + self.assertEqual(result.invalid_schema_count, 1) + self.assertTrue(any("JSON-LD script block" in item for item in result.issues)) + + def test_schema_types_are_sanitised_and_count_capped(self) -> None: + sentinel = "PRIVATE-SOURCE-CONTENT-SENTINEL" + nodes = [{"@type": sentinel}] + [{"@type": f"Type{index}"} for index in range(40)] + schema = '" + + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(schema)) + ) + + self.assertLessEqual(len(result.schema_types), 32) + self.assertNotIn(sentinel, result.schema_types) + self.assertNotIn(sentinel, repr(result)) + self.assertGreater(result.schema_types_ignored, 0) + self.assertTrue(result.schema_traversal_truncated) + + def test_commerce_fields_are_complete_incomplete_or_out_of_scope(self) -> None: + complete = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _complete_visible_product_html(_complete_product_schema()), + include_ecommerce=True, + ) + ) + incomplete_schema = """ + + """ + incomplete = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _good_html(incomplete_schema), + include_ecommerce=True, + ) + ) + off = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", _good_html(incomplete_schema)) + ) + + self.assertEqual(complete.commerce_missing_fields, ()) + self.assertEqual(complete.commerce_visible_missing_fields, ()) + self.assertEqual(complete.commerce_schema_visible_mismatches, ()) + self.assertIn("variants", complete.commerce_visible_fields) + self.assertTrue(complete.product_schema_present) + self.assertTrue(complete.offer_schema_present) + self.assertIn("description", incomplete.commerce_missing_fields) + self.assertIn("offers.priceCurrency", incomplete.commerce_missing_fields) + self.assertNotIn("variants", incomplete.commerce_visible_missing_fields) + self.assertEqual(off.commerce_missing_fields, ()) + self.assertEqual(off.commerce_visible_missing_fields, ()) + self.assertFalse(any("Commerce schema" in issue for issue in off.issues)) + + def test_reports_visible_schema_conflicts_without_retaining_values(self) -> None: + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _complete_visible_product_html(_complete_product_schema(), price="129.00"), + include_ecommerce=True, + ) + ) + + self.assertIn("price", result.commerce_schema_visible_mismatches) + self.assertNotIn("129.00", repr(result)) + self.assertNotIn("99.00", repr(result)) + + def test_variants_are_optional_but_asymmetric_cues_are_reported(self) -> None: + neither = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _complete_visible_product_html( + _complete_product_schema(include_variant=False), + include_variant=False, + ), + include_ecommerce=True, + ) + ) + visible_only = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _complete_visible_product_html( + _complete_product_schema(include_variant=False), + include_variant=True, + ), + include_ecommerce=True, + ) + ) + schema_only = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _complete_visible_product_html( + _complete_product_schema(include_variant=True), + include_variant=False, + ), + include_ecommerce=True, + ) + ) + + self.assertNotIn("variants", neither.commerce_missing_fields) + self.assertNotIn("variants", neither.commerce_visible_missing_fields) + self.assertNotIn("variants", neither.commerce_schema_visible_mismatches) + self.assertIn("variants", visible_only.commerce_schema_visible_mismatches) + self.assertIn("variants", schema_only.commerce_schema_visible_mismatches) + + def test_grouped_price_formats_match_equivalent_schema_price(self) -> None: + for visible_price in ("1,299.00", "1299.00", "1.299,00"): + schema = _complete_product_schema().replace('"price": "99.00"', '"price": "1299.00"') + with self.subTest(visible_price=visible_price): + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + _complete_visible_product_html(schema, price=visible_price), + include_ecommerce=True, + ) + ) + self.assertNotIn("price", result.commerce_schema_visible_mismatches) + + def test_handles_empty_and_malformed_html_without_raising(self) -> None: + for html in ("", "
"): + with self.subTest(html=html): + result = analyse_extraction_readiness( + ExtractionReadinessInput("https://example.com", html) + ) + self.assertIsInstance(result, ExtractionReadinessAnalysis) + self.assertTrue(result.issues) + + def test_caps_sources_and_ignores_excess_markdown_alternates(self) -> None: + oversized_html = "x" * ((15 * 1024 * 1024) + 1) + oversized_llms = "# Example\nhttps://example.com\n" + ("x" * (512 * 1024)) + oversized_sitemap = "" + (" " * (1024 * 1024)) + responses = [_response("# Guide\n\n" + "useful words " * 40) for _ in range(6)] + + result = analyse_extraction_readiness( + ExtractionReadinessInput( + "https://example.com", + oversized_html, + markdown_responses=responses, + llms_txt=oversized_llms, + sitemap_xml=oversized_sitemap, + ) + ) + + self.assertTrue(result.raw_html_truncated) + self.assertEqual(result.markdown_alternates_supplied, 6) + self.assertEqual(result.markdown_alternates_checked, 5) + self.assertTrue(any("15 MiB" in caveat for caveat in result.caveats)) + self.assertTrue(any("512 KiB" in caveat for caveat in result.caveats)) + self.assertTrue(any("Sitemap XML exceeded 1 MiB" in caveat for caveat in result.caveats)) + self.assertTrue(any("1 were ignored" in caveat for caveat in result.caveats)) + + def test_is_pure_frozen_and_retains_no_source_content(self) -> None: + sentinel = "PRIVATE-SOURCE-CONTENT-SENTINEL" + profile_input = ExtractionReadinessInput( + "https://example.com", + f"
{sentinel}
", + ) + with patch("app.fetching.fetch_url") as fetch_url: + result = analyse_extraction_readiness(profile_input) + + fetch_url.assert_not_called() + with self.assertRaises(FrozenInstanceError): + result.cleaned_text_words = 2 # type: ignore[misc] + output_field_names = {field.name for field in fields(result)} + self.assertFalse({"url", "raw_html", "cleaned_text", "main_text"} & output_field_names) + self.assertNotIn(sentinel, repr(result)) + self.assertTrue(any("local source-response readiness" in item for item in result.caveats)) + self.assertTrue(any("no Firecrawl" in item for item in result.caveats)) + self.assertTrue(any("Browser-rendered output" in item for item in result.caveats)) + self.assertTrue(any("Actual product extraction" in item for item in result.caveats)) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_free_checks.py b/backend/tests/test_free_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..4e680bdca71c3fab01d0e7e534ec692be5a98b6a --- /dev/null +++ b/backend/tests/test_free_checks.py @@ -0,0 +1,2279 @@ +import asyncio +import sys +import tempfile +import unittest +from datetime import date, timedelta +from pathlib import Path +from unittest.mock import AsyncMock, patch + +from bs4 import BeautifulSoup + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.agent_readiness import build_agent_readiness_summary +from app.audit_context import AuditContext +from app.benchmarks import build_agent_benchmark_comparison, build_benchmark_comparison +from app.crawler_registry import ( + CRAWLERS, + bot_user_agents, + crawler_directive_sources, + crawler_groups, + crawler_registry_caveat, + fetch_probe_names, + robots_scoring_crawlers, +) +from app.checks.bot_access import check_bot_access +from app.checks.locked import locked_checks +from app.checks.html_structure import _analyse as analyse_html_structure, check_html_structure +from app.checks.indexing import _has_zero_snippet_limit, check_indexing +from app.checks.llms_txt import _analyse_sitemap, analyse_markdown_response, check_llms_txt +from app.checks.machine_surfaces import check_machine_surfaces +from app.checks.pagespeed import _mobile_viewport_signal +from app.checks.robots import ( + _classify_bot_access, + check_robots, + content_signal_tokens, + explicit_ai_bot_count, + response_content_signal_tokens, + robots_quality_signals, +) +from app.checks.search_discovery import ( + FeedFreshnessResult, + HreflangValidationResult, + SamplePageMetadataResult, + _freshness_surface, + _parse_feed_response, + _sample_pages_have_discovery_metadata, + _trust_surface_discovery, + _validate_hreflang, + check_search_discovery, +) +from app.checks.schema_ld import _extract_schemas, _score_schema, check_schema_ld +from app.checks.sitemap_analysis import SitemapEntry, SitemapSampleResult, parse_sitemap +from app.checks.social import check_social +from app.checks.ssr import _analyse_rendering, _extraction_efficiency, check_ssr +from app.entity_cache import get_cached_entity_lookup, set_cached_entity_lookup +from app.fetching import BROWSER_USER_AGENT, FetchResult +from app.models import AgentReadinessSummary, CheckResult +from app.rubric import ESSENTIALS_CHECKED_MAX, ESSENTIALS_CHECK_GROUP_COUNT, ESSENTIALS_CHECK_GROUPS +from app.scoring import build_result +from backend.tests.fixtures import ( + BASIC_SITEMAP, + EXAMPLE_URL, + ROBOTS_WITH_SITEMAP, + SHOP_URL, + make_audit_context, + make_fetch_result, +) + + +class SchemaLdTests(unittest.TestCase): + def _context(self, homepage_html: str) -> AuditContext: + return make_audit_context( + base_url=SHOP_URL, + homepage_html=homepage_html, + homepage_final_url=f"{SHOP_URL}/", + ) + + def test_extracts_schema_graph_and_scores_best_entity(self) -> None: + html = """ + + """ + schemas, invalid_count = _extract_schemas(BeautifulSoup(html, "lxml")) + scored = [_score_schema(schema, include_ecommerce=True) for schema in schemas] + + self.assertEqual(invalid_count, 0) + self.assertEqual(len(schemas), 2) + self.assertIn((5, "Product", []), scored) + + def test_ecommerce_product_reports_expanded_missing_fields(self) -> None: + score, schema_type, missing = _score_schema( + { + "@type": "Product", + "name": "Trail Mug", + "description": "Insulated mug", + "offers": { + "@type": "Offer", + "price": "24", + "priceCurrency": "USD", + "availability": "https://schema.org/InStock", + }, + }, + include_ecommerce=True, + ) + + self.assertEqual(score, 3) + self.assertEqual(schema_type, "Product") + self.assertEqual( + missing, + [ + "recommended image", + "recommended brand", + "recommended sku", + "recommended gtin", + "recommended aggregateRating or review", + "recommended offers.priceValidUntil", + "recommended offers.shippingDetails", + "recommended offers.hasMerchantReturnPolicy", + ], + ) + + def test_ecommerce_offer_reports_price_shipping_and_return_details(self) -> None: + score, schema_type, missing = _score_schema( + { + "@type": "Offer", + "price": "24", + "priceCurrency": "USD", + "availability": "https://schema.org/InStock", + }, + include_ecommerce=True, + ) + + self.assertEqual(score, 3) + self.assertEqual(schema_type, "Offer") + self.assertEqual( + missing, + [ + "recommended priceValidUntil", + "recommended shippingDetails", + "recommended hasMerchantReturnPolicy", + ], + ) + + def test_commerce_scope_surfaces_product_schema_over_complete_website(self) -> None: + html = """ + + + + """ + + result = asyncio.run(check_schema_ld(self._context(html), include_ecommerce=True)) + + self.assertEqual(result.state, "partial") + self.assertIn("Found Product JSON-LD schema", result.finding) + self.assertIn("recommended sku", result.finding) + + def test_non_commerce_scope_does_not_penalize_commerce_recommended_fields(self) -> None: + html = """ + + + + """ + + result = asyncio.run(check_schema_ld(self._context(html), include_ecommerce=False)) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 5) + self.assertNotIn("recommended sku", result.finding) + self.assertNotIn("shipping", result.fix.lower()) + + def test_speakable_detected_in_finding(self) -> None: + """QA4-04: Speakable markup is a tracked-only signal — finding annotates it but score is unchanged. + + The same Product JSON-LD is run twice: once without speakable (baseline) + and once with a SpeakableSpecification @type. The score, state, fix, and + effort must be identical; only the finding text gains the + ``Speakable markup detected`` note. + """ + baseline_html = """ + + + + """ + speakable_html = """ + + + + """ + + baseline = asyncio.run( + check_schema_ld(self._context(baseline_html), include_ecommerce=False) + ) + annotated = asyncio.run( + check_schema_ld(self._context(speakable_html), include_ecommerce=False) + ) + + # Finding carries the tracked-only speakable note. + self.assertIn("Speakable markup detected", annotated.finding) + self.assertNotIn("Speakable markup detected", baseline.finding) + # Score / state / fix / effort are all unchanged — speakable is read-only. + self.assertEqual(annotated.score, baseline.score) + self.assertEqual(annotated.state, baseline.state) + self.assertEqual(annotated.fix, baseline.fix) + self.assertEqual(annotated.effort, baseline.effort) + + +class SocialMetadataTests(unittest.IsolatedAsyncioTestCase): + def _context(self, homepage_html: str) -> AuditContext: + return make_audit_context( + homepage_html=homepage_html, + homepage_final_url=f"{EXAMPLE_URL}/", + ) + + async def test_passes_when_social_cards_and_schema_entity_align(self) -> None: + html = """ + + + Acme AI - Agent-ready audits + + + + + + + + + + + + + + + LinkedIn + X + YouTube + + + """ + + result = await check_social(self._context(html)) + + self.assertEqual(result.label, "Social & Entity Metadata") + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 2) + self.assertIn("Open Graph, Twitter card, canonical", result.finding) + + async def test_reports_open_graph_schema_and_same_as_mismatches(self) -> None: + html = """ + + + Acme AI + + + + + + + + + X + + """ + + result = await check_social(self._context(html)) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 1) + self.assertIn("og:title does not align with page title", result.finding) + self.assertIn("og:url does not match canonical URL", result.finding) + self.assertIn("Detected tracked profile signal(s): X/Twitter, LinkedIn", result.finding) + + +class HtmlStructureTests(unittest.TestCase): + def _context(self, homepage_html: str) -> AuditContext: + return make_audit_context(homepage_html=homepage_html) + + def test_accepts_clear_static_form_affordances(self) -> None: + soup = BeautifulSoup( + """ + + + Contact Acme AI + + + +
+
+
+

Contact Acme AI

+

Tell us about your site

+
+ + + + + + + +
+
+
+
Acme AI
+ + + """, + "lxml", + ) + + score, issues = analyse_html_structure(soup) + + self.assertEqual(score, 4) + self.assertEqual(issues, []) + + def test_reports_javascript_only_forms_and_weak_field_affordances(self) -> None: + soup = BeautifulSoup( + """ + + + Contact Acme AI + + + +
+
+
+

Contact Acme AI

+

Tell us about your site

+
+ + + + + +
+
+
+
Acme AI
+ + + """, + "lxml", + ) + + score, issues = analyse_html_structure(soup) + + self.assertEqual(score, 1) + self.assertIn("1 form(s) use JavaScript-only actions", issues) + self.assertIn("1 form(s) lack explicit methods", issues) + self.assertIn("2 form field(s) lack useful name attributes", issues) + self.assertIn("2 form field(s) lack autocomplete hints", issues) + self.assertIn("1 form(s) lack named submit controls", issues) + self.assertIn("no form exposes an explicit non-JS action/method fallback", issues) + + def test_report_surfaces_form_affordance_issues(self) -> None: + html = """ + + + Contact Acme AI + + + +
+
+
+

Contact Acme AI

+

Tell us about your site

+
+ + + +
+
+
+
Acme AI
+ + + """ + + result = asyncio.run(check_html_structure(self._context(html))) + + self.assertEqual(result.state, "fail") + self.assertIn("form(s) use JavaScript-only actions", result.finding) + self.assertIn("form field(s) lack autocomplete hints", result.finding) + + +class RenderingTests(unittest.TestCase): + def _context(self, homepage_html: str) -> AuditContext: + return make_audit_context(homepage_html=homepage_html) + + def test_thin_static_page_is_not_js_shell(self) -> None: + result, words = _analyse_rendering("

Example Domain

Short text.

") + + self.assertEqual(result, "thin") + self.assertGreater(words, 0) + + def test_app_shell_is_detected_when_html_is_thin(self) -> None: + html = """ +
+ + + + """ + + result, _ = _analyse_rendering(html) + + self.assertEqual(result, "probable_js_shell") + + def test_extraction_efficiency_accepts_clear_main_content(self) -> None: + main_copy = " ".join(["Useful product and company detail"] * 35) + nav_copy = "Home Products About Contact" + html = f""" + + +
+

Trail Mug

{main_copy}

+ + + """ + + signal = _extraction_efficiency(html) + + self.assertEqual(signal.issues, []) + self.assertGreaterEqual(signal.main_content_words, 120) + self.assertLess(signal.navigation_ratio, 0.1) + + def test_extraction_efficiency_flags_navigation_heavy_payloads(self) -> None: + nav_copy = " ".join(["Menu link"] * 80) + html = f""" + + +
+

Short page copy.

+ + + + """ + + signal = _extraction_efficiency(html) + + self.assertIn("main-content area has only 3 words", signal.issues) + self.assertTrue(any(issue.startswith("navigation-heavy page") for issue in signal.issues)) + self.assertTrue(any(issue.startswith("script/style markup is heavy") for issue in signal.issues)) + self.assertTrue(any(issue.startswith("high HTML-to-text ratio") for issue in signal.issues)) + + def test_readable_page_with_extraction_issues_is_partial(self) -> None: + nav_copy = " ".join(["Menu link"] * 80) + html = f""" + + +
+

Short page copy.

+ + + + """ + + result = asyncio.run(check_ssr(self._context(html))) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 2) + self.assertIn("Extraction proxy flags", result.finding) + self.assertIn("main-content words", result.finding) + + +class SitemapTests(unittest.TestCase): + def test_parses_namespaced_urlset(self) -> None: + sitemap = """ + + https://example.com/2026-06-01 + + """ + + self.assertEqual(_analyse_sitemap(sitemap), (True, 1, True, False)) + + def test_parses_sitemap_index(self) -> None: + sitemap = """ + + https://example.com/posts.xml + + """ + + self.assertEqual(_analyse_sitemap(sitemap), (True, 1, False, True)) + + def test_tracks_invalid_and_future_lastmod_values(self) -> None: + sitemap = """ + + https://example.com/anot-a-date + https://example.com/b2999-01-01 + https://example.com/c + + """ + + parsed = parse_sitemap(sitemap) + + self.assertTrue(parsed.is_valid) + self.assertEqual(parsed.loc_count, 3) + self.assertEqual(parsed.invalid_lastmod_count, 1) + self.assertEqual(parsed.future_lastmod_count, 1) + self.assertEqual(parsed.missing_lastmod_count, 1) + + +class FeedFreshnessTests(unittest.IsolatedAsyncioTestCase): + def _context(self, homepage_html: str) -> AuditContext: + return make_audit_context( + homepage_html=homepage_html, + homepage_final_url=f"{EXAMPLE_URL}/", + ) + + def test_parses_rss_and_atom_feed_dates(self) -> None: + today = date.today() + latest = today - timedelta(days=5) + older = today - timedelta(days=30) + rss = f""" + + Latest{latest.strftime('%a, %d %b %Y 12:00:00 GMT')} + Older{older.isoformat()} + + """ + atom = f""" + + Latest{latest.isoformat()}T08:00:00Z + + """ + + rss_result = _parse_feed_response( + FetchResult( + "https://example.com/feed.xml", + "https://example.com/feed.xml", + 200, + {"content-type": "application/rss+xml"}, + rss, + 1, + [], + ), + today=today, + ) + atom_result = _parse_feed_response( + FetchResult( + "https://example.com/atom.xml", + "https://example.com/atom.xml", + 200, + {"content-type": "application/atom+xml"}, + atom, + 1, + [], + ), + today=today, + ) + + self.assertEqual(rss_result.feed_type, "RSS") + self.assertEqual(rss_result.item_count, 2) + self.assertEqual(rss_result.latest_date, latest) + self.assertEqual(rss_result.invalid_date_count, 0) + self.assertEqual(atom_result.feed_type, "Atom") + self.assertEqual(atom_result.item_count, 1) + self.assertEqual(atom_result.latest_date, latest) + + async def test_freshness_surface_reports_linked_feed_details(self) -> None: + today = date.today() + latest = today - timedelta(days=3) + feed = f""" + + Latest{latest.isoformat()} + Older{(today - timedelta(days=15)).isoformat()} + + """ + homepage = '' + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url == "https://example.com/feed.xml": + return FetchResult(url, url, 200, {"content-type": "application/rss+xml"}, feed, 1, []) + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + with patch("app.checks.search_discovery.fetch_url", new=fake_fetch): + result = await _freshness_surface(self._context(homepage)) + + self.assertTrue(result.available) + self.assertIn(f"linked RSS feed has 2 item(s); latest item dated {latest.isoformat()}", result.positives) + self.assertEqual(result.issues, []) + self.assertEqual(result.caveats, []) + + async def test_freshness_surface_reports_json_feed_stale_and_invalid_dates(self) -> None: + today = date.today() + stale = today - timedelta(days=365) + feed = ( + '{"version":"https://jsonfeed.org/version/1.1",' + '"items":[' + f'{{"title":"Old","date_published":"{stale.isoformat()}T08:00:00Z"}},' + '{"title":"Broken","date_published":"not-a-date"}' + "]}" + ) + homepage = '' + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url == "https://example.com/feed.json": + return FetchResult(url, url, 200, {"content-type": "application/feed+json"}, feed, 1, []) + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + with patch("app.checks.search_discovery.fetch_url", new=fake_fetch): + result = await _freshness_surface(self._context(homepage)) + + self.assertTrue(result.available) + self.assertIn(f"linked JSON Feed has 2 item(s); latest item dated {stale.isoformat()}", result.positives) + self.assertIn("1 feed item date(s) were invalid", result.caveats) + self.assertIn(f"latest feed item is older than 180 days ({stale.isoformat()})", result.caveats) + + +class TrustSurfaceTests(unittest.IsolatedAsyncioTestCase): + def _context(self, homepage_html: str) -> AuditContext: + return make_audit_context( + homepage_html=homepage_html, + homepage_final_url=f"{EXAMPLE_URL}/", + robots_text=ROBOTS_WITH_SITEMAP, + ) + + def test_discovers_homepage_and_sitemap_trust_surfaces(self) -> None: + html = """ + + + + """ + + result = _trust_surface_discovery( + self._context(html), + [ + SitemapEntry(loc="https://example.com/return-policy", lastmod="2026-06-01"), + SitemapEntry(loc="https://example.com/shipping", lastmod="2026-06-01"), + ], + include_ecommerce=True, + ) + + self.assertEqual(result.issues, []) + self.assertEqual(result.caveats, []) + self.assertIn("about", result.found) + self.assertIn("returns", result.found) + self.assertIn("core About, Contact, and Privacy surfaces are discoverable", result.positives) + self.assertIn("commerce Returns and Shipping surfaces are discoverable", result.positives) + + def test_reports_missing_core_and_commerce_trust_surfaces(self) -> None: + result = _trust_surface_discovery( + self._context('About us'), + [], + include_ecommerce=True, + ) + + self.assertIn("missing core trust/entity pages: Contact, Privacy", result.issues) + self.assertIn("commerce scope missing policy pages: Returns, Shipping", result.issues) + self.assertIn("recommended trust/support pages were not discovered: Terms, Support", result.caveats) + + def test_non_commerce_scope_does_not_penalize_returns_or_shipping(self) -> None: + result = _trust_surface_discovery( + self._context('About us'), + [], + include_ecommerce=False, + ) + + self.assertIn("missing core trust/entity pages: Contact, Privacy", result.issues) + self.assertNotIn("commerce scope missing policy pages: Returns, Shipping", result.issues) + + async def test_search_discovery_caps_score_when_trust_surfaces_are_missing(self) -> None: + sample = SitemapSampleResult( + entries=[SitemapEntry(loc="https://example.com/", lastmod="2026-06-01")], + sitemap_count=1, + is_index=False, + has_robot_reference=True, + invalid_lastmod_count=0, + future_lastmod_count=0, + missing_lastmod_count=0, + same_host_count=1, + non_https_count=0, + duplicate_count=0, + issues=[], + ) + + with ( + patch("app.checks.search_discovery.collect_sitemap_sample", new=AsyncMock(return_value=sample)), + patch( + "app.checks.search_discovery._freshness_surface", + new=AsyncMock( + return_value=FeedFreshnessResult( + True, + ["dated content metadata on the homepage"], + [], + [], + ) + ), + ), + patch( + "app.checks.search_discovery._sample_pages_have_discovery_metadata", + new=AsyncMock( + return_value=SamplePageMetadataResult( + True, + ["sampled pages include titles"], + [], + [], + ) + ), + ), + patch( + "app.checks.search_discovery._validate_hreflang", + new=AsyncMock(return_value=HreflangValidationResult(False, [], [], [])), + ), + ): + result = await check_search_discovery( + self._context("
Example
"), + include_ecommerce=True, + ) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 3) + self.assertIn("missing core trust/entity pages: About, Contact, Privacy", result.finding) + self.assertIn("commerce scope missing policy pages: Returns, Shipping", result.finding) + + async def test_search_discovery_passes_when_included_free_signals_align(self) -> None: + sample = SitemapSampleResult( + entries=[SitemapEntry(loc="https://example.com/about", lastmod="2026-06-01")], + sitemap_count=1, + is_index=False, + has_robot_reference=True, + invalid_lastmod_count=0, + future_lastmod_count=0, + missing_lastmod_count=0, + same_host_count=1, + non_https_count=0, + duplicate_count=0, + issues=[], + ) + html = """ + + +
Example
+ + """ + + with ( + patch("app.checks.search_discovery.collect_sitemap_sample", new=AsyncMock(return_value=sample)), + patch( + "app.checks.search_discovery._freshness_surface", + new=AsyncMock( + return_value=FeedFreshnessResult( + True, + ["linked RSS feed has 3 item(s); latest item dated 2026-07-01"], + [], + [], + ) + ), + ), + patch( + "app.checks.search_discovery._sample_pages_have_discovery_metadata", + new=AsyncMock( + return_value=SamplePageMetadataResult( + True, + [ + "sampled pages include titles", + "sampled pages include same-site canonicals", + "sampled pages include parseable JSON-LD", + ], + [], + [], + ) + ), + ), + patch( + "app.checks.search_discovery._validate_hreflang", + new=AsyncMock(return_value=HreflangValidationResult(False, [], [], [])), + ), + ): + result = await check_search_discovery(self._context(html)) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 4) + self.assertIn("Included search discovery hints are strong", result.finding) + self.assertIn("sampled pages include titles", result.finding) + self.assertIn("core About, Contact, and Privacy surfaces are discoverable", result.finding) + + +class IndexingTests(unittest.IsolatedAsyncioTestCase): + def _context(self, homepage_html: str, headers: dict[str, str] | None = None) -> AuditContext: + return make_audit_context(homepage_html=homepage_html, homepage_headers=headers or None) + + def test_detects_zero_snippet_limits(self) -> None: + self.assertTrue(_has_zero_snippet_limit("index, max-snippet: 0")) + self.assertTrue(_has_zero_snippet_limit("max-image-preview:none")) + self.assertTrue(_has_zero_snippet_limit("bingbot: max-video-preview: 0")) + self.assertFalse(_has_zero_snippet_limit("max-snippet:-1, max-image-preview:large")) + + async def test_reports_data_nosnippet_as_snippet_restriction(self) -> None: + result = await check_indexing( + self._context("

Private snippet text

") + ) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 2) + self.assertIn("data-nosnippet", result.finding) + self.assertIn("data-nosnippet", result.fix) + + async def test_reads_per_bot_x_robots_directives(self) -> None: + result = await check_indexing( + self._context( + "Example", + {"content-type": "text/html", "x-robots-tag": "googlebot: noindex, bingbot: max-snippet: 0"}, + ) + ) + + self.assertEqual(result.state, "fail") + self.assertEqual(result.score, 0) + self.assertIn("X-Robots-Tag googlebot", result.finding) + + async def test_treats_standard_image_preview_as_limited(self) -> None: + result = await check_indexing( + self._context( + '' + ) + ) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 4) + self.assertIn("limits large image previews", result.finding) + + async def test_treats_large_image_preview_as_positive(self) -> None: + result = await check_indexing( + self._context( + '' + ) + ) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 5) + self.assertIn("Large image previews are allowed", result.finding) + + +class MobileViewportTests(unittest.TestCase): + def test_accepts_device_width_viewport_and_responsive_hints(self) -> None: + soup = BeautifulSoup( + """ + + + + + + + + """, + "lxml", + ) + + result = _mobile_viewport_signal(soup) + + self.assertEqual(result.score, 4) + self.assertEqual(result.issues, []) + self.assertIn("mobile viewport sets width=device-width without zoom restrictions", result.positives) + self.assertIn("sampled HTML exposes responsive layout or image hints", result.positives) + + def test_reports_missing_mobile_viewport(self) -> None: + soup = BeautifulSoup("ExampleExample", "lxml") + + result = _mobile_viewport_signal(soup) + + self.assertEqual(result.score, 0) + self.assertIn("missing mobile viewport meta tag", result.issues) + + def test_reports_zoom_restrictive_viewport(self) -> None: + soup = BeautifulSoup( + '', + "lxml", + ) + + result = _mobile_viewport_signal(soup) + + self.assertEqual(result.score, 2) + self.assertIn("mobile viewport restricts pinch zoom", result.issues) + + +class MarkdownAccessTests(unittest.IsolatedAsyncioTestCase): + def test_accepts_meaningful_negotiated_markdown(self) -> None: + body = "# Example\n\n" + "Useful Markdown content for agents. " * 20 + "\n[Home](https://example.com)" + response = FetchResult( + requested_url="https://example.com", + final_url="https://example.com", + status_code=200, + headers={ + "Content-Type": "text/markdown; charset=utf-8", + "Vary": "Accept, Accept-Encoding", + "Link": '; rel="alternate"; type="text/markdown"', + }, + text=body, + elapsed_ms=1, + redirect_chain=[], + ) + + result = analyse_markdown_response(response, "homepage Markdown negotiation", True) + + self.assertTrue(result.available) + self.assertEqual(result.issues, []) + self.assertIn("Vary: Accept present", result.detail or "") + self.assertIn("Link header advertises Markdown/text alternate", result.hints) + + def test_rejects_html_body_for_markdown_access(self) -> None: + response = FetchResult( + requested_url="https://example.com", + final_url="https://example.com", + status_code=200, + headers={"content-type": "text/html", "vary": "Accept"}, + text="

Example

This is a normal page.

", + elapsed_ms=1, + redirect_chain=[], + ) + + result = analyse_markdown_response(response, "homepage Markdown negotiation", True) + + self.assertFalse(result.available) + self.assertIn("body is HTML, not Markdown/text", result.issues) + self.assertIn("Content-Type is not text/markdown or text/plain", result.issues) + + async def test_report_includes_markdown_negotiation_caveat(self) -> None: + context = make_audit_context( + homepage_headers={}, + sitemap_text=( + "https://example.com" + "2026-06-01" + ), + ) + markdown_body = "# Example\n\n" + "Useful Markdown body for agents. " * 20 + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url == "https://example.com": + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/markdown"}, + text=markdown_body, + elapsed_ms=1, + redirect_chain=[], + ) + return FetchResult( + requested_url=url, + final_url=url, + status_code=404, + headers={"content-type": "text/plain"}, + text="not found", + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.llms_txt.fetch_url", new=fake_fetch): + result = await check_llms_txt(context) + + self.assertEqual(result.state, "partial") + self.assertIn("Vary: Accept is missing", result.finding) + self.assertIn("Serve substantial Markdown", result.fix) + + +class SearchDiscoverySampleTests(unittest.IsolatedAsyncioTestCase): + def _context(self) -> AuditContext: + return make_audit_context() + + async def test_sampled_page_metadata_accepts_markdown_alternate(self) -> None: + page_url = "https://example.com/products/widget" + page_html = """ + + + Widget + + + + + +
{body}
+ + """.format(body="Helpful product details for agents. " * 50) + markdown = "# Widget\n\n" + "Helpful Markdown export with schema.org JSON-LD @type hints. " * 20 + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url == page_url: + return FetchResult(url, url, 200, {"content-type": "text/html"}, page_html, 1, []) + if url == "https://example.com/products/widget.md": + return FetchResult(url, url, 200, {"content-type": "text/markdown"}, markdown, 1, []) + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + with patch("app.checks.search_discovery.fetch_url", new=fake_fetch): + result = await _sample_pages_have_discovery_metadata( + self._context(), + [SitemapEntry(loc=page_url, lastmod="2026-06-01")], + ) + + self.assertTrue(result.ok) + self.assertIn("sampled pages include titles", result.positives) + self.assertIn("sampled pages include parseable JSON-LD", result.positives) + self.assertIn("1 sampled page Markdown alternate or index.md export(s) are usable", result.positives) + self.assertEqual(result.caveats, []) + + async def test_sampled_page_metadata_reports_missing_metadata(self) -> None: + page_url = "https://example.com/thin" + page_html = """ + + +
Thin page.
+ + """ + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + return FetchResult(url, url, 200, {"content-type": "text/html"}, page_html, 1, []) + + with patch("app.checks.search_discovery.fetch_url", new=fake_fetch): + result = await _sample_pages_have_discovery_metadata( + self._context(), + [SitemapEntry(loc=page_url, lastmod=None)], + ) + + self.assertFalse(result.ok) + self.assertIn("1 sampled sitemap URL(s) are noindex/none", result.issues) + self.assertIn("1 sampled page(s) are missing a title", result.issues) + self.assertIn("1 sampled page(s) are missing a canonical link", result.issues) + self.assertIn("no sampled pages expose parseable JSON-LD", result.issues) + self.assertIn("1 sampled page(s) have very little extractable text", result.issues) + + +class HreflangValidationTests(unittest.IsolatedAsyncioTestCase): + def _context(self, homepage_html: str, final_url: str = "https://example.com/en/") -> AuditContext: + return make_audit_context( + homepage_html=homepage_html, + homepage_requested_url=final_url, + homepage_final_url=final_url, + ) + + async def test_absent_hreflang_is_neutral(self) -> None: + result = await _validate_hreflang( + self._context("ExampleExample"), + [], + ) + + self.assertFalse(result.present) + self.assertEqual(result.issues, []) + self.assertEqual(result.caveats, []) + + async def test_accepts_valid_reciprocal_hreflang(self) -> None: + english_html = """ + + + + + English page + """ + french_html = """ + + + + + French page + """ + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url == "https://example.com/fr/": + return make_fetch_result(url, french_html, headers={"content-type": "text/html"}) + return make_fetch_result(url, "not found", status_code=404, headers={"content-type": "text/plain"}) + + with patch("app.checks.search_discovery.fetch_url", new=fake_fetch): + result = await _validate_hreflang(self._context(english_html), []) + + self.assertTrue(result.present) + self.assertEqual(result.issues, []) + self.assertIn("sampled hreflang uses valid language tags, self-references, and absolute URLs", result.positives) + self.assertIn("sampled same-site hreflang alternates are reciprocal where checked", result.positives) + + async def test_reports_invalid_hreflang_values_and_relative_urls(self) -> None: + html = """ + + + English page + """ + + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + return make_fetch_result(url, "not found", status_code=404, headers={"content-type": "text/plain"}) + + with patch("app.checks.search_discovery.fetch_url", new=fake_fetch): + result = await _validate_hreflang(self._context(html), []) + + self.assertTrue(result.present) + self.assertIn("1 hreflang value(s) are not valid language-region tags or x-default", result.issues) + self.assertIn("1 hreflang URL(s) are not absolute HTTP(S) URLs", result.issues) + self.assertIn("1 sampled page(s) publish hreflang without a self-reference", result.issues) + + +class CrawlerRegistryTests(unittest.TestCase): + def test_duckduckgo_crawlers_are_staged_with_official_source_metadata(self) -> None: + crawlers = {crawler.name: crawler for crawler in CRAWLERS} + user_agents = bot_user_agents() + + duckduckbot = crawlers["DuckDuckBot"] + self.assertEqual(duckduckbot.provider, "DuckDuckGo") + self.assertEqual(duckduckbot.purpose, "search and retrieval") + self.assertEqual( + duckduckbot.fetch_user_agent, + "DuckDuckBot/1.1; (+http://duckduckgo.com/duckduckbot.html)", + ) + self.assertEqual( + duckduckbot.official_documentation_url, + "https://duckduckgo.com/duckduckgo-help-pages/results/duckduckbot", + ) + self.assertEqual( + duckduckbot.official_ip_list_url, + "https://duckduckgo.com/duckduckbot.json", + ) + self.assertIn("cannot authenticate official DuckDuckGo traffic", duckduckbot.caveat) + self.assertIn("IP verification", duckduckbot.caveat) + + duckassist = crawlers["DuckAssistBot"] + self.assertEqual(duckassist.provider, "DuckDuckGo") + self.assertEqual(duckassist.purpose, "search and retrieval") + self.assertEqual( + duckassist.fetch_user_agent, + "DuckAssistBot/1.2; (+http://duckduckgo.com/duckassistbot.html)", + ) + self.assertEqual( + duckassist.official_documentation_url, + "https://duckduckgo.com/duckduckgo-help-pages/results/duckassistbot", + ) + self.assertEqual( + duckassist.official_ip_list_url, + "https://duckduckgo.com/duckassistbot.json", + ) + self.assertIn("cannot authenticate official DuckDuckGo traffic", duckassist.caveat) + self.assertIn("real-time retrieval for AI-assisted answers", duckassist.caveat) + self.assertIn("not model training", duckassist.caveat) + self.assertIn( + "does not affect organic search ranking or result inclusion", + duckassist.caveat, + ) + self.assertIn("up to 72 hours", duckassist.caveat) + + self.assertEqual(user_agents["DuckDuckBot"], duckduckbot.fetch_user_agent) + self.assertEqual(user_agents["DuckAssistBot"], duckassist.fetch_user_agent) + + def test_active_duckduckgo_crawlers_change_consumer_membership(self) -> None: + duckduckgo_names = {"DuckDuckBot", "DuckAssistBot"} + scored_names = tuple(crawler.name for crawler in robots_scoring_crawlers()) + groups = crawler_groups() + + self.assertEqual( + scored_names, + ( + "Googlebot", + "Bingbot", + "DuckDuckBot", + "DuckAssistBot", + "OAI-SearchBot", + "Claude-SearchBot", + "PerplexityBot", + "GPTBot", + "ClaudeBot", + "CCBot", + "Google-Extended", + "ChatGPT-User", + "Claude-User", + "Perplexity-User", + "Googlebot-Image", + ), + ) + self.assertEqual(len(scored_names), 15) + self.assertTrue(duckduckgo_names.issubset(scored_names)) + grouped_names = {name for names in groups.values() for name in names} + self.assertTrue(duckduckgo_names.issubset(grouped_names)) + self.assertEqual(sum(len(names) for names in groups.values()), 15) + + self.assertEqual( + fetch_probe_names(), + ( + "Googlebot", + "Bingbot", + "DuckDuckBot", + "DuckAssistBot", + "OAI-SearchBot", + "PerplexityBot", + "GPTBot", + "ClaudeBot", + "CCBot", + ), + ) + self.assertTrue(duckduckgo_names.issubset(fetch_probe_names())) + + directive_sources = crawler_directive_sources() + self.assertEqual(len(directive_sources), 17) + self.assertTrue( + {name.lower() for name in duckduckgo_names}.issubset(directive_sources) + ) + + def test_registry_groups_current_ai_crawlers_without_scoring_brave(self) -> None: + scored_tokens = {crawler.token for crawler in robots_scoring_crawlers()} + groups = crawler_groups() + + self.assertIn("OAI-SearchBot", groups["search and retrieval"]) + self.assertIn("Claude-SearchBot", groups["search and retrieval"]) + self.assertIn("PerplexityBot", groups["search and retrieval"]) + self.assertIn("GPTBot", groups["training and corpus"]) + self.assertIn("ClaudeBot", groups["training and corpus"]) + self.assertIn("CCBot", groups["training and corpus"]) + self.assertIn("ChatGPT-User", groups["user-triggered agents"]) + self.assertIn("Claude-User", groups["user-triggered agents"]) + self.assertIn("Perplexity-User", groups["user-triggered agents"]) + self.assertIn("Googlebot-Image", groups["media search"]) + self.assertNotIn("BraveBot", scored_tokens) + self.assertIn("Brave Search", crawler_registry_caveat()) + + def test_fetch_probe_matrix_excludes_control_only_and_unverified_tokens(self) -> None: + probe_names = set(fetch_probe_names()) + user_agents = bot_user_agents() + + self.assertIn("OAI-SearchBot", probe_names) + self.assertIn("PerplexityBot", probe_names) + self.assertNotIn("Google-Extended", probe_names) + self.assertNotIn("Claude-SearchBot", probe_names) + self.assertNotIn("BraveBot", probe_names) + self.assertNotIn("BraveBot", user_agents) + self.assertIn("OAI-SearchBot", user_agents["OAI-SearchBot"]) + + def test_indexing_directive_sources_come_from_registry(self) -> None: + directive_sources = crawler_directive_sources() + + self.assertIn("claude-searchbot", directive_sources) + self.assertIn("googlebot-news", directive_sources) + self.assertIn("perplexity-user", directive_sources) + self.assertNotIn("bravebot", directive_sources) + + +class RobotsTests(unittest.TestCase): + def test_distinguishes_explicit_block_from_wildcard_allow(self) -> None: + robots = """ + User-agent: GPTBot + Disallow: / + + User-agent: * + Allow: / + """ + access = _classify_bot_access(robots, "https://example.com/") + + self.assertEqual(access["GPTBot"], "explicit_blocked") + self.assertEqual(access["ClaudeBot"], "wildcard_allowed") + self.assertEqual(access["Claude-SearchBot"], "wildcard_allowed") + self.assertNotIn("BraveBot", access) + + def test_reads_agent_policy_signals(self) -> None: + robots = """ + User-agent: GPTBot + Allow: / + Content-Signal: search=yes, ai-input=no, ai-train=no + """ + + self.assertEqual(explicit_ai_bot_count(robots), 1) + self.assertEqual(content_signal_tokens(robots), ["ai-input", "ai-train", "search"]) + + def test_counts_current_anthropic_tokens_but_not_unverified_brave(self) -> None: + robots = """ + User-agent: Claude-SearchBot + Allow: / + + User-agent: Claude-User + Allow: / + + User-agent: BraveBot + Allow: / + """ + + self.assertEqual(explicit_ai_bot_count(robots), 2) + + def test_reads_response_content_signal_headers(self) -> None: + headers = {"Content-Signal": "search=yes, tdm-reservation=1"} + + self.assertEqual(response_content_signal_tokens(headers), ["search", "tdm-reservation"]) + + def test_reports_robots_quality_signals(self) -> None: + robots = """ + User-agent: GPTBot + Sitemap: /sitemap.xml + Crawl-delay: nope + Broken directive + """ + + signals = robots_quality_signals(robots) + + self.assertEqual(signals.empty_group_count, 1) + self.assertEqual(signals.invalid_sitemap_count, 1) + self.assertEqual(signals.crawl_delay_count, 1) + self.assertEqual(signals.invalid_crawl_delay_count, 1) + self.assertEqual(signals.malformed_line_count, 1) + + def test_flags_oversized_robots_file(self) -> None: + robots = "User-agent: *\nAllow: /\n" + ("#" * (501 * 1024)) + + self.assertTrue(robots_quality_signals(robots).oversized) + + +class RobotsCheckTests(unittest.IsolatedAsyncioTestCase): + async def test_check_includes_quality_and_response_content_signal(self) -> None: + context = make_audit_context( + homepage_headers={"Content-Signal": "search=yes"}, + robots_text="User-agent: *\nAllow: /\nSitemap: /sitemap.xml", + robots_headers={}, + sitemap_text=BASIC_SITEMAP, + ) + + result = await check_robots(context) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 5) + self.assertIn("HTTP Content-Signal headers", result.finding) + self.assertIn("invalid Sitemap directive", result.finding) + self.assertIn("absolute HTTP(S) URLs", result.fix) + + +class BotAccessTests(unittest.IsolatedAsyncioTestCase): + async def test_bot_access_probe_matrix_uses_registry_caveats(self) -> None: + body = "
" + ("Accessible content for agents. " * 120) + "
" + context = make_audit_context(homepage_html=body) + requested_user_agents: list[str] = [] + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + requested_user_agents.append(user_agent) + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 6) + self.assertIn("Probe caveat", result.finding) + self.assertIn("No material browser-vs-bot routing differences", result.finding) + self.assertIn("Brave Search", result.finding) + self.assertFalse(any("Brave" in user_agent for user_agent in requested_user_agents)) + + async def test_bot_access_reports_routing_differences_without_penalty(self) -> None: + browser_body = ( + '' + "
" + + ("Browser-visible content for agents and search. " * 75) + + "
" + ) + bot_body = ( + '' + "
" + + ("Bot-routed content remains readable. " * 60) + + "
" + ) + context = make_audit_context( + homepage_html=browser_body, + homepage_final_url=f"{EXAMPLE_URL}/", + ) + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + if "OAI-SearchBot" in user_agent: + return FetchResult( + requested_url=url, + final_url="https://example.com/bot", + status_code=206, + headers={"content-type": "text/html"}, + text=bot_body, + elapsed_ms=1, + redirect_chain=[], + ) + return FetchResult( + requested_url=url, + final_url="https://example.com/", + status_code=200, + headers={"content-type": "text/html"}, + text=browser_body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 6) + self.assertIn("Inferred browser-vs-bot routing differences", result.finding) + self.assertIn("OAI-SearchBot", result.finding) + self.assertIn("status 206 vs browser 200", result.finding) + self.assertIn("final URL example.com/bot vs browser example.com", result.finding) + self.assertIn("canonical example.com/bot vs browser example.com", result.finding) + self.assertIn("visible words", result.finding) + + async def test_bot_access_ignores_recaptcha_script_tag_in_body(self) -> None: + """F4-06: A Google reCAPTCHA ``' + '
' + "" + ) + context = make_audit_context(homepage_html=body) + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 6) + self.assertNotIn("challenge page", result.finding) + + async def test_bot_access_ignores_captcha_substring_in_response_headers(self) -> None: + """F4-06: ``captcha`` must not be matched inside HTTP response headers. + + Content-Security-Policy and other response headers can legitimately + include ``captcha`` as a directive keyword (e.g. ``script-src …/recaptcha/``). + Scanning header values used to flag every bot probe as ``challenge page``. + The fix removes header scanning for the captcha path by routing + captcha detection through ``_has_captcha_title`` only. + """ + body = ( + "Acme Robotics — Home" + "
" + + ("Accessible content for agents and search engines. " * 80) + + "
" + ) + # CSP and content-security headers reference /recaptcha/ in script-src — + # a normal pattern for any site that uses Google reCAPTCHA. + headers_with_captcha = { + "content-type": "text/html", + "content-security-policy": ( + "default-src 'self'; script-src 'self' https://www.google.com/recaptcha/ " + "https://www.gstatic.com/recaptcha/ 'unsafe-inline'; " + "frame-src https://www.google.com/recaptcha/" + ), + "link": "; rel=preconnect", + } + context = make_audit_context( + homepage_html=body, + homepage_headers=headers_with_captcha, + ) + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers=dict(headers_with_captcha), + text=body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 6) + self.assertNotIn("challenge page", result.finding) + + async def test_bot_access_baseline_suppresses_site_wide_challenge(self) -> None: + """F4-06: If the browser baseline ALSO matches a challenge signature, + the finding is a site-wide pattern, not bot discrimination, and is + suppressed for every bot probe. + """ + challenge_body = ( + "Just a moment…" + "" + "

cf-chl cf-chl-bypass

" + "

cloudflare ray id: 8a1b2c3d4e5f — checking your browser

" + "" + ) + context = make_audit_context(homepage_html=challenge_body) + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + # Same body for browser and every bot — site-wide challenge page, + # not bot discrimination. + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=challenge_body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + # The browser got the same challenge page, so no bot-specific finding. + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 6) + self.assertNotIn("challenge page", result.finding) + + async def test_bot_access_still_flags_real_captcha_title_for_bots(self) -> None: + """Positive case: a real CAPTCHA challenge page (with ``captcha`` + in the title) MUST still be flagged — but only for bots that see it + when the browser probe did NOT see the same challenge. + + Mixes the matrix: 1 bot (Googlebot) sees the clean page and stays + accessible, the remaining bots see the challenge page. Result: state + is ``partial`` and the finding lists ``(challenge page)`` per bot. + """ + challenge_body = ( + "reCAPTCHA verification required" + "" + + ("Verify you are human. " * 40) + + "" + ) + clean_body = ( + "Acme Robotics — Home" + "
" + + ("Accessible content for agents and search engines. " * 80) + + "
" + ) + context = make_audit_context(homepage_html=clean_body) + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + # Bots get the challenge page; the browser probe gets the clean page. + # The browser user-agent is identified by exact-match so that the + # OAI-SearchBot / PerplexityBot / GPTBot / Bingbot tokens — many of + # which contain "Mozilla" or "Chrome" — fall through to the + # challenge branch. + if user_agent == BROWSER_USER_AGENT: + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=clean_body, + elapsed_ms=1, + redirect_chain=[], + ) + # Googlebot gets the clean page (matrix mix); every other bot gets + # the captcha challenge. + if "Googlebot" in user_agent and "Image" not in user_agent and "Video" not in user_agent and "News" not in user_agent: + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=clean_body, + elapsed_ms=1, + redirect_chain=[], + ) + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=challenge_body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + # At least one bot is still accessible (Googlebot) and at least one + # bot must be flagged as a challenge page. ``partial`` exposes the + # per-bot reason list, so we can assert the literal ``(challenge page)`` + # string is present. + self.assertEqual(result.state, "partial") + self.assertIn("(challenge page)", result.finding) + # 8 of 9 probe bots are flagged: only Googlebot is accessible. + # Score is round(1/9 * 6) = 1. + self.assertEqual(result.score, 1) + + async def test_bot_access_baseline_suppresses_captcha_title(self) -> None: + """F4-06: a title that literally contains ``captcha`` does NOT trigger + the bot-only finding when the browser baseline also contains + ``captcha`` in its title (site-wide pattern, not bot discrimination). + """ + captcha_body = ( + "reCAPTCHA challenge" + "
" + + ("Site-wide captcha announcement that everyone sees. " * 80) + + "
" + ) + context = make_audit_context(homepage_html=captcha_body) + + async def fake_fetch(url: str, user_agent: str = "", **kwargs: object) -> FetchResult: + return FetchResult( + requested_url=url, + final_url=url, + status_code=200, + headers={"content-type": "text/html"}, + text=captcha_body, + elapsed_ms=1, + redirect_chain=[], + ) + + with patch("app.checks.bot_access.fetch_url", new=fake_fetch): + result = await check_bot_access(context) + + # The browser also got the captcha title — site-wide, not bot-only. + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 6) + self.assertNotIn("challenge page", result.finding) + + +class MachineSurfaceTests(unittest.IsolatedAsyncioTestCase): + def _context(self, homepage_html: str, headers: dict[str, str] | None = None) -> AuditContext: + return make_audit_context( + homepage_html=homepage_html, + homepage_headers=headers or None, + homepage_final_url=f"{EXAMPLE_URL}/", + ) + + async def test_warns_when_default_scope_has_no_optional_surfaces(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(self._context("Example")) + + self.assertEqual(result.state, "warn") + self.assertEqual(result.score, 0) + self.assertIn("across 5 included discovery families", result.finding) + self.assertIn("/llms-full.txt", result.fix) + self.assertNotIn("OpenAPI/API Catalog", result.fix) + + async def test_optional_scope_toggles_expand_only_selected_machine_families(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + scenarios = ( + ( + {}, + "across 5 included discovery families", + ("OpenAPI/API Catalog", "OAuth metadata", "commerce protocol metadata"), + ), + ( + {"include_protocols": True}, + "across 14 included discovery families", + ("OAuth metadata", "commerce protocol metadata"), + ), + ( + {"include_account_auth": True}, + "across 8 included discovery families", + ("OpenAPI/API Catalog", "commerce protocol metadata"), + ), + ( + {"include_ecommerce": True}, + "across 7 included discovery families", + ("OpenAPI/API Catalog", "OAuth metadata"), + ), + ) + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + ): + for kwargs, expected_count, excluded_recommendations in scenarios: + with self.subTest(scope=kwargs): + result = await check_machine_surfaces( + self._context("Example"), + **kwargs, + ) + + self.assertEqual(result.state, "warn") + self.assertIn(expected_count, result.finding) + for excluded_recommendation in excluded_recommendations: + self.assertNotIn(excluded_recommendation, result.fix) + + async def test_partial_default_scope_reports_excluded_optional_surface_families(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + headers = { + "content-type": "text/html", + "link": '; rel="api-catalog"', + } + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + self._context("Example", headers=headers) + ) + + self.assertEqual(result.state, "partial") + self.assertEqual(result.score, 1) + self.assertIn("Link header discovery", result.finding) + self.assertIn("Essentials checked 5 discovery families selected for this audit", result.finding) + self.assertIn("API/protocol surfaces, account/auth surfaces, commerce surfaces were excluded", result.finding) + + async def test_full_scope_passes_with_protocol_account_and_commerce_surfaces(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/.well-known/api-catalog"): + return FetchResult( + url, + url, + 200, + {"content-type": "application/json"}, + '{"name":"MachineRead API catalog","items":["api"]}', + 1, + [], + ) + if url.endswith("/.well-known/oauth-authorization-server"): + return FetchResult( + url, + url, + 200, + {"content-type": "application/json"}, + '{"issuer":"https://example.com","authorization_endpoint":"https://example.com/oauth"}', + 1, + [], + ) + if url.endswith("/.well-known/x402"): + return FetchResult( + url, + url, + 200, + {"content-type": "application/json"}, + '{"name":"Commerce metadata","accepts":["x402"]}', + 1, + [], + ) + return FetchResult(url, url, 404, {"content-type": "text/plain"}, "not found", 1, []) + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + self._context("Example"), + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + ) + + self.assertEqual(result.state, "pass") + self.assertEqual(result.score, 3) + self.assertIn("API catalog", result.finding) + self.assertIn("OAuth authorization metadata", result.finding) + self.assertIn("agentic commerce metadata", result.finding) + + +class AgentReadinessTests(unittest.IsolatedAsyncioTestCase): + async def test_strict_lens_separates_agent_native_signals(self) -> None: + context = make_audit_context( + homepage_headers={}, + robots_text=ROBOTS_WITH_SITEMAP, + sitemap_text=BASIC_SITEMAP, + ) + + with ( + patch("app.agent_readiness.best_sitemap", new=AsyncMock(return_value=(True, 1, False, False, True))), + patch("app.agent_readiness.agent_text_access", new=AsyncMock(return_value=(False, []))), + patch("app.agent_readiness._json_surface_available", new=AsyncMock(return_value=False)), + patch("app.agent_readiness._auth_md_available", new=AsyncMock(return_value=False)), + patch("app.agent_readiness._has_dns_aid", new=AsyncMock(return_value=False)), + ): + summary = await build_agent_readiness_summary(context) + + self.assertEqual(summary.score, 25) + self.assertEqual(summary.earned, 2) + self.assertEqual(summary.max, 8) + self.assertIn("robots.txt published", summary.passed) + self.assertIn("llms.txt or Markdown negotiation", summary.missing) + self.assertIn("API Catalog excluded by audit scope.", summary.not_checked) + self.assertIn("explicit agent-native discovery", summary.caveat) + + async def test_full_scope_exposes_a2a_and_split_commerce_protocols(self) -> None: + context = make_audit_context( + homepage_headers={}, + robots_text=( + "User-agent: GPTBot\nAllow: /\n" + "Content-Signal: search=yes\n" + "Sitemap: https://example.com/sitemap.xml" + ), + sitemap_text=BASIC_SITEMAP, + ) + + async def fake_json_surface( + _context: AuditContext, + paths: tuple[str, ...], + _accept: str, + _require_keys: tuple[str, ...] | None = None, + ) -> bool: + return "/.well-known/agent-card.json" in paths or "/.well-known/x402" in paths + + with ( + patch("app.agent_readiness.best_sitemap", new=AsyncMock(return_value=(True, 1, False, False, True))), + patch("app.agent_readiness.agent_text_access", new=AsyncMock(return_value=(True, []))), + patch("app.agent_readiness._json_surface_available", new=fake_json_surface), + patch("app.agent_readiness._auth_md_available", new=AsyncMock(return_value=True)), + patch("app.agent_readiness._has_dns_aid", new=AsyncMock(return_value=False)), + ): + summary = await build_agent_readiness_summary( + context, + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + ) + + self.assertEqual(summary.max, 21) + self.assertEqual(summary.earned, 8) + self.assertEqual(summary.score, 38) + self.assertIn("A2A Agent Card", summary.passed) + self.assertIn("x402 payment metadata", summary.passed) + self.assertIn("MPP commerce metadata", summary.missing) + self.assertIn("UCP commerce metadata", summary.missing) + self.assertIn("ACP commerce metadata", summary.missing) + commerce = next(category for category in summary.categories if category.name == "Commerce") + self.assertEqual(commerce.max, 4) + self.assertEqual(commerce.earned, 1) + self.assertEqual(summary.benchmark.max, 21) + + async def test_scope_toggles_include_only_relevant_agent_readiness_probes(self) -> None: + context = make_audit_context( + homepage_headers={}, + robots_text=ROBOTS_WITH_SITEMAP, + sitemap_text=BASIC_SITEMAP, + ) + scenarios = ( + ({}, 8, "API Catalog", "OAuth/OIDC discovery metadata", "x402 payment metadata"), + ({"include_protocols": True}, 14, None, "OAuth/OIDC discovery metadata", "x402 payment metadata"), + ({"include_account_auth": True}, 11, "API Catalog", None, "x402 payment metadata"), + ({"include_ecommerce": True}, 12, "API Catalog", "OAuth/OIDC discovery metadata", None), + ( + {"include_protocols": True, "include_account_auth": True, "include_ecommerce": True}, + 21, + None, + None, + None, + ), + ) + + with ( + patch("app.agent_readiness.best_sitemap", new=AsyncMock(return_value=(True, 1, False, False, True))), + patch("app.agent_readiness.agent_text_access", new=AsyncMock(return_value=(False, []))), + patch("app.agent_readiness._json_surface_available", new=AsyncMock(return_value=False)), + patch("app.agent_readiness._auth_md_available", new=AsyncMock(return_value=False)), + patch("app.agent_readiness._has_dns_aid", new=AsyncMock(return_value=False)), + ): + for kwargs, expected_max, protocol_excluded, auth_excluded, commerce_excluded in scenarios: + with self.subTest(scope=kwargs): + summary = await build_agent_readiness_summary(context, **kwargs) + + self.assertEqual(summary.max, expected_max) + self.assertEqual(summary.benchmark.max, expected_max) + not_checked = set(summary.not_checked) + for excluded_label in ( + protocol_excluded, + auth_excluded, + commerce_excluded, + ): + if excluded_label is None: + continue + self.assertIn(f"{excluded_label} excluded by audit scope.", not_checked) + included_labels = { + label + for label in ("API Catalog", "OAuth/OIDC discovery metadata", "x402 payment metadata") + if label not in (protocol_excluded, auth_excluded, commerce_excluded) + } + for included_label in included_labels: + self.assertNotIn(f"{included_label} excluded by audit scope.", not_checked) + + +class EntityCacheTests(unittest.TestCase): + def test_reads_fresh_cache_without_public_lookup(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + cache_path = Path(temp_dir) / "entity.sqlite3" + with patch.dict( + "os.environ", + {"ENTITY_CACHE_PATH": str(cache_path), "ENTITY_CACHE_TTL_DAYS": "30"}, + ): + set_cached_entity_lookup( + cache_key="example.com", + status="neither", + state="fail", + evidence_level="verified", + score=0, + max_score=10, + finding="No entity found.", + fix="Build earned citations.", + ) + + cached = get_cached_entity_lookup("example.com") + + self.assertIsNotNone(cached) + assert cached is not None + self.assertEqual(cached.status, "neither") + self.assertEqual(cached.finding, "No entity found.") + + def test_expired_cache_is_ignored(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + cache_path = Path(temp_dir) / "entity.sqlite3" + with patch.dict( + "os.environ", + {"ENTITY_CACHE_PATH": str(cache_path), "ENTITY_CACHE_TTL_DAYS": "0"}, + ): + set_cached_entity_lookup( + cache_key="example.com", + status="both", + state="pass", + evidence_level="verified", + score=10, + max_score=10, + finding="Entity found.", + fix="No action needed.", + ) + + cached = get_cached_entity_lookup("example.com") + + self.assertIsNone(cached) + + +class RubricTests(unittest.TestCase): + def _calibrated_essentials_checks(self) -> list[CheckResult]: + return [ + CheckResult( + pillar=group.pillar, + check_name=group.check_name, + label=group.check_name, + state="pass", + score=group.max_score, + max_score=group.max_score, + finding="Included group passed.", + fix="No action needed.", + effort="low", + ) + for group in ESSENTIALS_CHECK_GROUPS + ] + + def _agent_readiness_summary(self) -> AgentReadinessSummary: + return AgentReadinessSummary( + score=100, + earned=8, + max=8, + label="Agent-native signals present", + categories=[], + passed=[], + missing=[], + not_checked=[], + benchmark=build_agent_benchmark_comparison(score=100, earned=8, maximum=8), + caveat="Strict agent-native readiness lens.", + ) + + def test_essentials_check_group_calibration_is_current(self) -> None: + expected_groups = { + "social": 2, + "wikipedia": 4, + "robots_txt": 6, + "bot_access": 6, + "html_structure": 4, + "schema_ld": 5, + "llms_txt": 5, + "ssr": 4, + "machine_surfaces": 3, + "pagespeed": 3, + "canonical": 5, + "indexing": 5, + "search_discovery": 4, + } + + self.assertEqual(ESSENTIALS_CHECK_GROUP_COUNT, 13) + self.assertEqual(ESSENTIALS_CHECKED_MAX, 56) + self.assertEqual( + {group.check_name: group.max_score for group in ESSENTIALS_CHECK_GROUPS}, + expected_groups, + ) + + def test_result_assembly_preserves_essentials_denominator(self) -> None: + result = build_result( + "https://example.com", + self._calibrated_essentials_checks(), + self._agent_readiness_summary(), + ) + included = [check for check in result.checks if check.state != "locked"] + advanced = [check for check in result.checks if check.state == "locked"] + + self.assertEqual(len(included), ESSENTIALS_CHECK_GROUP_COUNT) + self.assertEqual(sum(check.max_score for check in included), ESSENTIALS_CHECKED_MAX) + self.assertEqual(result.benchmark.checked_score, ESSENTIALS_CHECKED_MAX) + self.assertEqual(result.benchmark.checked_max, ESSENTIALS_CHECKED_MAX) + self.assertEqual(result.benchmark.score, 100) + self.assertEqual(result.overall_score, ESSENTIALS_CHECKED_MAX) + self.assertEqual(len(advanced), 9) + self.assertIn(f"{ESSENTIALS_CHECKED_MAX} checked points", result.benchmark.caveat) + + def test_result_scope_metadata_matches_every_toggle_combination(self) -> None: + scenarios = ( + (False, False, False, "General website", {"API and protocol discovery", "Account/auth discovery", "Commerce protocol metadata", "Catalog JSON"}, set()), + (True, False, False, "General website + API/protocol", {"Account/auth discovery", "Commerce protocol metadata", "Catalog JSON"}, {"API and protocol discovery"}), + (False, True, False, "General website + account/auth", {"API and protocol discovery", "Commerce protocol metadata", "Catalog JSON"}, {"Account/auth discovery"}), + (False, False, True, "Commerce storefront", {"API and protocol discovery", "Account/auth discovery"}, {"Commerce protocol metadata", "Catalog JSON"}), + (True, True, True, "Commerce storefront + API/protocol + account/auth", set(), {"API and protocol discovery", "Account/auth discovery", "Commerce protocol metadata", "Catalog JSON"}), + ) + + for include_protocols, include_account_auth, include_ecommerce, label, excluded, included in scenarios: + with self.subTest( + include_protocols=include_protocols, + include_account_auth=include_account_auth, + include_ecommerce=include_ecommerce, + ): + result = build_result( + "https://example.com", + self._calibrated_essentials_checks(), + self._agent_readiness_summary(), + include_protocols=include_protocols, + include_account_auth=include_account_auth, + include_ecommerce=include_ecommerce, + ) + included_rows = [check for check in result.checks if check.state != "locked"] + workflow_row = next( + check for check in result.checks if check.check_name == "agent_task_simulation" + ) + + self.assertEqual(result.scope.label, label) + self.assertEqual(len(included_rows), ESSENTIALS_CHECK_GROUP_COUNT) + self.assertEqual(sum(check.max_score for check in included_rows), ESSENTIALS_CHECKED_MAX) + self.assertTrue(excluded.issubset(set(result.scope.excluded_optional_surfaces))) + self.assertTrue(included.issubset(set(result.scope.included_optional_surfaces))) + expected_workflow_label = "Agent Commerce Simulation" if include_ecommerce else "Agent Workflow Simulation" + self.assertEqual(workflow_row.label, expected_workflow_label) + self.assertIn("same selected Essentials scope", result.benchmark.caveat) + + def test_locked_checks_reserve_full_rubric_points(self) -> None: + locked_total = sum(check.max_score for check in locked_checks()) + + self.assertEqual(locked_total, 44) + + def test_locked_workflow_check_follows_commerce_scope(self) -> None: + general = next(check for check in locked_checks() if check.check_name == "agent_task_simulation") + commerce = next( + check for check in locked_checks(include_ecommerce=True) + if check.check_name == "agent_task_simulation" + ) + + self.assertEqual(general.label, "Agent Workflow Simulation") + self.assertEqual(commerce.label, "Agent Commerce Simulation") + self.assertIn("conversion", general.finding) + self.assertIn("checkout", commerce.finding) + + def test_benchmark_comparison_uses_free_evidence_score(self) -> None: + checks = [ + CheckResult( + pillar="scrapability", + check_name="html_structure", + label="Semantic HTML", + state="pass", + score=28, + max_score=40, + finding="Readable HTML.", + fix="No action needed.", + effort="low", + ), + CheckResult( + pillar="seo", + check_name="multi_engine_index_coverage", + label="Index coverage", + state="locked", + evidence_level="not_applicable", + available_in="Starter", + score=0, + max_score=20, + finding="Locked.", + fix="Upgrade to verify.", + effort="medium", + ), + ] + + comparison = build_benchmark_comparison(checks) + + self.assertEqual(comparison.score, 70) + self.assertEqual(comparison.checked_score, 28) + self.assertEqual(comparison.checked_max, 40) + self.assertEqual(comparison.benchmark_count, len(comparison.entries)) + self.assertGreaterEqual(comparison.benchmark_count, 12) + self.assertGreaterEqual(len(comparison.nearest), 1) + self.assertIn("same selected Essentials scope", comparison.caveat) + + def test_benchmark_comparison_follows_selected_scope(self) -> None: + checks = [ + CheckResult( + pillar="scrapability", + check_name="html_structure", + label="Semantic HTML", + state="pass", + score=28, + max_score=40, + finding="Readable HTML.", + fix="No action needed.", + effort="low", + ) + ] + + default_comparison = build_benchmark_comparison(checks) + full_scope_comparison = build_benchmark_comparison( + checks, + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + ) + default_entry = default_comparison.entries[0] + full_scope_entry = next(entry for entry in full_scope_comparison.entries if entry.name == default_entry.name) + agent_comparison = build_agent_benchmark_comparison( + score=31, + earned=5, + maximum=21, + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + ) + + self.assertEqual(default_comparison.benchmark_count, len(default_comparison.entries)) + self.assertEqual(full_scope_comparison.benchmark_count, len(full_scope_comparison.entries)) + self.assertGreaterEqual(default_comparison.benchmark_count, 12) + self.assertEqual(default_comparison.benchmark_count, full_scope_comparison.benchmark_count) + self.assertEqual(default_entry.agent_readiness_max, 8) + self.assertEqual(full_scope_entry.agent_readiness_max, 21) + self.assertEqual(agent_comparison.benchmark_count, full_scope_comparison.benchmark_count) + self.assertEqual(agent_comparison.max, 21) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_machine_surfaces_reachability.py b/backend/tests/test_machine_surfaces_reachability.py new file mode 100644 index 0000000000000000000000000000000000000000..be3b3617849785473499e654e8c5c3166e5787df --- /dev/null +++ b/backend/tests/test_machine_surfaces_reachability.py @@ -0,0 +1,549 @@ +import sys +import unittest +from pathlib import Path +from unittest.mock import AsyncMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.audit_context import AuditContext +from app.checks.machine_surfaces import _surface_reachability, check_machine_surfaces +from app.fetching import FetchResult + + +_BASE_URL = "https://example.com" + + +def _fetch_result( + url: str, + status_code: int | None = 200, + text: str = "", + headers: dict[str, str] | None = None, + error: str | None = None, +) -> FetchResult: + return FetchResult( + requested_url=url, + final_url=url, + status_code=status_code, + headers=headers or {}, + text=text, + elapsed_ms=1, + redirect_chain=[], + error=error, + ) + + +def _context( + homepage_html: str, + homepage_headers: dict[str, str] | None = None, + homepage_ok: bool = True, +) -> AuditContext: + homepage = _fetch_result( + _BASE_URL, + status_code=200 if homepage_ok else None, + text=homepage_html, + headers=homepage_headers, + error=None if homepage_ok else "homepage unavailable", + ) + return AuditContext( + url=_BASE_URL, + homepage=homepage, + robots=_fetch_result(f"{_BASE_URL}/robots.txt", status_code=404, text="not found"), + sitemap=_fetch_result(f"{_BASE_URL}/sitemap.xml", status_code=404, text="not found"), + ) + + +async def _surface_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/llms-full.txt"): + return _fetch_result( + url, + text="# Example full export\n\nMachine-readable documentation for agents.", + headers={"content-type": "text/plain"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + +class MachineSurfaceReachabilityTests(unittest.IsolatedAsyncioTestCase): + async def test_linked_surface_has_no_orphan_note(self) -> None: + context = _context( + 'LLM export' + ) + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=_surface_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertNotIn("Reachability note:", result.finding) + self.assertNotIn("agents may not discover them", result.finding) + + async def test_unlinked_surface_has_orphan_note(self) -> None: + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=_surface_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertIn("Reachability note: /llms-full.txt", result.finding) + self.assertIn("agents may not discover them", result.finding) + + async def test_link_header_makes_surface_reachable(self) -> None: + context = _context( + "
Example
", + homepage_headers={ + "link": '; rel="alternate"; type="text/plain"' + }, + ) + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=_surface_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertNotIn("Reachability note:", result.finding) + + async def test_multiple_orphans_are_all_listed(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/llms-full.txt"): + return await _surface_fetch(url, **kwargs) + if url.endswith("/feed.xml"): + return _fetch_result( + url, + text="Example updates", + headers={"content-type": "application/rss+xml"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + _context("
Example
") + ) + + self.assertIn("Reachability note:", result.finding) + self.assertIn("/feed.xml", result.finding) + self.assertIn("/llms-full.txt", result.finding) + + async def test_no_discovered_surfaces_has_no_orphan_note(self) -> None: + async def missing_fetch(url: str, **kwargs: object) -> FetchResult: + return _fetch_result(url, status_code=404, text="not found") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=missing_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + _context("
Example
") + ) + + self.assertNotIn("Reachability note:", result.finding) + + async def test_orphan_note_changes_only_finding(self) -> None: + linked_context = _context( + '' + ) + orphaned_context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=_surface_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + linked_result = await check_machine_surfaces(linked_context) + orphaned_result = await check_machine_surfaces(orphaned_context) + + self.assertEqual(orphaned_result.state, linked_result.state) + self.assertEqual(orphaned_result.score, linked_result.score) + self.assertEqual(orphaned_result.fix, linked_result.fix) + self.assertNotEqual(orphaned_result.finding, linked_result.finding) + self.assertIn("Reachability note:", orphaned_result.finding) + self.assertNotIn("Reachability note:", orphaned_result.fix) + + async def test_relative_homepage_href_resolves_to_surface(self) -> None: + context = _context( + 'LLM export' + ) + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=_surface_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertNotIn("Reachability note:", result.finding) + + def test_missing_homepage_soup_returns_empty_note(self) -> None: + context = _context("", homepage_ok=False) + + note = _surface_reachability( + {"/llms-full.txt"}, + None, + "", + context, + ) + + self.assertEqual(note, "") + + # ------------------------------------------------------------------ + # Conventional path probes (Part A) + # ------------------------------------------------------------------ + + async def test_conventional_docs_path_appears_positively(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/docs"): + return _fetch_result( + url, + text="

Documentation

", + headers={"content-type": "text/html"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertIn("Conventional paths found: /docs.", result.finding) + + async def test_api_missing_when_protocols_excluded(self) -> None: + async def missing_fetch(url: str, **kwargs: object) -> FetchResult: + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=missing_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + context, + include_protocols=False, + ) + + self.assertIn("API path not checked (excluded by scope).", result.finding) + + async def test_pricing_and_integrations_missing_when_commerce_excluded(self) -> None: + async def missing_fetch(url: str, **kwargs: object) -> FetchResult: + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=missing_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + context, + include_ecommerce=False, + ) + + self.assertIn( + "Pricing and integrations paths not checked (excluded by scope).", + result.finding, + ) + + async def test_all_conventional_paths_listed_positively_when_full_scope(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + for path in ("/docs", "/pricing", "/integrations", "/api"): + if url.endswith(path): + return _fetch_result( + url, + text=f"

{path}

", + headers={"content-type": "text/html"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + context, + include_protocols=True, + include_ecommerce=True, + ) + + self.assertIn( + "Conventional paths found: /docs, /pricing, /integrations, /api.", + result.finding, + ) + + async def test_conventional_paths_do_not_change_state_score_or_fix(self) -> None: + async def with_paths_fetch(url: str, **kwargs: object) -> FetchResult: + for path in ("/docs", "/pricing", "/integrations", "/api"): + if url.endswith(path): + return _fetch_result( + url, + text=f"

{path}

", + headers={"content-type": "text/html"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + async def without_paths_fetch(url: str, **kwargs: object) -> FetchResult: + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=with_paths_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + with_paths_result = await check_machine_surfaces( + context, + include_protocols=True, + include_ecommerce=True, + ) + with ( + patch("app.checks.machine_surfaces.fetch_url", new=without_paths_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + without_paths_result = await check_machine_surfaces( + context, + include_protocols=True, + include_ecommerce=True, + ) + + self.assertEqual(with_paths_result.state, without_paths_result.state) + self.assertEqual(with_paths_result.score, without_paths_result.score) + self.assertEqual(with_paths_result.fix, without_paths_result.fix) + self.assertIn("Conventional paths found:", with_paths_result.finding) + self.assertNotIn( + "Conventional paths found:", without_paths_result.finding + ) + + # ------------------------------------------------------------------ + # Docs-page reachability (Part B) + # ------------------------------------------------------------------ + + async def test_docs_page_linked_surface_drops_orphan_note(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/llms-full.txt"): + return _fetch_result( + url, + text="# Example full export\n\nMachine-readable docs for agents.", + headers={"content-type": "text/plain"}, + ) + if url.endswith("/docs"): + return _fetch_result( + url, + text=( + "" + '' + "LLM export" + "" + "" + ), + headers={"content-type": "text/html"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + # Homepage does NOT link to /llms-full.txt, so without docs-page + # reachability this surface would be orphaned. + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertNotIn("Reachability note:", result.finding) + + async def test_no_docs_page_keeps_homepage_only_orphan(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/llms-full.txt"): + return _fetch_result( + url, + text="# Example full export\n\nMachine-readable docs for agents.", + headers={"content-type": "text/plain"}, + ) + # /docs returns 404 + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertIn("Reachability note: /llms-full.txt", result.finding) + + async def test_docs_page_with_no_anchors_does_not_crash(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/llms-full.txt"): + return _fetch_result( + url, + text="# Example full export\n\nMachine-readable docs for agents.", + headers={"content-type": "text/plain"}, + ) + if url.endswith("/docs"): + return _fetch_result( + url, + text="

No links here

", + headers={"content-type": "text/html"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + # Should not raise; surface remains orphaned. + result = await check_machine_surfaces(context) + + self.assertIn("Reachability note: /llms-full.txt", result.finding) + + async def test_docs_page_relative_href_resolves_via_make_root_url(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/llms-full.txt"): + return _fetch_result( + url, + text="# Example full export\n\nMachine-readable docs for agents.", + headers={"content-type": "text/plain"}, + ) + if url.endswith("/docs"): + return _fetch_result( + url, + text=( + "" + 'LLM export' + "" + ), + headers={"content-type": "text/html"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertNotIn("Reachability note:", result.finding) + + # ------------------------------------------------------------------ + # ai-plugin.json valid + malformed (Part A) + # ------------------------------------------------------------------ + + async def test_ai_plugin_valid_shape_detected(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/.well-known/ai-plugin.json"): + return _fetch_result( + url, + text=( + '{"schema_version": "v1", ' + '"name_for_model": "example", ' + '"name_for_human": "Example Plugin", ' + '"api": {"url": "https://example.com/api"}}' + ), + headers={"content-type": "application/json"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + context, + include_protocols=True, + ) + + self.assertIn("legacy ai-plugin.json", result.finding) + + async def test_ai_plugin_malformed_rejected(self) -> None: + async def fake_fetch(url: str, **kwargs: object) -> FetchResult: + if url.endswith("/.well-known/ai-plugin.json"): + return _fetch_result( + url, + text="this is not { valid: json at all <<>>", + headers={"content-type": "application/json"}, + ) + return _fetch_result(url, status_code=404, text="not found") + + context = _context("
Example
") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=fake_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces( + context, + include_protocols=True, + ) + + self.assertNotIn("legacy ai-plugin.json", result.finding) + + # ------------------------------------------------------------------ + # NLWeb Schemamap robots directive (Part B) + # ------------------------------------------------------------------ + + async def test_nlweb_schemamap_detected(self) -> None: + context = AuditContext( + url=_BASE_URL, + homepage=_fetch_result(_BASE_URL, text="
Example
"), + robots=_fetch_result( + f"{_BASE_URL}/robots.txt", + status_code=200, + text=( + "User-agent: *\n" + "Allow: /\n" + "Schemamap: https://example.com/nlweb/schemamap.json\n" + ), + ), + sitemap=_fetch_result( + f"{_BASE_URL}/sitemap.xml", status_code=404, text="not found" + ), + ) + + async def missing_fetch(url: str, **kwargs: object) -> FetchResult: + return _fetch_result(url, status_code=404, text="not found") + + with ( + patch("app.checks.machine_surfaces.fetch_url", new=missing_fetch), + patch("app.checks.machine_surfaces._dns_aid_surfaces", new=AsyncMock(return_value=[])), + patch("app.checks.machine_surfaces._ard_dns_hints", new=AsyncMock(return_value=[])), + ): + result = await check_machine_surfaces(context) + + self.assertIn("nlweb schemamap", result.finding.lower()) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_preset_integration.py b/backend/tests/test_preset_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..9691c8990a66db17a63437ca4a21e790a346964b --- /dev/null +++ b/backend/tests/test_preset_integration.py @@ -0,0 +1,449 @@ +"""Preset pipeline integration tests. + +End-to-end coverage that proves every one of the seven presets works through +the real FastAPI /audit pipeline, lands on the expected benchmark scope key, +and produces the matching strict-agent-readiness maximum. Also exercises the +two backward-compatibility paths the chunk promises: + +- Legacy callers sending only the three ``include_*`` booleans keep working. +- A preset always wins over a conflicting ``include_*`` value, so the report + reflects the preset the user picked rather than the leftover legacy flags. + +The checks, agent-readiness summary, and benchmark assembly are all mocked so +the test stays hermetic and fast; the assertions focus on the scope metadata +that the preset model owns and the audit response contract must preserve. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from pathlib import Path +from unittest.mock import AsyncMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from fastapi.testclient import TestClient # noqa: E402 + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app import benchmarks # noqa: E402 +from app.main import app # noqa: E402 +from app.models import ( # noqa: E402 + AgentBenchmarkComparison, + AgentReadinessCategory, + AgentReadinessSummary, + CheckResult, +) +from app.presets import ( # noqa: E402 + PRESETS, + benchmark_scope_key_for_scope, + resolve_scope, +) + + +# (preset_key, expected_scope_key, expected_agent_max) +# These pairs are derived from the preset definitions. The expected scope key +# matches the documented 8-variant benchmark contract; the expected agent +# max matches ``_agent_max_for_scope`` in ``backend/app/benchmarks.py``. +EXPECTED_PRESET_SCOPE: dict[str, tuple[str, int]] = { + "blog": ("p0_a0_c0", 8), + "corporate": ("p0_a0_c0", 8), + "services": ("p0_a0_c0", 8), + "ecommerce": ("p1_a1_c1", 21), + "news": ("p0_a0_c0", 8), + "saas": ("p1_a1_c0", 17), + # Custom defaults to the Blog/Content base. + "custom": ("p0_a0_c0", 8), +} + + +def _stub_check() -> CheckResult: + return CheckResult( + pillar="scrapability", + check_name="preset_probe", + label="Preset integration probe", + state="partial", + evidence_level="inferred", + available_in="Essentials preset fixture", + score=3, + max_score=5, + finding="Stub evidence for preset pipeline integration.", + fix="Replace stub evidence with real fixture data.", + effort="medium", + ) + + +def _agent_readiness(max_value: int) -> AgentReadinessSummary: + return AgentReadinessSummary( + score=35, + earned=7, + max=max_value, + label="Developing agent-native readiness", + categories=[ + AgentReadinessCategory( + name="Preset category", + earned=2, + max=5, + score=40, + passed=["Public discovery signal"], + missing=["Public protocol signal"], + excluded=["No excluded preset signals"], + ) + ], + passed=["Public discovery signal"], + missing=["Public protocol signal"], + not_checked=["Live agent journey"], + benchmark=AgentBenchmarkComparison( + score=35, + earned=7, + max=max_value, + benchmark_count=0, + median_score=0, + percentile=100, + position_label="Preset fixture position", + nearest=[], + entries=[], + basis="Preset fixture agent benchmark basis", + snapshot_date="2026-07-18", + caveat="Preset fixture agent benchmark caveat.", + ), + caveat="Preset fixture readiness caveat.", + ) + + +class PresetPipelineIntegrationTests(unittest.TestCase): + """Every preset resolves through the real /audit endpoint and lands on + the expected benchmark scope + strict-agent-readiness maximum.""" + + def _post_audit(self, body: dict) -> tuple[int, dict]: + normalized_url = "https://preset.example/" + with ( + patch("app.main.validate_url", return_value=normalized_url), + patch( + "app.main._build_context_or_error", + new=AsyncMock(return_value=object()), + ), + patch( + "app.main._run_essential_checks", + new=AsyncMock(return_value=[_stub_check()]), + ), + patch( + "app.main._safe_agent_readiness_summary", + new=AsyncMock(side_effect=lambda ctx, p, a, c, **_: _agent_readiness( + benchmarks._agent_max_for_scope(p, a, c) + )), + ), + ): + response = TestClient(app).post("/audit", json=body) + return response.status_code, response.json() + + def test_all_seven_presets_return_200(self) -> None: + for preset_key in PRESETS: + with self.subTest(preset=preset_key): + status, _ = self._post_audit({"url": "preset.example", "preset": preset_key}) + self.assertEqual(status, 200, f"preset={preset_key} returned {status}") + + def test_each_preset_sets_expected_benchmark_scope_key(self) -> None: + # The backend exposes the benchmark scope key indirectly through the + # scope booleans. We re-derive the canonical key from those booleans + # and compare it against the expected preset map, so a future change + # that drifts a preset away from its documented scope key will fail. + for preset_key, (expected_key, _expected_max) in EXPECTED_PRESET_SCOPE.items(): + with self.subTest(preset=preset_key): + _status, payload = self._post_audit( + {"url": "preset.example", "preset": preset_key} + ) + scope = payload["scope"] + derived_key = ( + f"p{int(scope['include_protocols'])}_" + f"a{int(scope['include_account_auth'])}_" + f"c{int(scope['include_ecommerce'])}" + ) + self.assertEqual( + derived_key, + expected_key, + f"preset={preset_key} expected benchmark key " + f"{expected_key!r}, got {derived_key!r}", + ) + + def test_each_preset_sets_expected_strict_agent_max(self) -> None: + for preset_key, (_expected_key, expected_max) in EXPECTED_PRESET_SCOPE.items(): + with self.subTest(preset=preset_key): + _status, payload = self._post_audit( + {"url": "preset.example", "preset": preset_key} + ) + agent_max = payload["agent_readiness"]["max"] + self.assertEqual( + agent_max, + expected_max, + f"preset={preset_key} expected strict-agent max " + f"{expected_max}, got {agent_max}", + ) + + def test_each_preset_sets_preset_applied_field(self) -> None: + for preset_key in PRESETS: + with self.subTest(preset=preset_key): + _status, payload = self._post_audit( + {"url": "preset.example", "preset": preset_key} + ) + self.assertEqual( + payload["scope"]["preset_applied"], + preset_key, + ) + self.assertEqual( + payload["scope"]["machine_surfaces_scope"], + resolve_scope(preset_key, None).machine_surfaces, + ) + + def test_scope_label_uses_preset_definition_label(self) -> None: + for preset_key, scope in resolve_scope.__globals__["PRESETS"].items(): + with self.subTest(preset=preset_key): + _status, payload = self._post_audit( + {"url": "preset.example", "preset": preset_key} + ) + self.assertEqual( + payload["scope"]["label"], + scope.label, + ) + + +class LegacyBackwardCompatTests(unittest.TestCase): + """The legacy three-boolean path keeps working unchanged.""" + + def _post_audit(self, body: dict) -> tuple[int, dict]: + normalized_url = "https://legacy.example/" + with ( + patch("app.main.validate_url", return_value=normalized_url), + patch( + "app.main._build_context_or_error", + new=AsyncMock(return_value=object()), + ), + patch( + "app.main._run_essential_checks", + new=AsyncMock(return_value=[_stub_check()]), + ), + patch( + "app.main._safe_agent_readiness_summary", + new=AsyncMock(side_effect=lambda ctx, p, a, c, **_: _agent_readiness( + benchmarks._agent_max_for_scope(p, a, c) + )), + ), + ): + response = TestClient(app).post("/audit", json=body) + return response.status_code, response.json() + + def test_no_preset_no_overrides_uses_default_general_scope(self) -> None: + status, payload = self._post_audit({"url": "legacy.example"}) + self.assertEqual(status, 200) + scope = payload["scope"] + self.assertIsNone(scope["preset_applied"]) + self.assertEqual(scope["overrides_applied"], {}) + self.assertEqual(scope["include_protocols"], False) + self.assertEqual(scope["include_account_auth"], False) + self.assertEqual(scope["include_ecommerce"], False) + self.assertEqual(payload["agent_readiness"]["max"], 8) + self.assertEqual(scope["machine_surfaces_scope"], "common-contextual") + + def test_legacy_booleans_only_passes_with_true_flags(self) -> None: + status, payload = self._post_audit( + { + "url": "legacy.example", + "include_protocols": True, + "include_account_auth": False, + "include_ecommerce": True, + } + ) + self.assertEqual(status, 200) + scope = payload["scope"] + self.assertIsNone(scope["preset_applied"]) + self.assertEqual(scope["include_protocols"], True) + self.assertEqual(scope["include_account_auth"], False) + self.assertEqual(scope["include_ecommerce"], True) + self.assertEqual(payload["agent_readiness"]["max"], 8 + 6 + 4) + + def test_legacy_full_scope_matches_eight_variant_max(self) -> None: + status, payload = self._post_audit( + { + "url": "legacy.example", + "include_protocols": True, + "include_account_auth": True, + "include_ecommerce": True, + } + ) + self.assertEqual(status, 200) + self.assertEqual(payload["agent_readiness"]["max"], 21) + scope = payload["scope"] + self.assertEqual( + ( + f"p{int(scope['include_protocols'])}_" + f"a{int(scope['include_account_auth'])}_" + f"c{int(scope['include_ecommerce'])}" + ), + "p1_a1_c1", + ) + + +class PresetOverridesLegacyTests(unittest.TestCase): + """When preset and legacy booleans disagree, the preset wins.""" + + def _post_audit(self, body: dict) -> tuple[int, dict]: + normalized_url = "https://override.example/" + with ( + patch("app.main.validate_url", return_value=normalized_url), + patch( + "app.main._build_context_or_error", + new=AsyncMock(return_value=object()), + ), + patch( + "app.main._run_essential_checks", + new=AsyncMock(return_value=[_stub_check()]), + ), + patch( + "app.main._safe_agent_readiness_summary", + new=AsyncMock(side_effect=lambda ctx, p, a, c, **_: _agent_readiness( + benchmarks._agent_max_for_scope(p, a, c) + )), + ), + ): + response = TestClient(app).post("/audit", json=body) + return response.status_code, response.json() + + def test_ecommerce_preset_overrides_include_ecommerce_false(self) -> None: + status, payload = self._post_audit( + { + "url": "override.example", + "preset": "ecommerce", + "include_ecommerce": False, + } + ) + self.assertEqual(status, 200) + scope = payload["scope"] + self.assertEqual(scope["preset_applied"], "ecommerce") + # The preset wins: ecommerce scope must stay on even though the legacy + # boolean tried to disable it. + self.assertTrue(scope["include_ecommerce"]) + self.assertEqual(payload["agent_readiness"]["max"], 21) + self.assertEqual( + ( + f"p{int(scope['include_protocols'])}_" + f"a{int(scope['include_account_auth'])}_" + f"c{int(scope['include_ecommerce'])}" + ), + "p1_a1_c1", + ) + + def test_blog_preset_overrides_all_legacy_booleans_true(self) -> None: + # Caller asks for every dimension on, but the Blog/Content preset must + # still resolve to p0_a0_c0 because the preset wins over the legacy + # booleans. + status, payload = self._post_audit( + { + "url": "override.example", + "preset": "blog", + "include_protocols": True, + "include_account_auth": True, + "include_ecommerce": True, + } + ) + self.assertEqual(status, 200) + scope = payload["scope"] + self.assertEqual(scope["preset_applied"], "blog") + self.assertFalse(scope["include_protocols"]) + self.assertFalse(scope["include_account_auth"]) + self.assertFalse(scope["include_ecommerce"]) + self.assertEqual(payload["agent_readiness"]["max"], 8) + + def test_custom_preset_with_no_overrides_matches_legacy_default(self) -> None: + # Custom starts from the same default as Blog; with no overrides it + # should produce the same scope metadata as the legacy default path. + status, payload = self._post_audit( + { + "url": "override.example", + "preset": "custom", + } + ) + self.assertEqual(status, 200) + scope = payload["scope"] + self.assertEqual(scope["preset_applied"], "custom") + self.assertFalse(scope["include_protocols"]) + self.assertFalse(scope["include_account_auth"]) + self.assertFalse(scope["include_ecommerce"]) + self.assertEqual(payload["agent_readiness"]["max"], 8) + self.assertEqual(scope["machine_surfaces_scope"], "common-contextual") + + def test_custom_preset_with_protocol_override_extends_scope(self) -> None: + status, payload = self._post_audit( + { + "url": "override.example", + "preset": "custom", + "custom_overrides": {"protocols": True, "api_catalog": True}, + } + ) + self.assertEqual(status, 200) + scope = payload["scope"] + self.assertEqual(scope["preset_applied"], "custom") + self.assertTrue(scope["include_protocols"]) + self.assertEqual(scope["overrides_applied"]["protocols"], True) + self.assertEqual(scope["overrides_applied"]["api_catalog"], True) + self.assertEqual(payload["agent_readiness"]["max"], 8 + 6) + self.assertEqual(scope["machine_surfaces_scope"], "full") + + +class PresetContractIntegrationTests(unittest.TestCase): + """Cross-check the pipeline's reported metadata against the standalone + ``resolve_scope`` helper, so the two stay in sync.""" + + def test_response_metadata_matches_resolve_scope(self) -> None: + normalized_url = "https://mirror.example/" + for preset_key in PRESETS: + with ( + self.subTest(preset=preset_key), + patch("app.main.validate_url", return_value=normalized_url), + patch( + "app.main._build_context_or_error", + new=AsyncMock(return_value=object()), + ), + patch( + "app.main._run_essential_checks", + new=AsyncMock(return_value=[_stub_check()]), + ), + patch( + "app.main._safe_agent_readiness_summary", + new=AsyncMock(side_effect=lambda ctx, p, a, c, **_: _agent_readiness( + benchmarks._agent_max_for_scope(p, a, c) + )), + ), + ): + response = TestClient(app).post( + "/audit", json={"url": "mirror.example", "preset": preset_key} + ) + self.assertEqual(response.status_code, 200) + payload = response.json() + scope = payload["scope"] + resolved = resolve_scope(preset_key, None) + self.assertEqual(scope["include_protocols"], resolved.include_protocols) + self.assertEqual(scope["include_account_auth"], resolved.include_account_auth) + self.assertEqual(scope["include_ecommerce"], resolved.include_ecommerce) + self.assertEqual(scope["machine_surfaces_scope"], resolved.machine_surfaces) + self.assertEqual( + scope["included_families"], + list(resolved.included_families), + ) + self.assertEqual( + scope["excluded_families"], + list(resolved.excluded_families), + ) + self.assertEqual( + benchmark_scope_key_for_scope(resolved), + ( + f"p{int(scope['include_protocols'])}_" + f"a{int(scope['include_account_auth'])}_" + f"c{int(scope['include_ecommerce'])}" + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_presets.py b/backend/tests/test_presets.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8a11af847b58e5e17b019d46c2ae68a7d8d06b --- /dev/null +++ b/backend/tests/test_presets.py @@ -0,0 +1,350 @@ +"""Preset model unit tests. + +Covers the 7-preset catalog, ResolvedScope resolution, validation rules, +precedence over legacy booleans, backward compatibility, and the benchmark +contract invariants that the preset model must preserve. +""" + +from __future__ import annotations + +import sys +import unittest +from itertools import product +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app import benchmarks +from app.presets import ( + PRESETS, + VALID_PRESETS, + ResolvedScope, + benchmark_scope_key_for_scope, + resolve_scope, + validate_overrides, +) + + +class PresetCatalogTests(unittest.TestCase): + """Catalog-level invariants that the rest of the tests rely on.""" + + def test_all_seven_presets_are_exposed(self) -> None: + self.assertEqual( + set(PRESETS), + {"blog", "corporate", "services", "ecommerce", "news", "saas", "custom"}, + ) + self.assertEqual(VALID_PRESETS, set(PRESETS)) + + def test_blog_is_common_contextual_with_p0_a0_c0(self) -> None: + scope = resolve_scope("blog", None) + self.assertEqual(scope.preset, "blog") + self.assertFalse(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "common-contextual") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p0_a0_c0") + + def test_corporate_is_common_contextual_with_p0_a0_c0(self) -> None: + scope = resolve_scope("corporate", None) + self.assertFalse(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "common-contextual") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p0_a0_c0") + + def test_services_is_common_contextual_with_p0_a0_c0(self) -> None: + scope = resolve_scope("services", None) + self.assertFalse(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "common-contextual") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p0_a0_c0") + + def test_ecommerce_is_full_protocol_scope_with_p1_a1_c1(self) -> None: + scope = resolve_scope("ecommerce", None) + self.assertTrue(scope.include_protocols) + self.assertTrue(scope.include_account_auth) + self.assertTrue(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "full") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p1_a1_c1") + + def test_news_is_common_contextual_with_p0_a0_c0(self) -> None: + scope = resolve_scope("news", None) + self.assertFalse(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "common-contextual") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p0_a0_c0") + + def test_saas_is_full_protocol_scope_with_p1_a1_c0(self) -> None: + scope = resolve_scope("saas", None) + self.assertTrue(scope.include_protocols) + self.assertTrue(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "full") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p1_a1_c0") + + def test_custom_defaults_to_blog_base(self) -> None: + scope = resolve_scope("custom", None) + # Custom starts from the Blog/Content base. + blog_scope = resolve_scope("blog", None) + self.assertEqual(scope.include_protocols, blog_scope.include_protocols) + self.assertEqual( + scope.include_account_auth, blog_scope.include_account_auth + ) + self.assertEqual(scope.include_ecommerce, blog_scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "common-contextual") + self.assertEqual( + scope.included_families, blog_scope.included_families + ) + self.assertEqual(scope.preset, "custom") + + +class CustomOverrideTests(unittest.TestCase): + """Custom/Power User override resolution and validation.""" + + def test_custom_with_no_overrides_matches_blog(self) -> None: + custom = resolve_scope("custom", None) + blog = resolve_scope("blog", None) + self.assertEqual(custom.include_protocols, blog.include_protocols) + self.assertEqual( + custom.include_account_auth, blog.include_account_auth + ) + self.assertEqual(custom.include_ecommerce, blog.include_ecommerce) + self.assertEqual(custom.included_families, blog.included_families) + + def test_custom_can_toggle_a_family_on(self) -> None: + scope = resolve_scope( + "custom", {"oauth_oidc": True, "auth_md": True} + ) + self.assertTrue("oauth_oidc" in scope.included_families) + self.assertTrue("auth_md" in scope.included_families) + self.assertTrue(scope.include_account_auth) + + def test_custom_can_disable_a_default_family(self) -> None: + scope = resolve_scope("custom", {"feed_discovery": False}) + self.assertNotIn("feed_discovery", scope.included_families) + self.assertIn("feed_discovery", scope.excluded_families) + + def test_custom_can_toggle_protocol_dimensions(self) -> None: + scope = resolve_scope( + "custom", + {"protocols": True, "api_catalog": True, "mcp": True}, + ) + self.assertTrue(scope.include_protocols) + self.assertEqual(scope.machine_surfaces, "full") + self.assertIn("api_catalog", scope.included_families) + self.assertIn("mcp", scope.included_families) + + def test_validate_overrides_unknown_key_returns_error(self) -> None: + errors = validate_overrides("custom", {"definitely_unknown": True}) + self.assertTrue(any("Unknown override key" in e for e in errors)) + + def test_validate_overrides_universal_core_key_returns_error(self) -> None: + # ``robots_txt`` is not in the override key set, so it falls through to + # the unknown-key branch. This proves the universal core is rejected. + errors = validate_overrides("custom", {"robots_txt": True}) + self.assertTrue(errors) + self.assertTrue(any("Unknown override key" in e for e in errors)) + + def test_validate_overrides_locked_key_returns_error(self) -> None: + errors = validate_overrides("custom", {"earned_mentions_backlinks": True}) + self.assertTrue(errors) + + def test_validate_overrides_rejects_not_applicable_family(self) -> None: + # LocalBusiness is not applicable for the Blog preset. + errors = validate_overrides("blog", {"localbusiness_schema": True}) + self.assertTrue(any("not applicable" in e for e in errors)) + + def test_validate_overrides_rejects_protocols_with_no_protocol_family(self) -> None: + errors = validate_overrides("custom", {"protocols": True}) + self.assertTrue( + any("protocol family" in e for e in errors), + f"expected protocol family error, got {errors}", + ) + + def test_validate_overrides_rejects_account_auth_with_no_auth_family(self) -> None: + errors = validate_overrides("custom", {"account_auth": True}) + self.assertTrue( + any("auth family" in e for e in errors), + f"expected auth family error, got {errors}", + ) + + def test_validate_overrides_rejects_ecommerce_with_no_commerce_family(self) -> None: + errors = validate_overrides("custom", {"ecommerce": True}) + self.assertTrue( + any("commerce family" in e for e in errors), + f"expected commerce family error, got {errors}", + ) + + def test_validate_overrides_empty_dict_passes(self) -> None: + self.assertEqual(validate_overrides("blog", {}), []) + + def test_validate_overrides_none_passes(self) -> None: + self.assertEqual(validate_overrides("blog", None), []) + + +class PrecedenceTests(unittest.TestCase): + """Preset wins over legacy booleans; legacy path still works.""" + + def test_preset_wins_over_legacy_booleans(self) -> None: + # Legacy booleans say everything on, but blog preset should still + # resolve to p0_a0_c0. + scope = resolve_scope( + "blog", None, True, True, True + ) + self.assertEqual(scope.preset, "blog") + self.assertFalse(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + + def test_legacy_preset_none_with_booleans_works(self) -> None: + scope = resolve_scope(None, None, True, False, True) + self.assertIsNone(scope.preset) + self.assertTrue(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertTrue(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "full") + self.assertEqual(benchmark_scope_key_for_scope(scope), "p1_a0_c1") + + def test_legacy_preset_none_with_no_overrides_works(self) -> None: + scope = resolve_scope(None, None) + self.assertIsNone(scope.preset) + self.assertFalse(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertFalse(scope.include_ecommerce) + self.assertEqual(scope.machine_surfaces, "common-contextual") + + def test_preset_none_with_overrides_is_rejected(self) -> None: + with self.assertRaises(ValueError) as ctx: + resolve_scope(None, {"feed_discovery": True}) + self.assertIn("custom_overrides", str(ctx.exception).lower()) + self.assertIn("preset", str(ctx.exception).lower()) + + def test_overrides_override_preset_dimensions(self) -> None: + # Ecommerce default is p1_a1_c1; explicitly turning off account_auth + # via override should be accepted (it's a valid Custom-style toggle). + scope = resolve_scope("ecommerce", {"account_auth": False}) + self.assertTrue(scope.include_protocols) + self.assertFalse(scope.include_account_auth) + self.assertTrue(scope.include_ecommerce) + + +class BenchmarkContractTests(unittest.TestCase): + """The resolved scopes must map cleanly onto the 8-variant benchmark + contract documented in scripts/check_score_contract.py.""" + + def _all_resolved_keys(self) -> set[str]: + """Yield every benchmark key produced by any preset under any + legacy-boolean override (which Custom uses to bypass the validation + gate for power-user combinations).""" + + keys: set[str] = set() + for preset in PRESETS: + for ( + include_protocols, + include_account_auth, + include_ecommerce, + ) in product((False, True), repeat=3): + # Custom accepts every combination; the standard presets + # validate over their default scope so we only exercise the + # default resolution path here. + if preset == "custom": + keys.add( + benchmark_scope_key_for_scope( + resolve_scope(preset, None) + ) + ) + else: + keys.add( + benchmark_scope_key_for_scope( + resolve_scope( + preset, + None, + include_protocols, + include_account_auth, + include_ecommerce, + ) + ) + ) + return keys + + def test_all_seven_presets_produce_a_key_in_the_eight_variant_set(self) -> None: + expected_keys = { + benchmarks.benchmark_scope_key(p, a, c) + for p, a, c in product((False, True), repeat=3) + } + observed_keys = self._all_resolved_keys() + self.assertTrue( + observed_keys.issubset(expected_keys), + f"preset keys out of contract: {observed_keys}", + ) + + def test_all_seven_presets_produce_strict_agent_max_in_expected_set(self) -> None: + expected_maxes = {8, 11, 12, 14, 15, 17, 18, 21} + observed_maxes: set[int] = set() + for preset in PRESETS: + for ( + include_protocols, + include_account_auth, + include_ecommerce, + ) in product((False, True), repeat=3): + if preset == "custom": + scope = resolve_scope(preset, None) + else: + scope = resolve_scope( + preset, + None, + include_protocols, + include_account_auth, + include_ecommerce, + ) + observed_maxes.add( + benchmarks._agent_max_for_scope( + scope.include_protocols, + scope.include_account_auth, + scope.include_ecommerce, + ) + ) + self.assertTrue( + observed_maxes.issubset(expected_maxes), + f"strict agent max out of contract: {observed_maxes}", + ) + + +class ResolvedScopeShapeTests(unittest.TestCase): + """ResolvedScope shape invariants consumed by the API response.""" + + def test_resolved_scope_included_families_is_sorted(self) -> None: + scope = resolve_scope( + "custom", + {"webmcp": True, "api_catalog": True, "mcp": True}, + ) + self.assertEqual( + list(scope.included_families), + sorted(scope.included_families), + ) + + def test_resolved_scope_excluded_families_is_sorted(self) -> None: + scope = resolve_scope("blog", None) + self.assertEqual( + list(scope.excluded_families), + sorted(scope.excluded_families), + ) + + def test_resolved_scope_is_frozen(self) -> None: + scope = resolve_scope("blog", None) + with self.assertRaises(Exception): + scope.preset = "saas" # type: ignore[misc] + + def test_resolved_scope_preset_label_uses_preset_definition_label(self) -> None: + scope = resolve_scope("ecommerce", None) + self.assertEqual(scope.preset_label, "Ecommerce/Catalog audit") + + def test_resolved_scope_legacy_label_uses_legacy_format(self) -> None: + scope = resolve_scope(None, None, True, False, True) + self.assertEqual(scope.preset_label, "Commerce storefront + API/protocol") + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/backend/tests/test_rate_limits.py b/backend/tests/test_rate_limits.py new file mode 100644 index 0000000000000000000000000000000000000000..146dda1e7e4e2795d82880f789af4d1b290e5370 --- /dev/null +++ b/backend/tests/test_rate_limits.py @@ -0,0 +1,30 @@ +import os +import sys +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.main import DEFAULT_AUDIT_RATE_LIMIT, audit_rate_limit + + +class RateLimitConfigTests(unittest.TestCase): + def test_audit_rate_limit_uses_local_default_when_unset(self) -> None: + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(audit_rate_limit(), DEFAULT_AUDIT_RATE_LIMIT) + + def test_audit_rate_limit_uses_configured_value(self) -> None: + with patch.dict(os.environ, {"MACHINEREAD_AUDIT_RATE_LIMIT": "10/minute"}): + self.assertEqual(audit_rate_limit(), "10/minute") + + def test_audit_rate_limit_strips_and_falls_back_when_blank(self) -> None: + with patch.dict(os.environ, {"MACHINEREAD_AUDIT_RATE_LIMIT": " "}): + self.assertEqual(audit_rate_limit(), DEFAULT_AUDIT_RATE_LIMIT) + + with patch.dict(os.environ, {"MACHINEREAD_AUDIT_RATE_LIMIT": " 5/minute "}): + self.assertEqual(audit_rate_limit(), "5/minute") + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_report_summary.py b/backend/tests/test_report_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbfe3b818c05ba7b3640ec1eae8d038d5826f76 --- /dev/null +++ b/backend/tests/test_report_summary.py @@ -0,0 +1,683 @@ +"""Projection tests for the agent-oriented report summary. + +These tests build synthetic ``AuditResult`` fixtures and call +``build_report_summary`` directly. The expected contract is captured in the +brief: 13 check groups, 56 checked points, 30/40/30 pillars, 8 scope variants, +max 5 attention items, and a fixed ordered tuple of limitation codes. +""" + +from __future__ import annotations + +import sys +import unittest +from itertools import product +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.models import ( + AgentBenchmarkComparison, + AgentReadinessCategory, + AgentReadinessSummary, + AuditResult, + AuditScope, + BenchmarkComparison, + BenchmarkEntry, + CheckResult, + PillarMax, + PillarScores, +) +from app.report_summary import ( + SUMMARY_LIMITATION_CODES, + build_report_summary, +) +from app.checks.locked import locked_checks + + +def _benchmark(*, score: int = 50, snapshot: str = "2026-07-18") -> BenchmarkComparison: + return BenchmarkComparison( + score=score, + checked_score=score, + checked_max=56, + benchmark_count=3, + median_score=score, + percentile=50, + position_label="At median", + nearest=[], + entries=[], + basis="Public fallback benchmark basis.", + snapshot_date=snapshot, + caveat="Benchmark positions are relative context among public peers.", + ) + + +def _agent_readiness( + *, + include_protocols: bool, + include_account_auth: bool, + include_ecommerce: bool, + score: int = 50, + earned: int = 4, +) -> AgentReadinessSummary: + max_value = ( + 8 + + (6 if include_protocols else 0) + + (3 if include_account_auth else 0) + + (4 if include_ecommerce else 0) + ) + return AgentReadinessSummary( + score=score, + earned=earned, + max=max_value, + label="Developing agent-native readiness", + categories=[ + AgentReadinessCategory( + name="Discovery", + earned=2, + max=3, + score=round((2 / 3) * 100), + passed=["robots.txt published"], + missing=["DNS-AID records"], + excluded=[], + ) + ], + passed=["robots.txt published"], + missing=["DNS-AID records"], + not_checked=["Verified crawler IP treatment"], + benchmark=AgentBenchmarkComparison( + score=score, + earned=earned, + max=max_value, + benchmark_count=3, + median_score=score, + percentile=50, + position_label="At median", + nearest=[], + entries=[], + basis="Public fallback agent benchmark basis.", + snapshot_date="2026-07-18", + caveat="Strict agent-readiness positions are relative context.", + ), + caveat="Strict agent-readiness does not imply agent routing or citation share.", + ) + + +def _check( + check_name: str, + pillar: str, + *, + state: str, + earned: int = 0, + max_score: int = 4, + effort: str = "medium", + evidence_level: str = "verified", +) -> CheckResult: + return CheckResult( + pillar=pillar, + check_name=check_name, + label=check_name.replace("_", " ").title(), + state=state, + evidence_level=evidence_level, + available_in="Essentials", + score=earned, + max_score=max_score, + finding=f"{check_name} finding", + fix=f"{check_name} fix", + effort=effort, + ) + + +def _build_result( + *, + include_protocols: bool, + include_account_auth: bool, + include_ecommerce: bool, + preset_applied: str | None = "blog", + checks: list[CheckResult] | None = None, +) -> AuditResult: + if checks is None: + checks = [ + _check("robots_txt", "scrapability", state="partial", earned=4, max_score=6), + _check("bot_access", "scrapability", state="partial", earned=4, max_score=6), + _check("html_structure", "scrapability", state="pass", earned=4, max_score=4), + _check("schema_ld", "scrapability", state="partial", earned=3, max_score=5), + _check("llms_txt", "scrapability", state="partial", earned=3, max_score=5), + _check("ssr", "scrapability", state="pass", earned=4, max_score=4), + _check("machine_surfaces", "scrapability", state="partial", earned=2, max_score=3), + _check("pagespeed", "seo", state="partial", earned=2, max_score=3), + _check("canonical", "seo", state="partial", earned=4, max_score=5), + _check("indexing", "seo", state="partial", earned=4, max_score=5), + _check("search_discovery", "seo", state="partial", earned=3, max_score=4), + _check("social", "off_site", state="partial", earned=1, max_score=2), + _check("wikipedia", "off_site", state="partial", earned=2, max_score=4), + ] + # Always include the 9 locked rows so check counts and locked + # counts match the runtime contract. + checks = list(checks) + list(locked_checks(include_ecommerce)) + scope = AuditScope( + include_protocols=include_protocols, + include_account_auth=include_account_auth, + include_ecommerce=include_ecommerce, + label="Blog/Content audit", + included_optional_surfaces=[], + excluded_optional_surfaces=[], + preset_applied=preset_applied, + overrides_applied={}, + included_families=[], + excluded_families=[], + machine_surfaces_scope="common-contextual", + ) + pillar_scores = PillarScores(off_site=3, scrapability=24, seo=13) + return AuditResult( + api_version="1.0", + url="https://example.com/", + scope=scope, + overall_score=pillar_scores.off_site + pillar_scores.scrapability + pillar_scores.seo, + pillar_scores=pillar_scores, + pillar_max=PillarMax(off_site=30, scrapability=40, seo=30), + agent_readiness=_agent_readiness( + include_protocols=include_protocols, + include_account_auth=include_account_auth, + include_ecommerce=include_ecommerce, + ), + benchmark=_benchmark(), + checks=checks, + ) + + +class ProjectionSmokeTests(unittest.TestCase): + def test_full_projection_smoke(self) -> None: + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + ) + summary = build_report_summary(result) + + self.assertEqual(summary.api_version, "1.0") + self.assertEqual(summary.summary_version, "1.0") + self.assertEqual(summary.url, "https://example.com/") + self.assertEqual(summary.scores.overall.earned, result.overall_score) + self.assertEqual(summary.scores.overall.max, 100) + self.assertEqual(summary.scores.essentials.percent, result.benchmark.score) + self.assertEqual(summary.scores.essentials.earned, result.benchmark.checked_score) + self.assertEqual(summary.scores.essentials.max, result.benchmark.checked_max) + self.assertEqual( + summary.scores.agent_readiness.percent, + result.agent_readiness.score, + ) + self.assertEqual(summary.scores.agent_readiness.earned, result.agent_readiness.earned) + self.assertEqual(summary.scores.agent_readiness.max, result.agent_readiness.max) + self.assertEqual( + set(summary.benchmarks), + {"essentials", "agent_readiness"}, + ) + self.assertEqual( + summary.benchmarks["essentials"].snapshot, + result.benchmark.snapshot_date, + ) + self.assertEqual( + summary.benchmarks["essentials"].median_percent, + result.benchmark.median_score, + ) + self.assertEqual( + summary.benchmarks["essentials"].peer_count, + result.benchmark.benchmark_count, + ) + self.assertEqual( + summary.benchmarks["essentials"].percentile, + result.benchmark.percentile, + ) + self.assertEqual( + summary.benchmarks["agent_readiness"].snapshot, + result.agent_readiness.benchmark.snapshot_date, + ) + self.assertEqual(summary.limitations, SUMMARY_LIMITATION_CODES) + self.assertEqual( + summary.limitations, + ( + "relative_scores", + "no_live_ranking", + "no_provider_ip_auth", + "no_paid_crawlers", + ), + ) + + +class ScorePreservationTests(unittest.TestCase): + def test_score_pairs_preserve_source_numerics(self) -> None: + result = _build_result( + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + ) + summary = build_report_summary(result) + self.assertEqual( + summary.scores.overall.earned, + result.overall_score, + ) + self.assertEqual(summary.scores.overall.max, 100) + self.assertEqual( + summary.scores.pillars["off_site"].earned, + result.pillar_scores.off_site, + ) + self.assertEqual( + summary.scores.pillars["off_site"].max, + result.pillar_max.off_site, + ) + self.assertEqual( + summary.scores.pillars["scrapability"].earned, + result.pillar_scores.scrapability, + ) + self.assertEqual( + summary.scores.pillars["scrapability"].max, + result.pillar_max.scrapability, + ) + self.assertEqual( + summary.scores.pillars["seo"].earned, + result.pillar_scores.seo, + ) + self.assertEqual( + summary.scores.pillars["seo"].max, + result.pillar_max.seo, + ) + self.assertEqual( + summary.scores.essentials.percent, + result.benchmark.score, + ) + self.assertEqual( + summary.scores.agent_readiness.percent, + result.agent_readiness.score, + ) + # Full-scope strict-agent max is 21 (8+6+3+4). + self.assertEqual(summary.scores.agent_readiness.max, 21) + + +class AttentionSelectionTests(unittest.TestCase): + def _fail_check( + self, + check_name: str, + pillar: str, + *, + earned: int = 0, + max_score: int = 4, + ) -> CheckResult: + return _check( + check_name, + pillar, + state="fail", + earned=earned, + max_score=max_score, + ) + + def test_attention_capped_at_five_items(self) -> None: + checks = [ + self._fail_check("robots_txt", "scrapability", earned=0, max_score=6), + self._fail_check("bot_access", "scrapability", earned=0, max_score=6), + self._fail_check("html_structure", "scrapability", earned=0, max_score=4), + self._fail_check("schema_ld", "scrapability", earned=0, max_score=5), + self._fail_check("llms_txt", "scrapability", earned=0, max_score=5), + self._fail_check("ssr", "scrapability", earned=0, max_score=4), + self._fail_check("machine_surfaces", "scrapability", earned=0, max_score=3), + self._fail_check("pagespeed", "seo", earned=0, max_score=3), + self._fail_check("canonical", "seo", earned=0, max_score=5), + self._fail_check("indexing", "seo", earned=0, max_score=5), + self._fail_check("search_discovery", "seo", earned=0, max_score=4), + self._fail_check("social", "off_site", earned=0, max_score=2), + self._fail_check("wikipedia", "off_site", earned=0, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + self.assertEqual(len(summary.attention), 5) + self.assertEqual(summary.checks.attention_total, 5) + + def test_severity_order_fail_before_partial_before_warn(self) -> None: + checks = [ + _check("robots_txt", "scrapability", state="partial", earned=2, max_score=6), + _check("bot_access", "scrapability", state="fail", earned=0, max_score=6), + _check("html_structure", "scrapability", state="warn", earned=0, max_score=4), + _check("schema_ld", "scrapability", state="partial", earned=2, max_score=5), + _check("llms_txt", "scrapability", state="fail", earned=0, max_score=5), + _check("ssr", "scrapability", state="partial", earned=1, max_score=4), + _check("machine_surfaces", "scrapability", state="warn", earned=0, max_score=3), + _check("pagespeed", "seo", state="fail", earned=0, max_score=3), + _check("canonical", "seo", state="partial", earned=2, max_score=5), + _check("indexing", "seo", state="warn", earned=0, max_score=5), + _check("search_discovery", "seo", state="partial", earned=1, max_score=4), + _check("social", "off_site", state="warn", earned=0, max_score=2), + _check("wikipedia", "off_site", state="pass", earned=4, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + states = [item.state for item in summary.attention] + # The five-row cap is filled by the higher-severity fail and partial + # clusters before any warn row can enter the projection. + self.assertEqual(states, ["fail", "fail", "fail", "partial", "partial"]) + + def test_ratio_ordering_within_severity(self) -> None: + checks = [ + _check("robots_txt", "scrapability", state="fail", earned=5, max_score=6), + _check("bot_access", "scrapability", state="fail", earned=1, max_score=6), + _check("html_structure", "scrapability", state="fail", earned=3, max_score=4), + _check("schema_ld", "scrapability", state="pass", earned=5, max_score=5), + _check("llms_txt", "scrapability", state="pass", earned=5, max_score=5), + _check("ssr", "scrapability", state="pass", earned=4, max_score=4), + _check("machine_surfaces", "scrapability", state="pass", earned=3, max_score=3), + _check("pagespeed", "seo", state="pass", earned=3, max_score=3), + _check("canonical", "seo", state="pass", earned=5, max_score=5), + _check("indexing", "seo", state="pass", earned=5, max_score=5), + _check("search_discovery", "seo", state="pass", earned=4, max_score=4), + _check("social", "off_site", state="pass", earned=2, max_score=2), + _check("wikipedia", "off_site", state="pass", earned=4, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + names = [item.check_name for item in summary.attention] + self.assertEqual( + names, + ["bot_access", "html_structure", "robots_txt"], + ) + # Lower earned/max ratio must surface first. + self.assertEqual(summary.attention[0].earned, 1) + self.assertEqual(summary.attention[1].earned, 3) + self.assertEqual(summary.attention[2].earned, 5) + + def test_empty_attention_when_all_pass(self) -> None: + checks = [ + _check("robots_txt", "scrapability", state="pass", earned=6, max_score=6), + _check("bot_access", "scrapability", state="pass", earned=6, max_score=6), + _check("html_structure", "scrapability", state="pass", earned=4, max_score=4), + _check("schema_ld", "scrapability", state="pass", earned=5, max_score=5), + _check("llms_txt", "scrapability", state="pass", earned=5, max_score=5), + _check("ssr", "scrapability", state="pass", earned=4, max_score=4), + _check("machine_surfaces", "scrapability", state="pass", earned=3, max_score=3), + _check("pagespeed", "seo", state="pass", earned=3, max_score=3), + _check("canonical", "seo", state="pass", earned=5, max_score=5), + _check("indexing", "seo", state="pass", earned=5, max_score=5), + _check("search_discovery", "seo", state="pass", earned=4, max_score=4), + _check("social", "off_site", state="pass", earned=2, max_score=2), + _check("wikipedia", "off_site", state="pass", earned=4, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + self.assertEqual(summary.attention, []) + self.assertEqual(summary.checks.attention_total, 0) + self.assertEqual(summary.checks.fail, 0) + self.assertEqual(summary.checks.partial, 0) + self.assertEqual(summary.checks.warn, 0) + # ``pass`` is a reserved Python keyword; the model exposes the + # public field under ``pass_count`` while keeping the JSON key + # ``pass`` via Pydantic aliasing. + self.assertEqual(summary.checks.pass_count, 13) + self.assertEqual(summary.checks.locked, 9) + self.assertEqual(summary.checks.included, 13) + + +class PrivateFieldBoundaryTests(unittest.TestCase): + def test_forbidden_keys_absent_from_payload(self) -> None: + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + ) + summary = build_report_summary(result) + payload = summary.model_dump(mode="json") + + def _walk(node: object) -> None: + if isinstance(node, dict): + for key, child in node.items(): + self.assertNotIn( + key, + { + "finding", + "fix", + "label", + "entries", + "nearest", + "basis", + "caveat", + "passed", + "missing", + "not_checked", + "display_label", + "context", + "raw", + "rate_limit", + }, + f"forbidden key {key!r} leaked into summary payload", + ) + _walk(child) + elif isinstance(node, list): + for child in node: + _walk(child) + + _walk(payload) + # Top-level scope must be SummaryScope, not full AuditScope. + self.assertEqual( + set(summary.scope.model_dump(mode="json")), + {"preset", "protocols", "account_auth", "ecommerce", "overrides"}, + ) + # Attention rows must only contain the public summary keys. + if summary.attention: + allowed = { + "check_name", + "pillar", + "state", + "evidence_level", + "earned", + "max", + "effort", + } + self.assertEqual( + set(summary.attention[0].model_dump(mode="json")), + allowed, + ) + + +class LimitationCodesTests(unittest.TestCase): + def test_limitation_codes_fixed_order(self) -> None: + for include_protocols, include_account_auth, include_ecommerce in product( + (False, True), repeat=3 + ): + with self.subTest( + p=include_protocols, + a=include_account_auth, + c=include_ecommerce, + ): + result = _build_result( + include_protocols=include_protocols, + include_account_auth=include_account_auth, + include_ecommerce=include_ecommerce, + ) + summary = build_report_summary(result) + self.assertEqual( + summary.limitations, + ( + "relative_scores", + "no_live_ranking", + "no_provider_ip_auth", + "no_paid_crawlers", + ), + ) + + +class AgentPercentTests(unittest.TestCase): + def test_agent_percent_taken_from_result_score(self) -> None: + result = _build_result( + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + ) + # Replace the agent readiness summary with a custom percentage. + result.agent_readiness = _agent_readiness( + include_protocols=True, + include_account_auth=True, + include_ecommerce=True, + score=64, + earned=12, + ) + summary = build_report_summary(result) + self.assertEqual(summary.scores.agent_readiness.percent, 64) + self.assertEqual(summary.scores.agent_readiness.earned, 12) + self.assertEqual(summary.scores.agent_readiness.max, 21) + + +class ScopeVariantTests(unittest.TestCase): + def test_all_eight_scope_variants_produce_correct_max(self) -> None: + expected = { + (False, False, False): 8, + (True, False, False): 14, + (False, True, False): 11, + (False, False, True): 12, + (True, True, False): 17, + (True, False, True): 18, + (False, True, True): 15, + (True, True, True): 21, + } + for ( + include_protocols, + include_account_auth, + include_ecommerce, + ), strict_max in expected.items(): + with self.subTest( + p=include_protocols, + a=include_account_auth, + c=include_ecommerce, + ): + result = _build_result( + include_protocols=include_protocols, + include_account_auth=include_account_auth, + include_ecommerce=include_ecommerce, + ) + summary = build_report_summary(result) + self.assertEqual( + summary.scores.agent_readiness.max, + strict_max, + f"max mismatch for (p={include_protocols}, " + f"a={include_account_auth}, c={include_ecommerce})", + ) + # 13 groups, 56 checked points, 30/40/30 pillars must hold. + self.assertEqual(summary.checks.included, 13) + self.assertEqual(summary.checks.locked, 9) + self.assertEqual(summary.scores.essentials.max, 56) + self.assertEqual(summary.scores.pillars["off_site"].max, 30) + self.assertEqual(summary.scores.pillars["scrapability"].max, 40) + self.assertEqual(summary.scores.pillars["seo"].max, 30) + self.assertEqual(summary.scores.overall.max, 100) + + +class LockedRowsTests(unittest.TestCase): + def test_locked_rows_excluded_from_attention(self) -> None: + checks = [ + _check("robots_txt", "scrapability", state="fail", earned=0, max_score=6), + _check("bot_access", "scrapability", state="pass", earned=6, max_score=6), + _check("html_structure", "scrapability", state="pass", earned=4, max_score=4), + _check("schema_ld", "scrapability", state="pass", earned=5, max_score=5), + _check("llms_txt", "scrapability", state="pass", earned=5, max_score=5), + _check("ssr", "scrapability", state="pass", earned=4, max_score=4), + _check("machine_surfaces", "scrapability", state="pass", earned=3, max_score=3), + _check("pagespeed", "seo", state="pass", earned=3, max_score=3), + _check("canonical", "seo", state="pass", earned=5, max_score=5), + _check("indexing", "seo", state="pass", earned=5, max_score=5), + _check("search_discovery", "seo", state="pass", earned=4, max_score=4), + _check("social", "off_site", state="pass", earned=2, max_score=2), + _check("wikipedia", "off_site", state="pass", earned=4, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + # Only one row should be in attention: robots_txt is the lone fail. + self.assertEqual(len(summary.attention), 1) + self.assertEqual(summary.attention[0].check_name, "robots_txt") + # 9 locked rows must be counted separately and never appear in attention. + self.assertEqual(summary.checks.locked, 9) + self.assertEqual(summary.checks.included, 13) + self.assertNotIn("locked", [row.state for row in summary.attention]) + + +class TieBreakerTests(unittest.TestCase): + def test_same_state_same_ratio_breaks_tie_on_check_name(self) -> None: + checks = [ + _check("schema_ld", "scrapability", state="fail", earned=1, max_score=5), + _check("llms_txt", "scrapability", state="fail", earned=1, max_score=5), + _check("robots_txt", "scrapability", state="pass", earned=6, max_score=6), + _check("bot_access", "scrapability", state="pass", earned=6, max_score=6), + _check("html_structure", "scrapability", state="pass", earned=4, max_score=4), + _check("ssr", "scrapability", state="pass", earned=4, max_score=4), + _check("machine_surfaces", "scrapability", state="pass", earned=3, max_score=3), + _check("pagespeed", "seo", state="pass", earned=3, max_score=3), + _check("canonical", "seo", state="pass", earned=5, max_score=5), + _check("indexing", "seo", state="pass", earned=5, max_score=5), + _check("search_discovery", "seo", state="pass", earned=4, max_score=4), + _check("social", "off_site", state="pass", earned=2, max_score=2), + _check("wikipedia", "off_site", state="pass", earned=4, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + names = [row.check_name for row in summary.attention] + # Same state, same ratio; alphabetical order wins. + self.assertEqual(names, ["llms_txt", "schema_ld"]) + + def test_max_zero_rows_sort_first_within_severity(self) -> None: + checks = [ + _check("robots_txt", "scrapability", state="fail", earned=0, max_score=6), + _check("bot_access", "scrapability", state="fail", earned=0, max_score=6), + _check("html_structure", "scrapability", state="fail", earned=0, max_score=0), + _check("schema_ld", "scrapability", state="pass", earned=5, max_score=5), + _check("llms_txt", "scrapability", state="pass", earned=5, max_score=5), + _check("ssr", "scrapability", state="pass", earned=4, max_score=4), + _check("machine_surfaces", "scrapability", state="pass", earned=3, max_score=3), + _check("pagespeed", "seo", state="pass", earned=3, max_score=3), + _check("canonical", "seo", state="pass", earned=5, max_score=5), + _check("indexing", "seo", state="pass", earned=5, max_score=5), + _check("search_discovery", "seo", state="pass", earned=4, max_score=4), + _check("social", "off_site", state="pass", earned=2, max_score=2), + _check("wikipedia", "off_site", state="pass", earned=4, max_score=4), + ] + result = _build_result( + include_protocols=False, + include_account_auth=False, + include_ecommerce=False, + checks=checks, + ) + summary = build_report_summary(result) + # All three fail rows have ratio 0 (max=0 forces the floor). + # Stable tie-break is alphabetical on check_name. + names = [row.check_name for row in summary.attention] + self.assertEqual(names, ["bot_access", "html_structure", "robots_txt"]) + # The max=0 row is part of the attention set; the field reports 0 + # for ``max`` so an agent can detect the unsalvageable row. + self.assertEqual(summary.attention[1].max, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_runtime_integration.py b/backend/tests/test_runtime_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..12f3e66c8d61b83d6773f71d839f3bd67e1f4dff --- /dev/null +++ b/backend/tests/test_runtime_integration.py @@ -0,0 +1,303 @@ +import sys +import unittest +from dataclasses import replace +from pathlib import Path +from unittest.mock import AsyncMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.checks.extraction_readiness import ExtractionReadinessInput, analyse_extraction_readiness +from app.checks.llms_txt import check_llms_txt +from app.checks.schema_ld import check_schema_ld +from app.checks.search_blurb import SearchBlurbAnalysis +from app.checks.search_discovery import ( + FeedFreshnessResult, + SamplePageMetadataResult, + TrustSurfaceResult, + check_search_discovery, +) +from app.checks.ssr import check_ssr +from app.fetch_evidence import collect_fetch_evidence +from app.rubric import ESSENTIALS_CHECKED_MAX, ESSENTIALS_CHECK_GROUP_COUNT +from backend.tests.fixtures import make_audit_context, make_fetch_result + + +def _page(title: str, path: str) -> str: + description = ( + f"{title} explains reliable machine-readable website content with clear " + "metadata, structured facts, and accessible source text for public crawlers." + ) + words = " ".join( + f"reliable machine readable website content metadata structured facts accessible source crawler {index}" + for index in range(12) + ) + return f""" + + {title} + + + + + +

{title}

{words}

+ """ + + +class RuntimeIntegrationTests(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + sitemap = """ + + https://example.com2026-07-17 + https://example.com/about2026-07-17 + + """ + self.context = make_audit_context( + homepage_html=_page("Machine-readable homepage", ""), + robots_text=( + "User-agent: *\nAllow: /\nSitemap: https://example.com/sitemap.xml" + ), + sitemap_text=sitemap, + ) + self.calls: list[tuple[str, str]] = [] + + async def _fetch(self, url: str, **kwargs): + self.calls.append((url, kwargs.get("accept", ""))) + if url == "https://example.com/alternate-index.xml": + return make_fetch_result( + url, + """ + + https://example.com/child-sitemap.xml + https://example.com/child-sitemap.xml + + """, + headers={"content-type": "application/xml"}, + ) + if url == "https://example.com/child-sitemap.xml": + return make_fetch_result( + url, + """ + + https://example.com/about2026-07-17 + + """, + headers={"content-type": "application/xml"}, + ) + if url == "https://example.com/llms.txt": + return make_fetch_result( + url, + "# Example\n\nMachine-readable documentation: https://example.com/about", + headers={"content-type": "text/plain"}, + ) + if url == "https://example.com/about": + return make_fetch_result( + url, + _page("About Machine-readable Example", "/about"), + headers={"content-type": "text/html"}, + ) + markdown = "# Machine-readable content\n\n" + " ".join( + "reliable machine readable website content metadata structured facts accessible source crawler" + for _ in range(8) + ) + return make_fetch_result( + url, + markdown, + headers={"content-type": "text/markdown", "vary": "Accept"}, + ) + + async def _bundle(self, include_ecommerce: bool = False): + with ( + patch("app.fetch_evidence.fetch_url", new=self._fetch), + patch("app.checks.sitemap_analysis.fetch_url", new=self._fetch), + ): + return await collect_fetch_evidence(self.context, include_ecommerce) + + async def test_bundle_reuses_root_sitemap_homepage_and_sample_fetches(self) -> None: + bundle = await self._bundle() + + requested_urls = [url for url, _ in self.calls] + self.assertEqual(requested_urls.count("https://example.com/sitemap.xml"), 0) + self.assertEqual(requested_urls.count("https://example.com"), 1) + self.assertEqual(requested_urls.count("https://example.com/about"), 1) + self.assertEqual(requested_urls.count("https://example.com/about/index.md"), 1) + self.assertEqual(requested_urls.count("https://example.com/llms.txt"), 1) + self.assertEqual(len(bundle.search_blurb.pages), 2) + self.assertEqual(len(bundle.sample_page_responses), 2) + + async def test_fetches_each_alternate_and_child_sitemap_once(self) -> None: + self.context = make_audit_context( + homepage_html=_page("Machine-readable homepage", ""), + robots_text=( + "User-agent: *\nAllow: /\n" + "Sitemap: https://example.com/sitemap.xml\n" + "Sitemap: https://example.com/alternate-index.xml\n" + "Sitemap: https://example.com/alternate-index.xml" + ), + sitemap_text=self.context.sitemap.text, + ) + + bundle = await self._bundle() + + requested_urls = [url for url, _ in self.calls] + self.assertEqual(requested_urls.count("https://example.com/alternate-index.xml"), 1) + self.assertEqual(requested_urls.count("https://example.com/child-sitemap.xml"), 1) + self.assertTrue(bundle.sitemap_sample.is_index) + self.assertEqual(bundle.sitemap_sample.sitemap_count, 3) + + async def test_reuses_homepage_markdown_by_redirect_final_url(self) -> None: + redirected_url = "https://example.com/home" + candidate_url = f"{redirected_url}/index.md" + sitemap = ( + "https://example.com/home" + "2026-07-17" + ) + self.context = make_audit_context( + homepage_html=_page("Machine-readable homepage", "/home"), + homepage_final_url=redirected_url, + sitemap_text=sitemap, + ) + markdown = "# Machine-readable content\n\n" + " ".join( + "reliable machine readable website content metadata structured facts accessible source crawler" + for _ in range(8) + ) + + async def redirect_fetch(url: str, **kwargs): + self.calls.append((url, kwargs.get("accept", ""))) + if url == "https://example.com": + return make_fetch_result( + url, + markdown, + final_url=redirected_url, + headers={"content-type": "text/markdown", "vary": "Accept"}, + ) + if url == "https://example.com/llms.txt": + return make_fetch_result( + url, + "# Example\n\nMachine-readable documentation: https://example.com/home", + headers={"content-type": "text/plain"}, + ) + self.fail(f"unexpected fetch: {url}") + + with ( + patch("app.fetch_evidence.fetch_url", new=redirect_fetch), + patch("app.checks.sitemap_analysis.fetch_url", new=redirect_fetch), + ): + bundle = await collect_fetch_evidence(self.context) + + requested_urls = [url for url, _ in self.calls] + self.assertNotIn(candidate_url, requested_urls) + self.assertEqual(len(bundle.sample_markdown_by_page), 1) + page_url, response = bundle.sample_markdown_by_page[0] + self.assertEqual(page_url, redirected_url) + self.assertEqual(response.final_url, redirected_url) + + async def test_good_bundle_preserves_authoritative_row_scores(self) -> None: + bundle = await self._bundle() + freshness = FeedFreshnessResult(True, ["recent update surface"], [], []) + trust = TrustSurfaceResult( + found={"about": ["sitemap"], "contact": ["homepage"], "privacy": ["homepage"]}, + positives=["core trust surfaces are discoverable"], + issues=[], + caveats=[], + ) + with ( + patch( + "app.checks.search_discovery._freshness_surface", + new=AsyncMock(return_value=freshness), + ), + patch("app.checks.search_discovery._trust_surface_discovery", return_value=trust), + ): + search = await check_search_discovery(self.context, False, bundle) + + llms = await check_llms_txt(self.context, bundle) + schema = await check_schema_ld(self.context, False, bundle) + ssr = await check_ssr(self.context, bundle) + + self.assertEqual((search.state, search.score), ("pass", 4)) + self.assertEqual((llms.state, llms.score), ("pass", 5)) + self.assertEqual((schema.state, schema.score), ("pass", 5)) + self.assertEqual((ssr.state, ssr.score), ("pass", 4)) + self.assertIn("no Firecrawl or other extraction-provider API was called", llms.finding) + + async def test_blurb_issue_only_caps_existing_sampled_metadata_point(self) -> None: + bundle = await self._bundle() + degraded = replace( + bundle, + search_blurb=SearchBlurbAnalysis( + pages=bundle.search_blurb.pages, + positives=(), + issues=("2 sampled page(s) reuse a normalized title across 1 duplicate group(s).",), + caveats=(), + ), + ) + freshness = FeedFreshnessResult(True, ["recent update surface"], [], []) + trust = TrustSurfaceResult({}, [], [], []) + with ( + patch( + "app.checks.search_discovery._freshness_surface", + new=AsyncMock(return_value=freshness), + ), + patch("app.checks.search_discovery._trust_surface_discovery", return_value=trust), + ): + result = await check_search_discovery(self.context, False, degraded) + + self.assertEqual((result.state, result.score), ("partial", 3)) + self.assertIn("search-blurb proxy", result.finding) + self.assertIn("actual DuckDuckGo and Bing snippet display was not verified", result.finding) + + already_degraded = SamplePageMetadataResult( + False, [], ["sampled metadata is incomplete"], [] + ) + with ( + patch( + "app.checks.search_discovery._freshness_surface", + new=AsyncMock(return_value=freshness), + ), + patch("app.checks.search_discovery._trust_surface_discovery", return_value=trust), + patch( + "app.checks.search_discovery._sample_pages_have_discovery_metadata", + new=AsyncMock(return_value=already_degraded), + ), + ): + result = await check_search_discovery(self.context, False, degraded) + self.assertEqual(result.score, 3) + + async def test_hidden_app_shell_caps_only_an_otherwise_passing_ssr_row(self) -> None: + bundle = await self._bundle() + hidden_words = " ".join(f"important content {index}" for index in range(100)) + html = ( + '

Hidden

' + + hidden_words + + '

' + + "".join(f'' for index in range(4)) + + "" + ) + hidden_context = make_audit_context(homepage_html=html) + extraction = analyse_extraction_readiness( + ExtractionReadinessInput(url="https://example.com", raw_html=html) + ) + result = await check_ssr( + hidden_context, + replace(bundle, extraction_readiness=extraction), + ) + + self.assertEqual((result.state, result.score), ("partial", 3)) + self.assertIn("hidden source node", result.finding) + + async def test_scope_off_excludes_commerce_coherence_and_contract_is_fixed(self) -> None: + bundle = await self._bundle(include_ecommerce=False) + schema = await check_schema_ld(self.context, False, bundle) + + self.assertEqual(bundle.extraction_readiness.commerce_missing_fields, ()) + self.assertEqual(bundle.extraction_readiness.commerce_schema_visible_mismatches, ()) + self.assertNotIn("Visible product content", schema.finding) + self.assertEqual(ESSENTIALS_CHECK_GROUP_COUNT, 13) + self.assertEqual(ESSENTIALS_CHECKED_MAX, 56) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_search_blurb.py b/backend/tests/test_search_blurb.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2c424d7887fa9c55fbef554e0aa048f5a9c4cc --- /dev/null +++ b/backend/tests/test_search_blurb.py @@ -0,0 +1,221 @@ +import sys +import unittest +from dataclasses import FrozenInstanceError +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.checks.search_blurb import BlurbPageInput, analyse_search_blurbs, extract_page_blurb + + +def _html( + description: str, + *, + canonical: str = "/guide", + social: str | None = None, + title: str = "Trail running shoe guide", + visible_suffix: str = "", +) -> str: + social_tags = "" if social is None else ( + f'' + f'' + ) + return f""" + {title} + + {social_tags} +
+

How to choose trail running shoes

+

Learn how grip, cushioning, fit, terrain, and weather affect your choice of trail running shoes.

+

This practical guide compares durable footwear for rocky and muddy routes. {visible_suffix}

+
+ """ + + +class SearchBlurbTests(unittest.TestCase): + def test_extracts_owned_signals_and_cleans_main_text(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + signals = extract_page_blurb(BlurbPageInput("https://example.com/start", _html(description))) + + self.assertEqual(signals.title, "Trail running shoe guide") + self.assertEqual(signals.h1, "How to choose trail running shoes") + self.assertEqual(signals.meta_description, description) + self.assertEqual(signals.canonical_url, "https://example.com/guide") + self.assertNotIn("Cookie settings", signals.main_text) + self.assertNotIn("All rights reserved", signals.main_text) + with self.assertRaises(FrozenInstanceError): + signals.title = "changed" # type: ignore[misc] + + def test_reports_complete_coherent_metadata_and_required_caveat(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + result = analyse_search_blurbs( + [BlurbPageInput("https://example.com/guide", _html(description, social=description))] + ) + + self.assertFalse(result.issues) + self.assertTrue(any("align with visible page content" in item for item in result.positives)) + self.assertTrue(any("Open Graph/Twitter" in item for item in result.positives)) + self.assertIn("actual DuckDuckGo or Bing snippet selection and display were not verified", result.caveats[0]) + + def test_reports_missing_fields_and_keeps_canonical_absent(self) -> None: + result = analyse_search_blurbs([BlurbPageInput("https://example.com", "")]) + + self.assertIsNone(result.pages[0].canonical_url) + self.assertTrue(any("missing title" in item for item in result.issues)) + self.assertTrue(any("missing meta description" in item for item in result.issues)) + self.assertTrue(any("missing H1" in item for item in result.issues)) + self.assertTrue(any("missing extractable main text" in item for item in result.issues)) + self.assertTrue(any("missing canonical URL" in item for item in result.issues)) + + def test_flags_conservative_length_bounds(self) -> None: + pages = [ + BlurbPageInput("https://example.com/short", _html("Too short.")), + BlurbPageInput("https://example.com/long", _html("Useful trail running details " * 12)), + ] + result = analyse_search_blurbs(pages) + + self.assertTrue(any("shorter than 50" in item for item in result.issues)) + self.assertTrue(any("longer than 200" in item for item in result.issues)) + + def test_flags_normalized_duplicates_across_pages(self) -> None: + first = "Choose durable trail shoes for rocky routes, wet weather, and comfortable long-distance running." + second = " CHOOSE durable trail shoes for rocky routes wet weather and comfortable long distance running!!! " + result = analyse_search_blurbs([ + BlurbPageInput("https://example.com/a", _html(first, canonical="/a")), + BlurbPageInput("https://example.com/b", _html(second, canonical="/b")), + ]) + + self.assertTrue(any("2 sampled page(s) reuse a normalized meta description" in item for item in result.issues)) + + def test_flags_normalized_duplicate_titles_across_pages(self) -> None: + description_a = "Choose durable trail shoes for rocky routes, wet weather, and comfortable running." + description_b = "Compare trail footwear cushioning, grip, fit, and protection for long routes." + result = analyse_search_blurbs([ + BlurbPageInput( + "https://example.com/a", + _html(description_a, canonical="/a", title="Trail-running Shoe Guide!"), + ), + BlurbPageInput( + "https://example.com/b", + _html(description_b, canonical="/b", title=" trail running shoe guide "), + ), + ]) + + self.assertTrue(any("2 sampled page(s) reuse a normalized title" in item for item in result.issues)) + + def test_flags_page_owned_stale_year_conflict_without_live_claim(self) -> None: + description = "Read the 2024 trail running shoe guide for grip, cushioning, fit, and terrain advice." + result = analyse_search_blurbs([ + BlurbPageInput( + "https://example.com/guide", + _html(description, canonical="/guide", visible_suffix="Updated for 2026."), + ) + ]) + + self.assertTrue(any("older year in page-owned description metadata" in item for item in result.issues)) + self.assertFalse(any("snippet is stale" in item.casefold() for item in result.issues)) + + def test_does_not_flag_year_without_newer_visible_year(self) -> None: + description = "Read the 2024 trail running shoe guide for grip, cushioning, fit, and terrain advice." + result = analyse_search_blurbs([ + BlurbPageInput("https://example.com/guide", _html(description, canonical="/guide")) + ]) + + self.assertFalse(any("older year" in item for item in result.issues)) + + def test_flags_off_host_and_different_canonical_targets(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + result = analyse_search_blurbs([ + BlurbPageInput("https://example.com/a", _html(description, canonical="https://other.test/a")), + BlurbPageInput("https://example.com/b", _html(description, canonical="/other")), + ]) + + self.assertTrue(any("off-host canonical" in item for item in result.issues)) + self.assertTrue(any("canonicalize to a different same-host URL" in item for item in result.issues)) + + def test_flags_shared_canonical_collision_but_accepts_normalized_self_canonicals(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + collisions = analyse_search_blurbs([ + BlurbPageInput("https://example.com/a", _html(description, canonical="/shared")), + BlurbPageInput("https://example.com/b", _html(description, canonical="/shared")), + ]) + self.assertTrue(any("share a canonical target" in item for item in collisions.issues)) + + self_canonical = analyse_search_blurbs([ + BlurbPageInput( + "https://EXAMPLE.com:443/guide/?source=test#top", + _html(description, canonical="https://example.com/guide"), + ) + ]) + self.assertFalse(any("canonicalize" in item for item in self_canonical.issues)) + self.assertTrue(any("normalized self-canonicals" in item for item in self_canonical.positives)) + + def test_malformed_canonical_is_reported_without_crashing(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + result = analyse_search_blurbs([ + BlurbPageInput( + "https://example.com/guide", + _html(description, canonical="https://example.com:bad/path"), + ), + BlurbPageInput( + "https://example.com/other", + _html(description, canonical="https://[broken/path"), + ), + ]) + + self.assertTrue(any("2 sampled page(s) publish a malformed canonical URL" in item for item in result.issues)) + self.assertFalse(any("normalized self-canonicals" in item for item in result.positives)) + + def test_missing_social_descriptions_are_optional_caveats(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + result = analyse_search_blurbs([ + BlurbPageInput("https://example.com/guide", _html(description, canonical="/guide")) + ]) + + self.assertTrue(any("optional Open Graph description" in item for item in result.caveats)) + self.assertTrue(any("optional Twitter description" in item for item in result.caveats)) + self.assertFalse(any("Open Graph" in item for item in result.issues)) + + def test_flags_placeholder_and_boilerplate_descriptions(self) -> None: + result = analyse_search_blurbs([ + BlurbPageInput( + "https://example.com/a", + _html("Lorem ipsum description goes here for this future page and its unfinished content."), + ), + BlurbPageInput( + "https://example.com/b", + _html("We use cookies. Privacy policy and terms of service. All rights reserved on this site."), + ), + ]) + + self.assertTrue( + any("2 sampled meta description(s) look like placeholder or boilerplate" in item for item in result.issues) + ) + + def test_flags_low_overlap_only_when_token_guards_are_met(self) -> None: + unrelated = ( + "Explore astronomy telescopes, distant galaxies, planetary imaging, " + "and observatory equipment tonight." + ) + guarded_short = "Astronomy telescope guide" + result = analyse_search_blurbs([ + BlurbPageInput("https://example.com/unrelated", _html(unrelated, canonical="/unrelated")), + BlurbPageInput("https://example.com/short", _html(guarded_short, canonical="/short")), + ]) + + self.assertTrue(any("1 sampled meta description(s) have low token overlap" in item for item in result.issues)) + + def test_flags_material_social_description_mismatch(self) -> None: + description = "Learn how grip, cushioning, fit, and terrain shape your choice of trail running shoes." + unrelated = "Astronomy telescopes reveal galaxies, planets, nebulae, observatories, and night skies." + result = analyse_search_blurbs([ + BlurbPageInput("https://example.com/guide", _html(description, social=unrelated)) + ]) + + self.assertTrue( + any("2 Open Graph/Twitter description(s) materially mismatch" in item for item in result.issues) + ) + + +if __name__ == "__main__": + unittest.main()