georgejieh commited on
Commit
7d7841f
·
unverified ·
0 Parent(s):

MachineRead Essentials backend for HF Space

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +35 -0
  2. .gitignore +3 -0
  3. DockerFile +6 -0
  4. README.md +11 -0
  5. backend/.cache/entity_lookup.sqlite3 +0 -0
  6. backend/app/__init__.py +0 -0
  7. backend/app/agent_readiness.py +497 -0
  8. backend/app/audit_context.py +21 -0
  9. backend/app/benchmarks.py +860 -0
  10. backend/app/checks/__init__.py +0 -0
  11. backend/app/checks/__pycache__/__init__.cpython-311.pyc +0 -0
  12. backend/app/checks/__pycache__/__init__.cpython-312.pyc +0 -0
  13. backend/app/checks/__pycache__/ard_catalog.cpython-311.pyc +0 -0
  14. backend/app/checks/__pycache__/ard_catalog.cpython-312.pyc +0 -0
  15. backend/app/checks/__pycache__/bot_access.cpython-311.pyc +0 -0
  16. backend/app/checks/__pycache__/bot_access.cpython-312.pyc +0 -0
  17. backend/app/checks/__pycache__/canonical.cpython-311.pyc +0 -0
  18. backend/app/checks/__pycache__/canonical.cpython-312.pyc +0 -0
  19. backend/app/checks/__pycache__/extraction_readiness.cpython-311.pyc +0 -0
  20. backend/app/checks/__pycache__/extraction_readiness.cpython-312.pyc +0 -0
  21. backend/app/checks/__pycache__/html_structure.cpython-311.pyc +0 -0
  22. backend/app/checks/__pycache__/html_structure.cpython-312.pyc +0 -0
  23. backend/app/checks/__pycache__/indexing.cpython-311.pyc +0 -0
  24. backend/app/checks/__pycache__/indexing.cpython-312.pyc +0 -0
  25. backend/app/checks/__pycache__/llms_txt.cpython-311.pyc +0 -0
  26. backend/app/checks/__pycache__/llms_txt.cpython-312.pyc +0 -0
  27. backend/app/checks/__pycache__/locked.cpython-311.pyc +0 -0
  28. backend/app/checks/__pycache__/locked.cpython-312.pyc +0 -0
  29. backend/app/checks/__pycache__/machine_surfaces.cpython-311.pyc +0 -0
  30. backend/app/checks/__pycache__/machine_surfaces.cpython-312.pyc +0 -0
  31. backend/app/checks/__pycache__/pagespeed.cpython-311.pyc +0 -0
  32. backend/app/checks/__pycache__/pagespeed.cpython-312.pyc +0 -0
  33. backend/app/checks/__pycache__/robots.cpython-311.pyc +0 -0
  34. backend/app/checks/__pycache__/robots.cpython-312.pyc +0 -0
  35. backend/app/checks/__pycache__/schema_ld.cpython-311.pyc +0 -0
  36. backend/app/checks/__pycache__/schema_ld.cpython-312.pyc +0 -0
  37. backend/app/checks/__pycache__/search_blurb.cpython-311.pyc +0 -0
  38. backend/app/checks/__pycache__/search_blurb.cpython-312.pyc +0 -0
  39. backend/app/checks/__pycache__/search_discovery.cpython-311.pyc +0 -0
  40. backend/app/checks/__pycache__/search_discovery.cpython-312.pyc +0 -0
  41. backend/app/checks/__pycache__/sitemap_analysis.cpython-311.pyc +0 -0
  42. backend/app/checks/__pycache__/sitemap_analysis.cpython-312.pyc +0 -0
  43. backend/app/checks/__pycache__/social.cpython-311.pyc +0 -0
  44. backend/app/checks/__pycache__/social.cpython-312.pyc +0 -0
  45. backend/app/checks/__pycache__/ssr.cpython-311.pyc +0 -0
  46. backend/app/checks/__pycache__/ssr.cpython-312.pyc +0 -0
  47. backend/app/checks/__pycache__/wikipedia.cpython-311.pyc +0 -0
  48. backend/app/checks/__pycache__/wikipedia.cpython-312.pyc +0 -0
  49. backend/app/checks/ard_catalog.py +204 -0
  50. backend/app/checks/bot_access.py +397 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
DockerFile ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+ WORKDIR /app
3
+ COPY backend/ ./backend/
4
+ RUN pip install --no-cache-dir -r backend/requirements.txt
5
+ EXPOSE 7860
6
+ CMD ["python", "-m", "uvicorn", "app.main:app", "--app-dir", "backend", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: MachineRead - Preview
3
+ emoji: 🔍
4
+ colorFrom: green
5
+ colorTo: gray
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: mit
10
+ short_description: Free Features Preview of MachineRead Project
11
+ ---
backend/.cache/entity_lookup.sqlite3 ADDED
Binary file (20.5 kB). View file
 
backend/app/__init__.py ADDED
File without changes
backend/app/agent_readiness.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ from dataclasses import dataclass
4
+ from urllib.parse import urlparse
5
+
6
+ from app.audit_context import AuditContext
7
+ from app.benchmarks import build_agent_benchmark_comparison
8
+ from app.checks.llms_txt import agent_text_access, best_sitemap
9
+ from app.checks.robots import content_signal_tokens, explicit_ai_bot_count
10
+ from app.fetching import FetchResult, fetch_url, make_root_url
11
+ from app.models import AgentReadinessCategory, AgentReadinessSummary
12
+
13
+ _LINK_HEADER_TOKENS = (
14
+ "api-catalog",
15
+ "oauth-authorization-server",
16
+ "oauth-protected-resource",
17
+ "mcp",
18
+ "agent",
19
+ "webmcp",
20
+ "auth.md",
21
+ )
22
+
23
+ _JSON_SURFACES: tuple[tuple[str, tuple[str, ...], str, str, str, tuple[str, ...]], ...] = (
24
+ (
25
+ "Web Bot Auth directory",
26
+ ("/.well-known/http-message-signatures-directory",),
27
+ "application/json, */*;q=0.5",
28
+ "Bot Access Control",
29
+ "core",
30
+ ("keys",),
31
+ ),
32
+ (
33
+ "API Catalog",
34
+ ("/.well-known/api-catalog", "/.well-known/api-catalog.json", "/api-catalog.json"),
35
+ "application/linkset+json, application/json, */*;q=0.5",
36
+ "Protocol Discovery",
37
+ "protocols",
38
+ ("linkset", "api-catalog"),
39
+ ),
40
+ (
41
+ "OAuth/OIDC discovery metadata",
42
+ (
43
+ "/.well-known/oauth-authorization-server",
44
+ "/.well-known/openid-configuration",
45
+ ),
46
+ "application/json, */*;q=0.5",
47
+ "Protocol Discovery",
48
+ "account_auth",
49
+ ("issuer",),
50
+ ),
51
+ (
52
+ "OAuth Protected Resource metadata",
53
+ ("/.well-known/oauth-protected-resource",),
54
+ "application/json, */*;q=0.5",
55
+ "Protocol Discovery",
56
+ "account_auth",
57
+ ("resource", "authorization_servers"),
58
+ ),
59
+ (
60
+ "MCP Server Card",
61
+ (
62
+ "/.well-known/mcp/server-card.json",
63
+ "/.well-known/mcp.json",
64
+ "/.well-known/mcp/server-cards.json",
65
+ ),
66
+ "application/json, */*;q=0.5",
67
+ "Protocol Discovery",
68
+ "protocols",
69
+ ("name",),
70
+ ),
71
+ (
72
+ "A2A Agent Card",
73
+ (
74
+ "/.well-known/agent-card.json",
75
+ "/.well-known/a2a-agent.json",
76
+ "/.well-known/agent.json",
77
+ ),
78
+ "application/json, */*;q=0.5",
79
+ "Protocol Discovery",
80
+ "protocols",
81
+ ("name",),
82
+ ),
83
+ (
84
+ "Agent Skills index",
85
+ (
86
+ "/.well-known/agent-skills/index.json",
87
+ "/.well-known/skills/index.json",
88
+ "/.well-known/agent-skills.json",
89
+ ),
90
+ "application/json, */*;q=0.5",
91
+ "Protocol Discovery",
92
+ "protocols",
93
+ ("skills",),
94
+ ),
95
+ (
96
+ "WebMCP manifest",
97
+ ("/.well-known/webmcp.json", "/.well-known/webmcp"),
98
+ "application/json, */*;q=0.5",
99
+ "Protocol Discovery",
100
+ "protocols",
101
+ ("name", "tools"),
102
+ ),
103
+ (
104
+ "ARD static catalog",
105
+ ("/.well-known/ai-catalog.json",),
106
+ "application/json, */*;q=0.5",
107
+ "Protocol Discovery",
108
+ "protocols",
109
+ ("specVersion", "entries"),
110
+ ),
111
+ (
112
+ "x402 payment metadata",
113
+ ("/.well-known/x402", "/.well-known/x402.json"),
114
+ "application/json, */*;q=0.5",
115
+ "Commerce",
116
+ "commerce",
117
+ ("accepts", "resource"),
118
+ ),
119
+ (
120
+ "MPP commerce metadata",
121
+ ("/.well-known/mpp.json",),
122
+ "application/json, */*;q=0.5",
123
+ "Commerce",
124
+ "commerce",
125
+ ("version", "manifest"),
126
+ ),
127
+ (
128
+ "UCP commerce metadata",
129
+ ("/.well-known/ucp.json",),
130
+ "application/json, */*;q=0.5",
131
+ "Commerce",
132
+ "commerce",
133
+ ("version", "manifest"),
134
+ ),
135
+ (
136
+ "ACP commerce metadata",
137
+ ("/.well-known/acp.json",),
138
+ "application/json, */*;q=0.5",
139
+ "Commerce",
140
+ "commerce",
141
+ ("version", "manifest"),
142
+ ),
143
+ )
144
+
145
+ # Top-level keys that, taken alone, indicate a soft-404 / generic error
146
+ # response rather than a real discovery document. Bodies whose only
147
+ # top-level keys come from this set are rejected by ``_looks_like_json``
148
+ # to prevent SPA/CDN error pages from passing protocol probes.
149
+ _ERROR_ONLY_KEYS: frozenset[str] = frozenset({"error", "message", "status", "code"})
150
+
151
+ _AUTH_MD_PATHS = ("/auth.md", "/.well-known/auth.md")
152
+ _DNS_PREFIXES = ("_index._agents", "_a2a._agents", "_mcp._agents")
153
+ _DNS_TYPES = ("SVCB", "HTTPS", "TXT")
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class ProbeResult:
158
+ label: str
159
+ category: str
160
+ passed: bool
161
+ included: bool = True
162
+
163
+
164
+ def _looks_like_json(
165
+ response: FetchResult,
166
+ require_keys: list[str] | tuple[str, ...] | None = None,
167
+ ) -> bool:
168
+ """Decide whether ``response`` looks like a real JSON discovery document.
169
+
170
+ Beyond the basic content-type + parseable-JSON gate, two shape checks
171
+ protect against soft-404 bodies:
172
+
173
+ 1. **Error-only rejection** — if the parsed body is a dict whose
174
+ top-level keys are all members of ``_ERROR_ONLY_KEYS`` (e.g.
175
+ ``{"error": "not found"}``), the body is treated as a generic error
176
+ envelope rather than a discovery document.
177
+ 2. **Surface-specific required keys** — when ``require_keys`` is
178
+ supplied, the dict must contain at least one of those keys to be
179
+ considered a valid document for the probed surface (e.g. an MCP
180
+ card must have ``name``, OAuth metadata must have ``issuer``).
181
+ JSON arrays and scalars are rejected when ``require_keys`` is set.
182
+ """
183
+ content_type = response.headers.get("content-type", "").lower()
184
+ if "json" not in content_type and "linkset" not in content_type:
185
+ return False
186
+ try:
187
+ parsed = json.loads(response.text)
188
+ except json.JSONDecodeError:
189
+ return False
190
+ if not isinstance(parsed, (dict, list)):
191
+ return False
192
+ if isinstance(parsed, list):
193
+ # Lists cannot satisfy dict-shape requirements; only return True
194
+ # when no shape validation was requested.
195
+ return require_keys is None
196
+ # Error-only rejection: every top-level key is a generic error field.
197
+ if parsed and set(parsed).issubset(_ERROR_ONLY_KEYS):
198
+ return False
199
+ if require_keys:
200
+ return any(key in parsed for key in require_keys)
201
+ return True
202
+
203
+
204
+ def _looks_like_auth_md(response: FetchResult) -> bool:
205
+ sample = response.text.strip()[:3000].lower()
206
+ if len(sample) < 20:
207
+ return False
208
+ return response.text.lstrip().startswith("#") or ("auth" in sample and "agent" in sample)
209
+
210
+
211
+ def _has_agent_link_header(context: AuditContext) -> bool:
212
+ if not context.homepage.ok:
213
+ return False
214
+ link_header = context.homepage.headers.get("link", "").lower()
215
+ return any(token in link_header for token in _LINK_HEADER_TOKENS)
216
+
217
+
218
+ def _dns_candidates(context: AuditContext) -> list[str]:
219
+ hostname = urlparse(context.url).hostname
220
+ if not hostname:
221
+ return []
222
+
223
+ roots = []
224
+ for root in (hostname, hostname.removeprefix("www.")):
225
+ if root not in roots:
226
+ roots.append(root)
227
+
228
+ return [
229
+ f"{prefix}.{root}"
230
+ for root in roots
231
+ for prefix in _DNS_PREFIXES
232
+ ]
233
+
234
+
235
+ # RCODE values from dnspython that indicate the name does not exist.
236
+ # NXDOMAIN (3) means "no such name" — we can stop probing other record
237
+ # types and other prefixes for the same base name. Empty domain (5)
238
+ # similarly indicates an unreachable name and short-circuits cleanly.
239
+ _NXDOMAIN_RCODES = {3, 5}
240
+
241
+
242
+ async def _has_dns_aid(context: AuditContext) -> bool:
243
+ try:
244
+ import dns.asyncresolver
245
+ import dns.exception
246
+ except ImportError:
247
+ return False
248
+
249
+ resolver = dns.asyncresolver.Resolver()
250
+ resolver.lifetime = 2
251
+ resolver.timeout = 2
252
+
253
+ for candidate in _dns_candidates(context):
254
+ base_name = candidate.split(".", 1)[1] if "." in candidate else candidate
255
+ for record_type in _DNS_TYPES:
256
+ try:
257
+ answers = await resolver.resolve(candidate, record_type)
258
+ except dns.resolver.NoNameservers:
259
+ # No working nameserver — treat as inconclusive, keep going.
260
+ continue
261
+ except dns.exception.Timeout:
262
+ continue
263
+ except dns.resolver.NXDOMAIN as exc:
264
+ # NXDOMAIN on the base name → skip remaining record types
265
+ # and prefixes rooted at the same name. Sub-prefix lookups
266
+ # under an NXDOMAIN apex are guaranteed to fail.
267
+ if base_name == candidate.split(".", 1)[1] and exc.rcode() in _NXDOMAIN_RCODES:
268
+ break
269
+ continue
270
+ except dns.resolver.NoAnswer:
271
+ # Name exists but no records of this type — try next type.
272
+ continue
273
+ except Exception:
274
+ continue
275
+ if answers:
276
+ return True
277
+ return False
278
+
279
+
280
+ async def _json_surface_available(
281
+ context: AuditContext,
282
+ paths: tuple[str, ...],
283
+ accept: str,
284
+ require_keys: tuple[str, ...] | None = None,
285
+ ) -> bool:
286
+ responses = await asyncio.gather(
287
+ *[fetch_url(make_root_url(context.url, path), accept=accept) for path in paths]
288
+ )
289
+ return any(
290
+ response.ok and _looks_like_json(response, require_keys)
291
+ for response in responses
292
+ )
293
+
294
+
295
+ async def _auth_md_available(context: AuditContext) -> bool:
296
+ responses = await asyncio.gather(
297
+ *[
298
+ fetch_url(make_root_url(context.url, path), accept="text/markdown, text/plain, */*;q=0.5")
299
+ for path in _AUTH_MD_PATHS
300
+ ]
301
+ )
302
+ return any(response.ok and _looks_like_auth_md(response) for response in responses)
303
+
304
+
305
+ def _scope_included(scope: str, include_protocols: bool, include_account_auth: bool, include_ecommerce: bool) -> bool:
306
+ if scope == "core":
307
+ return True
308
+ if scope == "protocols":
309
+ return include_protocols
310
+ if scope == "account_auth":
311
+ return include_account_auth
312
+ if scope == "commerce":
313
+ return include_ecommerce
314
+ return False
315
+
316
+
317
+ # Core probes that are always part of the default-scope strict-agent lens
318
+ # and do not depend on any optional scope flag. These 7 names mirror the
319
+ # unconditional ``ProbeResult(...)`` entries constructed in
320
+ # ``build_agent_readiness_summary``. ``auth.md`` is added separately below
321
+ # because it is gated by ``include_account_auth`` via
322
+ # ``ProbeResult(included=include_account_auth)``.
323
+ _CORE_PROBES: tuple[str, ...] = (
324
+ "robots.txt published",
325
+ "valid sitemap discovery",
326
+ "agent discovery Link headers",
327
+ "DNS-AID records",
328
+ "llms.txt or Markdown negotiation",
329
+ "AI-specific robots.txt rules",
330
+ "Content Signals in robots.txt",
331
+ )
332
+
333
+
334
+ def _scope_probe_labels(
335
+ include_protocols: bool,
336
+ include_account_auth: bool,
337
+ include_ecommerce: bool,
338
+ ) -> list[str]:
339
+ """Enumerate the strict-agent probe labels for the resolved scope.
340
+
341
+ Mirrors the probe list constructed by ``build_agent_readiness_summary``
342
+ so consumers can rely on ``len(passed) + len(missing) == max`` in both
343
+ the success and degraded-fallback paths.
344
+ """
345
+ labels: list[str] = list(_CORE_PROBES)
346
+ # Web Bot Auth directory is the single core JSON surface.
347
+ labels.extend(label for (label, _, _, _, scope, _) in _JSON_SURFACES if scope == "core")
348
+ if include_account_auth:
349
+ # The hardcoded ``auth.md`` probe is gated by include_account_auth
350
+ # in ``build_agent_readiness_summary``.
351
+ labels.append("auth.md")
352
+ labels.extend(
353
+ label
354
+ for (label, _, _, _, scope, _) in _JSON_SURFACES
355
+ if scope != "core"
356
+ and _scope_included(scope, include_protocols, include_account_auth, include_ecommerce)
357
+ )
358
+ return labels
359
+
360
+
361
+ def _category_summaries(probes: list[ProbeResult]) -> list[AgentReadinessCategory]:
362
+ categories = [
363
+ "Discoverability",
364
+ "Content Accessibility",
365
+ "Bot Access Control",
366
+ "Protocol Discovery",
367
+ "Commerce",
368
+ ]
369
+ summaries: list[AgentReadinessCategory] = []
370
+ for category in categories:
371
+ category_probes = [probe for probe in probes if probe.category == category]
372
+ included = [probe for probe in category_probes if probe.included]
373
+ passed = [probe.label for probe in included if probe.passed]
374
+ missing = [probe.label for probe in included if not probe.passed]
375
+ excluded = [probe.label for probe in category_probes if not probe.included]
376
+ earned = len(passed)
377
+ maximum = len(included)
378
+ score = round((earned / maximum) * 100) if maximum else 0
379
+ summaries.append(
380
+ AgentReadinessCategory(
381
+ name=category,
382
+ earned=earned,
383
+ max=maximum,
384
+ score=score,
385
+ passed=passed,
386
+ missing=missing,
387
+ excluded=excluded,
388
+ )
389
+ )
390
+ return summaries
391
+
392
+
393
+ async def build_agent_readiness_summary(
394
+ context: AuditContext,
395
+ include_protocols: bool = False,
396
+ include_account_auth: bool = False,
397
+ include_ecommerce: bool = False,
398
+ ) -> AgentReadinessSummary:
399
+ sitemap_valid, _, _, _, _ = await best_sitemap(context)
400
+ text_access_available, _ = await agent_text_access(context)
401
+ json_surface_results = [False for _ in _JSON_SURFACES]
402
+ json_surface_tasks = []
403
+ json_surface_indices = []
404
+ for index, (_, paths, accept, _, scope, require_keys) in enumerate(_JSON_SURFACES):
405
+ if _scope_included(scope, include_protocols, include_account_auth, include_ecommerce):
406
+ json_surface_tasks.append(
407
+ _json_surface_available(context, paths, accept, require_keys)
408
+ )
409
+ json_surface_indices.append(index)
410
+ if json_surface_tasks:
411
+ json_surface_found = await asyncio.gather(*json_surface_tasks)
412
+ for index, found in zip(json_surface_indices, json_surface_found, strict=True):
413
+ json_surface_results[index] = found
414
+
415
+ auth_md_available = await _auth_md_available(context) if include_account_auth else False
416
+
417
+ probes = [
418
+ ProbeResult(
419
+ "robots.txt published",
420
+ "Discoverability",
421
+ context.robots.ok and bool(context.robots.text.strip()),
422
+ ),
423
+ ProbeResult("valid sitemap discovery", "Discoverability", sitemap_valid),
424
+ ProbeResult("agent discovery Link headers", "Discoverability", _has_agent_link_header(context)),
425
+ ProbeResult("DNS-AID records", "Discoverability", await _has_dns_aid(context)),
426
+ ProbeResult("llms.txt or Markdown negotiation", "Content Accessibility", text_access_available),
427
+ ProbeResult(
428
+ "AI-specific robots.txt rules",
429
+ "Bot Access Control",
430
+ explicit_ai_bot_count(context.robots.text) > 0 if context.robots.ok else False,
431
+ ),
432
+ ProbeResult(
433
+ "Content Signals in robots.txt",
434
+ "Bot Access Control",
435
+ bool(content_signal_tokens(context.robots.text)) if context.robots.ok else False,
436
+ ),
437
+ ProbeResult(
438
+ "auth.md",
439
+ "Bot Access Control",
440
+ auth_md_available,
441
+ included=include_account_auth,
442
+ ),
443
+ ]
444
+ probes.extend(
445
+ ProbeResult(
446
+ label,
447
+ category,
448
+ passed,
449
+ included=_scope_included(scope, include_protocols, include_account_auth, include_ecommerce),
450
+ )
451
+ for (label, _, _, category, scope, _), passed in zip(_JSON_SURFACES, json_surface_results, strict=True)
452
+ )
453
+
454
+ included_probes = [probe for probe in probes if probe.included]
455
+ passed = [probe.label for probe in included_probes if probe.passed]
456
+ missing = [probe.label for probe in included_probes if not probe.passed]
457
+ excluded = [probe.label for probe in probes if not probe.included]
458
+ earned = len(passed)
459
+ maximum = len(included_probes)
460
+ score = round((earned / maximum) * 100) if maximum else 0
461
+
462
+ if score >= 70:
463
+ label = "Strong agent-native readiness"
464
+ elif score >= 40:
465
+ label = "Developing agent-native readiness"
466
+ elif score > 0:
467
+ label = "Limited agent-native readiness"
468
+ else:
469
+ label = "Limited agent-native readiness"
470
+
471
+ return AgentReadinessSummary(
472
+ score=score,
473
+ earned=earned,
474
+ max=maximum,
475
+ label=label,
476
+ categories=_category_summaries(probes),
477
+ passed=passed,
478
+ missing=missing,
479
+ not_checked=[
480
+ *[f"{label} excluded by audit scope." for label in excluded],
481
+ "WebMCP runtime tool registration requires browser instrumentation and is available in advanced coverage.",
482
+ "Verified crawler IP treatment, live search rankings, live index coverage, and model citation share require external or authenticated data.",
483
+ ],
484
+ benchmark=build_agent_benchmark_comparison(
485
+ score,
486
+ earned,
487
+ maximum,
488
+ include_protocols,
489
+ include_account_auth,
490
+ include_ecommerce,
491
+ ),
492
+ caveat=(
493
+ "This strict lens follows explicit agent-native discovery signals selected for "
494
+ "this audit scope. A site can score well on SEO basics or general crawlability "
495
+ "while still scoring low here if it has not published relevant agent-specific surfaces."
496
+ ),
497
+ )
backend/app/audit_context.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from dataclasses import dataclass
3
+
4
+ from app.fetching import FetchResult, fetch_url, make_root_url
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class AuditContext:
9
+ url: str
10
+ homepage: FetchResult
11
+ robots: FetchResult
12
+ sitemap: FetchResult
13
+
14
+
15
+ async def build_audit_context(url: str) -> AuditContext:
16
+ homepage, robots, sitemap = await asyncio.gather(
17
+ fetch_url(url),
18
+ fetch_url(make_root_url(url, "/robots.txt")),
19
+ fetch_url(make_root_url(url, "/sitemap.xml")),
20
+ )
21
+ return AuditContext(url=url, homepage=homepage, robots=robots, sitemap=sitemap)
backend/app/benchmarks.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-check benchmark peer profiles (schema v2).
2
+
3
+ Peer profiles are stored per-check rather than as pre-baked per-scope
4
+ variants. A single peer record captures the results of one full-scope
5
+ audit run (essentials_checks for the 13 included groups plus the
6
+ agent_passed probe labels). Peer scores are then recomputed at query
7
+ time from the user's chosen scope:
8
+
9
+ - ``peer_essentials`` sums score/max over the 13 groups, applying the
10
+ SAME exclusion rule as ``_checked_points`` (rows with
11
+ ``state == "locked"`` OR ``evidence_level == "unknown"`` contribute
12
+ to neither numerator nor denominator).
13
+ - ``peer_agent`` counts how many of the passed labels match the
14
+ current scope's probe list (``_scope_probe_labels``). Labels in
15
+ ``agent_passed`` that are no longer present in the current probe
16
+ list are silently ignored, so profile snapshots survive probe-list
17
+ evolution.
18
+
19
+ The public tree ships a hand-curated ``_SAMPLE_BENCHMARK_SEEDS`` for
20
+ the demo experience. The private deploy refreshes the on-disk snapshot
21
+ monthly via ``scripts/refresh_benchmarks.py``.
22
+ """
23
+ import json
24
+ import os
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from statistics import median
28
+ from typing import Any
29
+
30
+ from app.models import (
31
+ AgentBenchmarkComparison,
32
+ BenchmarkComparison,
33
+ BenchmarkEntry,
34
+ CheckResult,
35
+ PillarScores,
36
+ )
37
+ from app.rubric import ESSENTIALS_CHECKED_MAX, ESSENTIALS_CHECK_GROUPS
38
+
39
+ # ``_scope_probe_labels`` is imported lazily inside ``peer_agent`` to break
40
+ # the import cycle: ``app.agent_readiness`` imports ``build_agent_benchmark_comparison``
41
+ # from this module, so a top-level import here would deadlock on the
42
+ # partially-initialized module.
43
+
44
+ SCHEMA_VERSION = 2
45
+ BENCHMARK_SNAPSHOT_DATE = "2026-07-17" # fallback only when no file is loaded
46
+ BENCHMARK_BASIS = "Essentials evidence score from the MachineRead audit"
47
+ AGENT_BENCHMARK_BASIS = "Agent-native readiness score from the MachineRead audit"
48
+ BENCHMARK_CAVEAT = (
49
+ "Benchmark peers are scored under the same selected Essentials scope using bounded "
50
+ "public HTTP, DNS, and page evidence. Comparable scores do not imply comparable AI "
51
+ "exposure, search traffic, ecommerce conversion, ranking strength, backlinks, social "
52
+ "traction, real Google/Bing/Brave index coverage, Core Web Vitals field data, or live "
53
+ "model citation share. "
54
+ f"The current Essentials denominator is {ESSENTIALS_CHECKED_MAX} checked points across "
55
+ f"{len(ESSENTIALS_CHECK_GROUPS)} included check groups; each group may aggregate "
56
+ "several underlying signals. Review agent-native readiness separately for explicit "
57
+ "agent discovery."
58
+ )
59
+ AGENT_BENCHMARK_CAVEAT = (
60
+ "This benchmark compares explicit agent-native discovery and protocol signals under "
61
+ "the same selected audit scope. Low scores are common among current large sites, but "
62
+ "that should be read as market immaturity rather than evidence that missing surfaces "
63
+ "are irrelevant. Stored profile earned counts are normalized to the current scope "
64
+ "denominator when the strict probe list changes."
65
+ )
66
+
67
+ BenchmarkProfile = dict[str, Any]
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class _CheckSnapshot:
72
+ """Immutable per-check snapshot stored in a loaded v2 profile.
73
+
74
+ The on-disk JSON keeps keys ``score``, ``max``, ``state``, and
75
+ ``evidence_level`` (per the public schema); after validation we
76
+ freeze each entry into this dataclass so the runtime never
77
+ mutates the snapshot.
78
+ """
79
+
80
+ score: int
81
+ max_score: int
82
+ state: str
83
+ evidence_level: str
84
+
85
+
86
+ _DEFAULT_BENCHMARK_PROFILE_PATH = (
87
+ Path(__file__).resolve().parents[1] / "private_data" / "benchmark_profiles.json"
88
+ )
89
+
90
+
91
+ # --- Validation (eager, at load time) -------------------------------------
92
+
93
+ def _validate_profile(
94
+ profile: dict,
95
+ valid_check_names: set[str],
96
+ rubric_max: dict[str, int],
97
+ ) -> None:
98
+ """Raise ValueError if profile is malformed. Failure is loud at startup."""
99
+ for key in ("name", "category", "group", "size", "url", "essentials_checks", "agent_passed"):
100
+ if key not in profile:
101
+ raise ValueError(f"profile missing required key {key!r}")
102
+ for key in ("name", "category", "group", "size", "url"):
103
+ if not isinstance(profile[key], str):
104
+ raise ValueError(
105
+ f"profile {profile.get('name')!r}: {key!r} must be a string, "
106
+ f"got {type(profile[key]).__name__}"
107
+ )
108
+ checks = profile["essentials_checks"]
109
+ if not isinstance(checks, dict):
110
+ raise ValueError(f"profile {profile['name']!r}: essentials_checks must be a dict")
111
+ actual = set(checks.keys())
112
+ if actual != valid_check_names:
113
+ missing = valid_check_names - actual
114
+ extra = actual - valid_check_names
115
+ problems = []
116
+ if missing:
117
+ problems.append(f"missing {sorted(missing)}")
118
+ if extra:
119
+ problems.append(f"unknown {sorted(extra)}")
120
+ raise ValueError(
121
+ f"profile {profile['name']!r}: essentials_checks keys: {'; '.join(problems)}"
122
+ )
123
+ for check_name, entry in checks.items():
124
+ if not isinstance(entry, dict):
125
+ raise ValueError(
126
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}] must be a dict"
127
+ )
128
+ for key in ("score", "max", "state", "evidence_level"):
129
+ if key not in entry:
130
+ raise ValueError(
131
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}] "
132
+ f"missing {key!r}"
133
+ )
134
+ if not isinstance(entry["score"], int) or isinstance(entry["score"], bool):
135
+ raise ValueError(
136
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}].score "
137
+ f"must be an int"
138
+ )
139
+ if not isinstance(entry["max"], int) or isinstance(entry["max"], bool):
140
+ raise ValueError(
141
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}].max "
142
+ f"must be an int"
143
+ )
144
+ if entry["max"] != rubric_max[check_name]:
145
+ raise ValueError(
146
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}].max "
147
+ f"is {entry['max']}, rubric says {rubric_max[check_name]}"
148
+ )
149
+ if not (0 <= entry["score"] <= entry["max"]):
150
+ raise ValueError(
151
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}].score "
152
+ f"{entry['score']} not in [0, {entry['max']}]"
153
+ )
154
+ if entry["state"] not in ("pass", "partial", "fail", "warn", "locked"):
155
+ raise ValueError(
156
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}].state "
157
+ f"{entry['state']!r} unknown"
158
+ )
159
+ if entry["evidence_level"] not in ("verified", "inferred", "unknown"):
160
+ raise ValueError(
161
+ f"profile {profile['name']!r}: essentials_checks[{check_name!r}].evidence_level "
162
+ f"{entry['evidence_level']!r} unknown"
163
+ )
164
+ agent_passed = profile["agent_passed"]
165
+ if not isinstance(agent_passed, list):
166
+ raise ValueError(f"profile {profile['name']!r}: agent_passed must be a list")
167
+ for i, label in enumerate(agent_passed):
168
+ if not isinstance(label, str):
169
+ raise ValueError(
170
+ f"profile {profile['name']!r}: agent_passed[{i}] must be a string, "
171
+ f"got {type(label).__name__}"
172
+ )
173
+
174
+
175
+ def _coerce_entry(entry: Any) -> _CheckSnapshot:
176
+ """Accept either a loaded ``_CheckSnapshot`` or a raw dict with
177
+ ``score``/``max``/``state``/``evidence_level`` keys. Used by
178
+ ``_check_payload`` so that ad-hoc test profiles (dict shape) and
179
+ loaded profiles (frozen shape) both work.
180
+ """
181
+ if isinstance(entry, _CheckSnapshot):
182
+ return entry
183
+ return _CheckSnapshot(
184
+ score=int(entry["score"]),
185
+ max_score=int(entry["max"]),
186
+ state=entry["state"],
187
+ evidence_level=entry["evidence_level"],
188
+ )
189
+
190
+
191
+ def _check_payload(profile: dict) -> list[CheckResult]:
192
+ """Project a v2 profile's essentials_checks into CheckResult-like rows so
193
+ peer_essentials can reuse the existing _checked_points rule.
194
+ """
195
+ pillar_by_check = {g.check_name: g.pillar for g in ESSENTIALS_CHECK_GROUPS}
196
+ label_by_check = {g.check_name: g.label for g in ESSENTIALS_CHECK_GROUPS}
197
+ rows = []
198
+ for check_name, entry in profile["essentials_checks"].items():
199
+ snap = _coerce_entry(entry)
200
+ rows.append(
201
+ CheckResult(
202
+ pillar=pillar_by_check[check_name],
203
+ check_name=check_name,
204
+ label=label_by_check[check_name],
205
+ state=snap.state,
206
+ score=snap.score,
207
+ max_score=snap.max_score,
208
+ finding="",
209
+ fix="",
210
+ effort="low",
211
+ evidence_level=snap.evidence_level,
212
+ )
213
+ )
214
+ return rows
215
+
216
+
217
+ def peer_essentials(profile: dict) -> tuple[int, int, PillarScores]:
218
+ """Sum score/max over the 13 groups, applying the SAME exclusion rule
219
+ as ``_checked_points()`` (rows with ``state == 'locked'`` OR
220
+ ``evidence_level == 'unknown'`` contribute to neither numerator nor
221
+ denominator). Returns ``(checked_score, checked_max, pillar_scores)``.
222
+ """
223
+ rows = _check_payload(profile)
224
+ checked_score, checked_max = _checked_points(rows)
225
+ by_pillar = {"off_site": 0, "scrapability": 0, "seo": 0}
226
+ pillar_by_check = {g.check_name: g.pillar for g in ESSENTIALS_CHECK_GROUPS}
227
+ for row in rows:
228
+ if row.state == "locked" or row.evidence_level == "unknown":
229
+ continue
230
+ by_pillar[pillar_by_check[row.check_name]] += row.score
231
+ return checked_score, checked_max, PillarScores(**by_pillar)
232
+
233
+
234
+ def peer_agent(
235
+ profile: dict,
236
+ include_protocols: bool,
237
+ include_account_auth: bool,
238
+ include_ecommerce: bool,
239
+ ) -> tuple[int, int]:
240
+ """Count how many probes the peer passed in the current scope.
241
+ Labels in ``agent_passed`` that no longer exist in
242
+ ``_scope_probe_labels`` are silently ignored (robust to probe-list
243
+ evolution).
244
+ """
245
+ from app.agent_readiness import _scope_probe_labels # lazy: break import cycle
246
+
247
+ labels = _scope_probe_labels(include_protocols, include_account_auth, include_ecommerce)
248
+ passed = set(profile["agent_passed"])
249
+ earned = sum(1 for label in labels if label in passed)
250
+ return earned, len(labels)
251
+
252
+
253
+ # --- _agent_max_for_scope (KEEP — used by tests) ---------------------------
254
+
255
+ def _agent_max_for_scope(
256
+ include_protocols: bool = False,
257
+ include_account_auth: bool = False,
258
+ include_ecommerce: bool = False,
259
+ ) -> int:
260
+ return 8 + (6 if include_protocols else 0) + (3 if include_account_auth else 0) + (
261
+ 4 if include_ecommerce else 0
262
+ )
263
+
264
+
265
+ # --- Scope-key helper (KEEP for legacy tests + label display) --------------
266
+
267
+ def benchmark_scope_key(
268
+ include_protocols: bool = False,
269
+ include_account_auth: bool = False,
270
+ include_ecommerce: bool = False,
271
+ ) -> str:
272
+ """Label-only display helper. v2 stores one profile per peer; this key
273
+ is preserved for tests and UI display that asserts on the variant
274
+ shape. It is no longer used by the benchmarks comparison path.
275
+ """
276
+ return f"p{int(include_protocols)}_a{int(include_account_auth)}_c{int(include_ecommerce)}"
277
+
278
+
279
+ # --- Sample seeds (12 fictional peers, v2 profile dicts) ------------------
280
+
281
+ # Each peer's per-check scores were chosen so the sum over kept rows equals
282
+ # the v1 checked_score for the corresponding peer. agent_passed labels were
283
+ # distributed so commerce/API peers include protocol-scope probes while
284
+ # corporate/editorial peers do not.
285
+
286
+ _BASE_CORE_LABELS = (
287
+ "robots.txt published",
288
+ "valid sitemap discovery",
289
+ "agent discovery Link headers",
290
+ "DNS-AID records",
291
+ "llms.txt or Markdown negotiation",
292
+ "AI-specific robots.txt rules",
293
+ "Content Signals in robots.txt",
294
+ )
295
+ _PROTOCOL_LABELS = (
296
+ "API Catalog",
297
+ "MCP Server Card",
298
+ "A2A Agent Card",
299
+ "Agent Skills index",
300
+ "WebMCP manifest",
301
+ "ARD static catalog",
302
+ )
303
+ _AUTH_LABEL = ("auth.md",)
304
+
305
+
306
+ def _seed_profile(
307
+ *,
308
+ name: str,
309
+ category: str,
310
+ group: str,
311
+ size: str,
312
+ url: str,
313
+ check_scores: dict[str, int],
314
+ agent_passed: list[str],
315
+ ) -> dict[str, Any]:
316
+ """Build a v2 profile dict from per-check score map and passed label list."""
317
+ by_check = {g.check_name: g for g in ESSENTIALS_CHECK_GROUPS}
318
+ essentials_checks: dict[str, dict[str, Any]] = {}
319
+ for check_name, group_obj in by_check.items():
320
+ max_score = group_obj.max_score
321
+ score = check_scores[check_name]
322
+ if score == max_score:
323
+ state = "pass"
324
+ elif score > 0:
325
+ state = "partial"
326
+ else:
327
+ state = "fail"
328
+ essentials_checks[check_name] = {
329
+ "score": score,
330
+ "max": max_score,
331
+ "state": state,
332
+ "evidence_level": "verified",
333
+ }
334
+ return {
335
+ "name": name,
336
+ "category": category,
337
+ "group": group,
338
+ "size": size,
339
+ "url": url,
340
+ "essentials_checks": essentials_checks,
341
+ "agent_passed": list(agent_passed),
342
+ }
343
+
344
+
345
+ def _commerce_passed(base_earned: int, *, with_protocols: bool = False) -> list[str]:
346
+ """Return a plausible agent_passed list for a commerce-style peer."""
347
+ passed = list(_BASE_CORE_LABELS[: min(len(_BASE_CORE_LABELS), base_earned)])
348
+ if with_protocols and base_earned > len(_BASE_CORE_LABELS):
349
+ slots = base_earned - len(_BASE_CORE_LABELS)
350
+ passed.extend(_PROTOCOL_LABELS[:slots])
351
+ return passed
352
+
353
+
354
+ def _editorial_passed(base_earned: int) -> list[str]:
355
+ """Return a plausible agent_passed list for an editorial/corporate peer."""
356
+ return list(_BASE_CORE_LABELS[: min(len(_BASE_CORE_LABELS), base_earned)])
357
+
358
+
359
+ # v1 totals per peer (off_site, scrapability, seo) -> rebuilt here as per-check
360
+ # distributions that sum to the same totals. Sample-only; the private deploy
361
+ # regenerates real data via scripts/refresh_benchmarks.py.
362
+ _SAMPLE_BENCHMARK_SEEDS: list[dict] = [
363
+ # Commerce enterprise, strong scrapability
364
+ _seed_profile(
365
+ name="Example Retail Enterprise",
366
+ category="Major retailer",
367
+ group="ecommerce",
368
+ size="enterprise",
369
+ url="https://example.com/retail",
370
+ check_scores={
371
+ "social": 1, "wikipedia": 4,
372
+ "robots_txt": 6, "bot_access": 6, "html_structure": 4,
373
+ "schema_ld": 5, "llms_txt": 0, "ssr": 2, "machine_surfaces": 2,
374
+ "pagespeed": 2, "canonical": 5, "indexing": 4, "search_discovery": 3,
375
+ },
376
+ agent_passed=_commerce_passed(3, with_protocols=False),
377
+ ),
378
+ # Commerce enterprise, balanced
379
+ _seed_profile(
380
+ name="Example Consumer Brand",
381
+ category="Major consumer brand",
382
+ group="ecommerce",
383
+ size="enterprise",
384
+ url="https://example.com/consumer",
385
+ check_scores={
386
+ "social": 2, "wikipedia": 3,
387
+ "robots_txt": 5, "bot_access": 5, "html_structure": 3,
388
+ "schema_ld": 4, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
389
+ "pagespeed": 2, "canonical": 5, "indexing": 4, "search_discovery": 3,
390
+ },
391
+ agent_passed=_commerce_passed(2, with_protocols=False),
392
+ ),
393
+ # Commerce enterprise, strong on protocol surfaces (API catalog etc.)
394
+ _seed_profile(
395
+ name="Example Commerce Platform",
396
+ category="Commerce platform",
397
+ group="ecommerce",
398
+ size="enterprise",
399
+ url="https://example.com/platform",
400
+ check_scores={
401
+ "social": 2, "wikipedia": 4,
402
+ "robots_txt": 6, "bot_access": 6, "html_structure": 4,
403
+ "schema_ld": 5, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
404
+ "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3,
405
+ },
406
+ agent_passed=_commerce_passed(5, with_protocols=True),
407
+ ),
408
+ # Specialty DTC product, mid-tier
409
+ _seed_profile(
410
+ name="Example Product Studio",
411
+ category="Niche DTC product",
412
+ group="ecommerce",
413
+ size="specialty",
414
+ url="https://example.com/product",
415
+ check_scores={
416
+ "social": 1, "wikipedia": 3,
417
+ "robots_txt": 5, "bot_access": 5, "html_structure": 4,
418
+ "schema_ld": 4, "llms_txt": 0, "ssr": 4, "machine_surfaces": 2,
419
+ "pagespeed": 3, "canonical": 5, "indexing": 4, "search_discovery": 3,
420
+ },
421
+ agent_passed=_commerce_passed(3, with_protocols=False),
422
+ ),
423
+ # Niche beauty brand, mid-tier
424
+ _seed_profile(
425
+ name="Example Beauty Brand",
426
+ category="Niche beauty brand",
427
+ group="ecommerce",
428
+ size="specialty",
429
+ url="https://example.com/beauty",
430
+ check_scores={
431
+ "social": 1, "wikipedia": 3,
432
+ "robots_txt": 5, "bot_access": 5, "html_structure": 4,
433
+ "schema_ld": 4, "llms_txt": 0, "ssr": 4, "machine_surfaces": 2,
434
+ "pagespeed": 3, "canonical": 5, "indexing": 4, "search_discovery": 2,
435
+ },
436
+ agent_passed=_commerce_passed(3, with_protocols=False),
437
+ ),
438
+ # Specialty commerce, weak
439
+ _seed_profile(
440
+ name="Example Outdoor Shop",
441
+ category="Specialty commerce",
442
+ group="ecommerce",
443
+ size="specialty",
444
+ url="https://example.com/outdoor",
445
+ check_scores={
446
+ "social": 1, "wikipedia": 1,
447
+ "robots_txt": 3, "bot_access": 3, "html_structure": 2,
448
+ "schema_ld": 2, "llms_txt": 0, "ssr": 2, "machine_surfaces": 2,
449
+ "pagespeed": 1, "canonical": 3, "indexing": 2, "search_discovery": 2,
450
+ },
451
+ agent_passed=_commerce_passed(1, with_protocols=False),
452
+ ),
453
+ # Boutique commerce, strong SEO
454
+ _seed_profile(
455
+ name="Example Paper Goods",
456
+ category="Boutique product",
457
+ group="ecommerce",
458
+ size="boutique",
459
+ url="https://example.com/paper",
460
+ check_scores={
461
+ "social": 2, "wikipedia": 2,
462
+ "robots_txt": 4, "bot_access": 4, "html_structure": 2,
463
+ "schema_ld": 3, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
464
+ "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3,
465
+ },
466
+ agent_passed=_commerce_passed(2, with_protocols=False),
467
+ ),
468
+ # Boutique commerce, weak
469
+ _seed_profile(
470
+ name="Example Desk Goods",
471
+ category="Boutique product",
472
+ group="ecommerce",
473
+ size="boutique",
474
+ url="https://example.com/desk",
475
+ check_scores={
476
+ "social": 1, "wikipedia": 1,
477
+ "robots_txt": 2, "bot_access": 2, "html_structure": 1,
478
+ "schema_ld": 1, "llms_txt": 0, "ssr": 1, "machine_surfaces": 1,
479
+ "pagespeed": 1, "canonical": 2, "indexing": 1, "search_discovery": 0,
480
+ },
481
+ agent_passed=_commerce_passed(1, with_protocols=False),
482
+ ),
483
+ # Major technology brand (corporate), mid-tier
484
+ _seed_profile(
485
+ name="Example Technology Company",
486
+ category="Major technology brand",
487
+ group="corporate",
488
+ size="enterprise",
489
+ url="https://example.com/technology",
490
+ check_scores={
491
+ "social": 1, "wikipedia": 3,
492
+ "robots_txt": 6, "bot_access": 6, "html_structure": 4,
493
+ "schema_ld": 4, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
494
+ "pagespeed": 2, "canonical": 5, "indexing": 4, "search_discovery": 3,
495
+ },
496
+ agent_passed=_editorial_passed(3),
497
+ ),
498
+ # Developer platform, strong on protocols
499
+ _seed_profile(
500
+ name="Example Developer Platform",
501
+ category="Developer platform",
502
+ group="corporate",
503
+ size="specialty",
504
+ url="https://example.com/developer",
505
+ check_scores={
506
+ "social": 2, "wikipedia": 4,
507
+ "robots_txt": 6, "bot_access": 6, "html_structure": 4,
508
+ "schema_ld": 5, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
509
+ "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3,
510
+ },
511
+ agent_passed=_BASE_CORE_LABELS + _PROTOCOL_LABELS,
512
+ ),
513
+ # Software company (boutique), mid-tier
514
+ _seed_profile(
515
+ name="Example Software Studio",
516
+ category="Software company",
517
+ group="corporate",
518
+ size="boutique",
519
+ url="https://example.com/software",
520
+ check_scores={
521
+ "social": 2, "wikipedia": 2,
522
+ "robots_txt": 5, "bot_access": 5, "html_structure": 3,
523
+ "schema_ld": 3, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
524
+ "pagespeed": 2, "canonical": 3, "indexing": 4, "search_discovery": 2,
525
+ },
526
+ agent_passed=_editorial_passed(2),
527
+ ),
528
+ # Professional services / SaaS, strong on protocols
529
+ _seed_profile(
530
+ name="Example Scheduling Service",
531
+ category="SaaS service",
532
+ group="services",
533
+ size="specialty",
534
+ url="https://example.com/scheduling",
535
+ check_scores={
536
+ "social": 2, "wikipedia": 4,
537
+ "robots_txt": 6, "bot_access": 6, "html_structure": 4,
538
+ "schema_ld": 5, "llms_txt": 0, "ssr": 3, "machine_surfaces": 2,
539
+ "pagespeed": 3, "canonical": 5, "indexing": 5, "search_discovery": 3,
540
+ },
541
+ agent_passed=_BASE_CORE_LABELS + _PROTOCOL_LABELS,
542
+ ),
543
+ ]
544
+
545
+
546
+ def _sample_benchmark_profiles() -> list[dict]:
547
+ """Return v2 profile dicts for the bundled sample seeds (validation happens
548
+ at loader time so the runtime never sees malformed sample data).
549
+ """
550
+ return [dict(seed) for seed in _SAMPLE_BENCHMARK_SEEDS]
551
+
552
+
553
+ # --- Loader (parses v2 envelope) -------------------------------------------
554
+
555
+ def _configured_benchmark_profile_path() -> Path | None:
556
+ configured_path = os.getenv("MACHINEREAD_BENCHMARK_PROFILE_PATH")
557
+ if configured_path:
558
+ return Path(configured_path).expanduser()
559
+ return None
560
+
561
+
562
+ def _load_benchmark_profiles() -> tuple[BenchmarkProfile, ...]:
563
+ """Parse v2 envelope. Eager validation. Fail loud on malformed input.
564
+
565
+ Returns an immutable tuple of dicts so callers cannot mutate the
566
+ snapshot at runtime.
567
+ """
568
+ configured_path = _configured_benchmark_profile_path()
569
+ if configured_path:
570
+ if not configured_path.exists():
571
+ raise FileNotFoundError(f"Benchmark profile file not found: {configured_path}")
572
+ payload = json.loads(configured_path.read_text(encoding="utf-8"))
573
+ elif _DEFAULT_BENCHMARK_PROFILE_PATH.exists():
574
+ payload = json.loads(_DEFAULT_BENCHMARK_PROFILE_PATH.read_text(encoding="utf-8"))
575
+ else:
576
+ return tuple(_sample_benchmark_profiles())
577
+
578
+ # Detect v1 (bare list) shape and refuse to migrate
579
+ if isinstance(payload, list):
580
+ raise ValueError(
581
+ "Benchmark profile file is in the deprecated v1 (bare list) format. "
582
+ "Run `python scripts/refresh_benchmarks.py --peers "
583
+ "scripts/benchmark_peers.sample.json --out <path>` to migrate."
584
+ )
585
+ if not isinstance(payload, dict):
586
+ raise ValueError(
587
+ f"Benchmark profile file: expected object, got {type(payload).__name__}"
588
+ )
589
+ if payload.get("schema_version") != SCHEMA_VERSION:
590
+ raise ValueError(
591
+ f"Benchmark profile file: schema_version {payload.get('schema_version')!r} "
592
+ f"!= required {SCHEMA_VERSION}"
593
+ )
594
+ profiles = payload.get("profiles")
595
+ if not isinstance(profiles, list):
596
+ raise ValueError("Benchmark profile file: 'profiles' must be a list")
597
+
598
+ valid_check_names = {g.check_name for g in ESSENTIALS_CHECK_GROUPS}
599
+ rubric_max = {g.check_name: g.max_score for g in ESSENTIALS_CHECK_GROUPS}
600
+ validated: list[BenchmarkProfile] = []
601
+ for profile in profiles:
602
+ _validate_profile(profile, valid_check_names, rubric_max)
603
+ validated.append({
604
+ "name": profile["name"],
605
+ "category": profile["category"],
606
+ "group": profile["group"],
607
+ "size": profile["size"],
608
+ "url": profile["url"],
609
+ "essentials_checks": {
610
+ k: _CheckSnapshot(
611
+ score=int(v["score"]),
612
+ max_score=int(v["max"]),
613
+ state=v["state"],
614
+ evidence_level=v["evidence_level"],
615
+ )
616
+ for k, v in profile["essentials_checks"].items()
617
+ },
618
+ "agent_passed": tuple(profile["agent_passed"]),
619
+ })
620
+ return tuple(validated)
621
+
622
+
623
+ _BENCHMARK_PROFILES: tuple[BenchmarkProfile, ...] = _load_benchmark_profiles()
624
+
625
+
626
+ def _loaded_snapshot_date() -> str:
627
+ """Read the snapshot date from the loaded profile file, or fall back to
628
+ the bundled constant. The bundled sample seeds have no file on disk,
629
+ so they fall back.
630
+ """
631
+ configured_path = _configured_benchmark_profile_path()
632
+ if configured_path and configured_path.exists():
633
+ payload = json.loads(configured_path.read_text(encoding="utf-8"))
634
+ if isinstance(payload, dict):
635
+ return str(payload.get("snapshot_date") or BENCHMARK_SNAPSHOT_DATE)
636
+ if _DEFAULT_BENCHMARK_PROFILE_PATH.exists():
637
+ payload = json.loads(_DEFAULT_BENCHMARK_PROFILE_PATH.read_text(encoding="utf-8"))
638
+ if isinstance(payload, dict):
639
+ return str(payload.get("snapshot_date") or BENCHMARK_SNAPSHOT_DATE)
640
+ return BENCHMARK_SNAPSHOT_DATE
641
+
642
+
643
+ # --- Entry construction at query time -------------------------------------
644
+
645
+ def _entries(
646
+ include_protocols: bool,
647
+ include_account_auth: bool,
648
+ include_ecommerce: bool,
649
+ ) -> list[BenchmarkEntry]:
650
+ """Build BenchmarkEntry per profile for the current scope.
651
+
652
+ Replaces the v1 ``_entries_for_scope(scope_key)`` which keyed off
653
+ pre-baked per-scope variants. Scope is now derived from the three
654
+ booleans at call time.
655
+ """
656
+ entries: list[BenchmarkEntry] = []
657
+ for profile in _BENCHMARK_PROFILES:
658
+ checked_score, checked_max, pillar_scores = peer_essentials(profile)
659
+ agent_earned, agent_max = peer_agent(
660
+ profile, include_protocols, include_account_auth, include_ecommerce
661
+ )
662
+ free_evidence_score = (
663
+ round((checked_score / checked_max) * 100) if checked_max else 0
664
+ )
665
+ agent_readiness_score = (
666
+ round((agent_earned / agent_max) * 100) if agent_max else 0
667
+ )
668
+ entries.append(
669
+ BenchmarkEntry(
670
+ name=profile["name"],
671
+ category=profile["category"],
672
+ group=profile["group"],
673
+ size=profile["size"],
674
+ url=profile["url"],
675
+ overall_score=checked_score,
676
+ free_evidence_score=free_evidence_score,
677
+ checked_score=checked_score,
678
+ checked_max=checked_max,
679
+ agent_readiness_score=agent_readiness_score,
680
+ agent_readiness_earned=agent_earned,
681
+ agent_readiness_max=agent_max,
682
+ pillar_scores=pillar_scores,
683
+ )
684
+ )
685
+ return entries
686
+
687
+
688
+ # --- _checked_points (KEEP) and free_evidence_score (KEEP) -----------------
689
+
690
+ def _checked_points(checks: list[CheckResult]) -> tuple[int, int]:
691
+ # Exclude paid-tier locked rows AND inconclusive (warn/unknown-evidence) rows.
692
+ # Warn-state fallbacks (e.g. transient fetch failures from _fallback_check_result)
693
+ # carry evidence_level='unknown' and score=0/max_score=group.max_score. Keeping
694
+ # them in the denominator silently drags the Evidence score down even when the
695
+ # real site satisfied every other check. Treat them as out-of-scope for the
696
+ # benchmark the same way reserved/paid rows are excluded.
697
+ checked = [
698
+ check
699
+ for check in checks
700
+ if check.state != "locked" and check.evidence_level != "unknown"
701
+ ]
702
+ return (
703
+ sum(check.score for check in checked),
704
+ sum(check.max_score for check in checked),
705
+ )
706
+
707
+
708
+ def free_evidence_score(checks: list[CheckResult]) -> int:
709
+ checked_score, checked_max = _checked_points(checks)
710
+ if not checked_max:
711
+ return 0
712
+ return round((checked_score / checked_max) * 100)
713
+
714
+
715
+ # --- Percentile / position helpers (KEEP unchanged) ------------------------
716
+
717
+ def _percentile(score: int, entries: list[BenchmarkEntry]) -> int:
718
+ if not entries:
719
+ return 0
720
+ at_or_below = sum(entry.free_evidence_score <= score for entry in entries)
721
+ return round((at_or_below / len(entries)) * 100)
722
+
723
+
724
+ def _agent_percentile(score: int, entries: list[BenchmarkEntry]) -> int:
725
+ if not entries:
726
+ return 0
727
+ at_or_below = sum(entry.agent_readiness_score <= score for entry in entries)
728
+ return round((at_or_below / len(entries)) * 100)
729
+
730
+
731
+ def _position_label(score: int, entries: list[BenchmarkEntry]) -> str:
732
+ scores = sorted(entry.free_evidence_score for entry in entries)
733
+ lower_quartile = scores[len(scores) // 4]
734
+ upper_quartile = scores[(len(scores) * 3) // 4]
735
+ median_score = round(median(scores))
736
+
737
+ if score >= upper_quartile:
738
+ return "Near the top of this Essentials benchmark snapshot"
739
+ if score >= median_score:
740
+ return "Above the middle of this Essentials benchmark snapshot"
741
+ if score >= lower_quartile:
742
+ return "Within the middle of this Essentials benchmark snapshot"
743
+ return "Below most sites in this Essentials benchmark snapshot"
744
+
745
+
746
+ def _agent_position_label(score: int, entries: list[BenchmarkEntry]) -> str:
747
+ scores = sorted(entry.agent_readiness_score for entry in entries)
748
+ lower_quartile = scores[len(scores) // 4]
749
+ upper_quartile = scores[(len(scores) * 3) // 4]
750
+ median_score = round(median(scores))
751
+
752
+ if score >= upper_quartile:
753
+ return "Near the top of this strict agent-readiness snapshot"
754
+ if score >= median_score:
755
+ return "Above the middle of this strict agent-readiness snapshot"
756
+ if score >= lower_quartile:
757
+ return "Within the middle of this strict agent-readiness snapshot"
758
+ return "Below most sites in this strict agent-readiness snapshot"
759
+
760
+
761
+ # --- Public API: build_benchmark_comparison --------------------------------
762
+
763
+ def build_benchmark_comparison(
764
+ checks: list[CheckResult],
765
+ include_protocols: bool = False,
766
+ include_account_auth: bool = False,
767
+ include_ecommerce: bool = False,
768
+ ) -> BenchmarkComparison:
769
+ snapshot_date = _loaded_snapshot_date()
770
+ entries = sorted(
771
+ _entries(include_protocols, include_account_auth, include_ecommerce),
772
+ key=lambda entry: (-entry.free_evidence_score, entry.name),
773
+ )
774
+ if not entries:
775
+ return BenchmarkComparison(
776
+ score=0,
777
+ checked_score=0,
778
+ checked_max=0,
779
+ benchmark_count=0,
780
+ median_score=0,
781
+ percentile=0,
782
+ position_label="No peers available",
783
+ nearest=[],
784
+ entries=[],
785
+ basis=BENCHMARK_BASIS,
786
+ snapshot_date=snapshot_date,
787
+ caveat=BENCHMARK_CAVEAT,
788
+ )
789
+
790
+ checked_score, checked_max = _checked_points(checks)
791
+ score = free_evidence_score(checks)
792
+ nearest = sorted(
793
+ entries,
794
+ key=lambda entry: (abs(entry.free_evidence_score - score), -entry.free_evidence_score, entry.name),
795
+ )[:3]
796
+
797
+ return BenchmarkComparison(
798
+ score=score,
799
+ checked_score=checked_score,
800
+ checked_max=checked_max,
801
+ benchmark_count=len(entries),
802
+ median_score=round(median(entry.free_evidence_score for entry in entries)),
803
+ percentile=_percentile(score, entries),
804
+ position_label=_position_label(score, entries),
805
+ nearest=nearest,
806
+ entries=entries,
807
+ basis=BENCHMARK_BASIS,
808
+ snapshot_date=snapshot_date,
809
+ caveat=BENCHMARK_CAVEAT,
810
+ )
811
+
812
+
813
+ def build_agent_benchmark_comparison(
814
+ score: int,
815
+ earned: int,
816
+ maximum: int,
817
+ include_protocols: bool = False,
818
+ include_account_auth: bool = False,
819
+ include_ecommerce: bool = False,
820
+ ) -> AgentBenchmarkComparison:
821
+ snapshot_date = _loaded_snapshot_date()
822
+ entries = sorted(
823
+ _entries(include_protocols, include_account_auth, include_ecommerce),
824
+ key=lambda entry: (-entry.agent_readiness_score, entry.name),
825
+ )
826
+ if not entries:
827
+ return AgentBenchmarkComparison(
828
+ score=0,
829
+ earned=0,
830
+ max=0,
831
+ benchmark_count=0,
832
+ median_score=0,
833
+ percentile=0,
834
+ position_label="No peers available",
835
+ nearest=[],
836
+ entries=[],
837
+ basis=AGENT_BENCHMARK_BASIS,
838
+ snapshot_date=snapshot_date,
839
+ caveat=AGENT_BENCHMARK_CAVEAT,
840
+ )
841
+
842
+ nearest = sorted(
843
+ entries,
844
+ key=lambda entry: (abs(entry.agent_readiness_score - score), -entry.agent_readiness_score, entry.name),
845
+ )[:3]
846
+
847
+ return AgentBenchmarkComparison(
848
+ score=score,
849
+ earned=earned,
850
+ max=maximum,
851
+ benchmark_count=len(entries),
852
+ median_score=round(median(entry.agent_readiness_score for entry in entries)),
853
+ percentile=_agent_percentile(score, entries),
854
+ position_label=_agent_position_label(score, entries),
855
+ nearest=nearest,
856
+ entries=entries,
857
+ basis=AGENT_BENCHMARK_BASIS,
858
+ snapshot_date=snapshot_date,
859
+ caveat=AGENT_BENCHMARK_CAVEAT,
860
+ )
backend/app/checks/__init__.py ADDED
File without changes
backend/app/checks/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (184 Bytes). View file
 
backend/app/checks/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (172 Bytes). View file
 
backend/app/checks/__pycache__/ard_catalog.cpython-311.pyc ADDED
Binary file (13.5 kB). View file
 
backend/app/checks/__pycache__/ard_catalog.cpython-312.pyc ADDED
Binary file (11.6 kB). View file
 
backend/app/checks/__pycache__/bot_access.cpython-311.pyc ADDED
Binary file (18.5 kB). View file
 
backend/app/checks/__pycache__/bot_access.cpython-312.pyc ADDED
Binary file (17.2 kB). View file
 
backend/app/checks/__pycache__/canonical.cpython-311.pyc ADDED
Binary file (5.88 kB). View file
 
backend/app/checks/__pycache__/canonical.cpython-312.pyc ADDED
Binary file (5.53 kB). View file
 
backend/app/checks/__pycache__/extraction_readiness.cpython-311.pyc ADDED
Binary file (44.2 kB). View file
 
backend/app/checks/__pycache__/extraction_readiness.cpython-312.pyc ADDED
Binary file (37.5 kB). View file
 
backend/app/checks/__pycache__/html_structure.cpython-311.pyc ADDED
Binary file (21.8 kB). View file
 
backend/app/checks/__pycache__/html_structure.cpython-312.pyc ADDED
Binary file (17 kB). View file
 
backend/app/checks/__pycache__/indexing.cpython-311.pyc ADDED
Binary file (15.4 kB). View file
 
backend/app/checks/__pycache__/indexing.cpython-312.pyc ADDED
Binary file (13.3 kB). View file
 
backend/app/checks/__pycache__/llms_txt.cpython-311.pyc ADDED
Binary file (19 kB). View file
 
backend/app/checks/__pycache__/llms_txt.cpython-312.pyc ADDED
Binary file (17.2 kB). View file
 
backend/app/checks/__pycache__/locked.cpython-311.pyc ADDED
Binary file (4.56 kB). View file
 
backend/app/checks/__pycache__/locked.cpython-312.pyc ADDED
Binary file (4.32 kB). View file
 
backend/app/checks/__pycache__/machine_surfaces.cpython-311.pyc ADDED
Binary file (33.1 kB). View file
 
backend/app/checks/__pycache__/machine_surfaces.cpython-312.pyc ADDED
Binary file (30.1 kB). View file
 
backend/app/checks/__pycache__/pagespeed.cpython-311.pyc ADDED
Binary file (14.7 kB). View file
 
backend/app/checks/__pycache__/pagespeed.cpython-312.pyc ADDED
Binary file (13.1 kB). View file
 
backend/app/checks/__pycache__/robots.cpython-311.pyc ADDED
Binary file (22.8 kB). View file
 
backend/app/checks/__pycache__/robots.cpython-312.pyc ADDED
Binary file (19.6 kB). View file
 
backend/app/checks/__pycache__/schema_ld.cpython-311.pyc ADDED
Binary file (22.9 kB). View file
 
backend/app/checks/__pycache__/schema_ld.cpython-312.pyc ADDED
Binary file (18.9 kB). View file
 
backend/app/checks/__pycache__/search_blurb.cpython-311.pyc ADDED
Binary file (28 kB). View file
 
backend/app/checks/__pycache__/search_blurb.cpython-312.pyc ADDED
Binary file (23.9 kB). View file
 
backend/app/checks/__pycache__/search_discovery.cpython-311.pyc ADDED
Binary file (71.5 kB). View file
 
backend/app/checks/__pycache__/search_discovery.cpython-312.pyc ADDED
Binary file (60.5 kB). View file
 
backend/app/checks/__pycache__/sitemap_analysis.cpython-311.pyc ADDED
Binary file (15.2 kB). View file
 
backend/app/checks/__pycache__/sitemap_analysis.cpython-312.pyc ADDED
Binary file (13.7 kB). View file
 
backend/app/checks/__pycache__/social.cpython-311.pyc ADDED
Binary file (21.5 kB). View file
 
backend/app/checks/__pycache__/social.cpython-312.pyc ADDED
Binary file (18 kB). View file
 
backend/app/checks/__pycache__/ssr.cpython-311.pyc ADDED
Binary file (15.4 kB). View file
 
backend/app/checks/__pycache__/ssr.cpython-312.pyc ADDED
Binary file (13.9 kB). View file
 
backend/app/checks/__pycache__/wikipedia.cpython-311.pyc ADDED
Binary file (16.5 kB). View file
 
backend/app/checks/__pycache__/wikipedia.cpython-312.pyc ADDED
Binary file (15.1 kB). View file
 
backend/app/checks/ard_catalog.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure bounded validation for ARD static catalog payloads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from datetime import datetime
8
+ from typing import Any
9
+ from urllib.parse import urlparse
10
+
11
+ _MAX_PAYLOAD_BYTES = 500 * 1024
12
+ _SEMVER_PATTERN = re.compile(r"^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$")
13
+ _URN_AIR_PATTERN = re.compile(r"^urn:air:[a-z0-9.-]+(?::[a-z0-9._/-]+)+$", re.IGNORECASE)
14
+ _HTTP_SCHEMES = {"http", "https"}
15
+
16
+
17
+ def _looks_like_semver(value: str) -> bool:
18
+ return bool(_SEMVER_PATTERN.fullmatch(value.strip()))
19
+
20
+
21
+ def _non_empty_string(value: Any) -> bool:
22
+ return isinstance(value, str) and bool(value.strip())
23
+
24
+
25
+ def _domain_matches_audit(value: Any, audit_domain: str) -> bool:
26
+ if not _non_empty_string(value) or not audit_domain:
27
+ return False
28
+ candidate = value.strip().lower().rstrip(".")
29
+ parsed = urlparse(candidate if "://" in candidate else f"https://{candidate}")
30
+ hostname = (parsed.hostname or "").lower().rstrip(".")
31
+ normalized_audit_domain = audit_domain.lower().removeprefix("www.")
32
+ normalized_hostname = hostname.removeprefix("www.")
33
+ return normalized_hostname == normalized_audit_domain or normalized_hostname.endswith(
34
+ f".{normalized_audit_domain}"
35
+ )
36
+
37
+
38
+ def _entry_identifier(entry: dict[str, Any]) -> Any:
39
+ return entry.get("identifier") or entry.get("urn") or entry.get("id")
40
+
41
+
42
+ def _is_domain_anchored_urn(value: Any, audit_domain: str) -> bool:
43
+ if not _non_empty_string(value):
44
+ return False
45
+ identifier = value.strip()
46
+ if not _URN_AIR_PATTERN.fullmatch(identifier):
47
+ return False
48
+ if not audit_domain:
49
+ return True
50
+ publisher = identifier.split(":", 3)[2].lower().removeprefix("www.")
51
+ normalized_audit_domain = audit_domain.lower().removeprefix("www.")
52
+ return publisher == normalized_audit_domain or publisher.endswith(f".{normalized_audit_domain}")
53
+
54
+
55
+ def _is_timestamp(value: Any) -> bool:
56
+ if not _non_empty_string(value):
57
+ return False
58
+ candidate = value.strip()
59
+ try:
60
+ datetime.fromisoformat(candidate.replace("Z", "+00:00"))
61
+ except ValueError:
62
+ return False
63
+ return True
64
+
65
+
66
+ def _has_capability_metadata(entry: dict[str, Any]) -> bool:
67
+ for key in ("capabilities", "tags"):
68
+ value = entry.get(key)
69
+ if isinstance(value, list) and any(_non_empty_string(item) for item in value):
70
+ return True
71
+ return False
72
+
73
+
74
+ def _check_entry(entry: Any, audit_domain: str) -> list[str]:
75
+ if not isinstance(entry, dict):
76
+ return ["entry is not a JSON object"]
77
+
78
+ issues: list[str] = []
79
+ identifier = _entry_identifier(entry)
80
+ if not _non_empty_string(identifier):
81
+ issues.append("entry is missing `identifier`")
82
+ elif not _is_domain_anchored_urn(identifier, audit_domain):
83
+ issues.append(f"entry identifier `{identifier}` is not a domain-anchored `urn:air` value")
84
+
85
+ if not _non_empty_string(entry.get("displayName")):
86
+ issues.append("entry is missing `displayName`")
87
+ if not _non_empty_string(entry.get("mediaType") or entry.get("type")):
88
+ issues.append("entry is missing `mediaType`")
89
+
90
+ has_url = "url" in entry
91
+ has_data = "data" in entry
92
+ if has_url == has_data:
93
+ issues.append("entry must declare exactly one of `url` or `data`")
94
+ elif has_url:
95
+ if not _non_empty_string(entry.get("url")):
96
+ issues.append("entry `url` must be a non-empty HTTP(S) URL")
97
+ else:
98
+ parsed_url = urlparse(entry["url"].strip())
99
+ if parsed_url.scheme.lower() not in _HTTP_SCHEMES or not parsed_url.netloc:
100
+ issues.append("entry `url` must be an absolute HTTP(S) URL")
101
+ elif not isinstance(entry.get("data"), dict):
102
+ issues.append("entry `data` must be an embedded JSON object")
103
+
104
+ if not _non_empty_string(entry.get("description")):
105
+ issues.append("entry is missing `description`")
106
+ if not _has_capability_metadata(entry):
107
+ issues.append("entry is missing non-empty `capabilities` or `tags`")
108
+
109
+ queries = entry.get("representativeQueries")
110
+ if not isinstance(queries, list) or not queries or not all(_non_empty_string(query) for query in queries):
111
+ issues.append("entry is missing non-empty `representativeQueries`")
112
+
113
+ updated = entry.get("updated") or entry.get("updatedAt") or entry.get("lastUpdated")
114
+ if not _is_timestamp(updated):
115
+ issues.append("entry is missing an ISO 8601 `updated` timestamp")
116
+
117
+ return issues
118
+
119
+
120
+ def _result(
121
+ valid: bool,
122
+ spec_version: str | None,
123
+ entry_count: int,
124
+ has_trust_manifest: bool,
125
+ issues: list[str],
126
+ ) -> dict[str, Any]:
127
+ return {
128
+ "valid": valid,
129
+ "spec_version": spec_version,
130
+ "entry_count": entry_count,
131
+ "has_trust_manifest": has_trust_manifest,
132
+ "issues": issues,
133
+ "sample_issues": issues[:5],
134
+ }
135
+
136
+
137
+ def ard_catalog_quality(text: str, audit_url: str | None = None) -> dict[str, Any]:
138
+ """Validate an ARD catalog body without network or provider calls."""
139
+ if not isinstance(text, str):
140
+ return _result(False, None, 0, False, ["ARD catalog body is not text"])
141
+
142
+ payload_size = len(text.encode("utf-8"))
143
+ if payload_size > _MAX_PAYLOAD_BYTES:
144
+ return _result(
145
+ False,
146
+ None,
147
+ 0,
148
+ False,
149
+ [f"ARD catalog payload exceeds the 500 KiB limit ({payload_size} bytes)"],
150
+ )
151
+ if not text.strip():
152
+ return _result(False, None, 0, False, ["ARD catalog body is empty"])
153
+
154
+ try:
155
+ catalog = json.loads(text)
156
+ except json.JSONDecodeError as exc:
157
+ return _result(False, None, 0, False, [f"ARD catalog is not valid JSON: {exc.msg}"])
158
+
159
+ if not isinstance(catalog, dict):
160
+ return _result(False, None, 0, False, ["ARD catalog root must be a JSON object"])
161
+
162
+ issues: list[str] = []
163
+ spec_version = catalog.get("specVersion")
164
+ if not _non_empty_string(spec_version):
165
+ issues.append("ARD catalog is missing `specVersion`")
166
+ spec_version_value = None
167
+ else:
168
+ spec_version_value = spec_version.strip()
169
+ if not _looks_like_semver(spec_version_value):
170
+ issues.append(f"ARD catalog `specVersion` `{spec_version_value}` is not semver-shaped")
171
+
172
+ audit_domain = ""
173
+ if audit_url:
174
+ audit_domain = (urlparse(audit_url).hostname or "").strip(".").lower()
175
+
176
+ host = catalog.get("host")
177
+ if not isinstance(host, dict):
178
+ issues.append("ARD catalog is missing `host` metadata")
179
+ else:
180
+ host_domain = host.get("domain") or host.get("hostname") or host.get("url")
181
+ if host_domain is None:
182
+ issues.append("ARD catalog host metadata is missing `domain`")
183
+ elif audit_domain and not _domain_matches_audit(host_domain, audit_domain):
184
+ issues.append(f"ARD catalog host domain `{host_domain}` does not match the audited host")
185
+ elif not audit_domain and not _non_empty_string(host_domain):
186
+ issues.append("ARD catalog host `domain` must be non-empty")
187
+
188
+ entries = catalog.get("entries")
189
+ if not isinstance(entries, list):
190
+ issues.append("ARD catalog is missing an `entries` list")
191
+ entry_count = 0
192
+ else:
193
+ entry_count = len(entries)
194
+ for index, entry in enumerate(entries):
195
+ issues.extend(f"entry[{index}]: {issue}" for issue in _check_entry(entry, audit_domain))
196
+
197
+ has_trust_manifest = "trustManifest" in catalog or (
198
+ isinstance(host, dict) and "trustManifest" in host
199
+ ) or any(isinstance(entry, dict) and "trustManifest" in entry for entry in entries or [])
200
+
201
+ return _result(not issues, spec_version_value, entry_count, has_trust_manifest, issues)
202
+
203
+
204
+ __all__ = ["ard_catalog_quality"]
backend/app/checks/bot_access.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from dataclasses import dataclass
3
+ from urllib.parse import urljoin, urlparse
4
+
5
+ from bs4 import BeautifulSoup
6
+
7
+ from app.audit_context import AuditContext
8
+ from app.crawler_registry import active_crawler_caveats, fetch_probe_names
9
+ from app.fetching import BOT_USER_AGENTS, BROWSER_USER_AGENT, FetchResult, fetch_url
10
+ from app.models import CheckResult
11
+
12
+ _MATRIX_BOTS = fetch_probe_names()
13
+
14
+ _BLOCK_SIGNATURES = (
15
+ "just a moment",
16
+ "checking your browser",
17
+ "cf-chl",
18
+ "cloudflare ray id",
19
+ "verify you are human",
20
+ "access denied",
21
+ "datadome",
22
+ "perimeterx",
23
+ "akamai bot manager",
24
+ )
25
+ # Substrings that indicate a generic anti-bot challenge page. The classic
26
+ # ``captcha`` substring is intentionally NOT in this list: contact forms and
27
+ # many legitimate pages embed Google reCAPTCHA ``<script src="…/recaptcha/api.js">``
28
+ # tags, which would otherwise produce a false-positive challenge page for every
29
+ # bot probe. CAPTCHA-style pages are matched separately against the page
30
+ # ``<title>`` only — see :func:`_has_captcha_title`.
31
+ _BODY_SCAN_LENGTH = 20000
32
+
33
+ # Stagger between bot probes so a multi-user-agent wave does not look like a
34
+ # coordinated attack to upstream WAFs. The previous behaviour fired all 9
35
+ # crawlers simultaneously via ``asyncio.gather``; one IP hitting the homepage
36
+ # with 9 different user agents at once reads as a brute-force scan and the
37
+ # WAF's rate-limit response is exactly the friction the probes are trying to
38
+ # measure. A paced sequence (0.5s gap between each, ~4.5s total for 9 probes)
39
+ # looks like ordinary bot traffic instead.
40
+ _STAGGER_DELAY = 0.5 # seconds between bot probes
41
+ # When a probe gets HTTP 429, wait this long before the single retry. The
42
+ # ``Retry-After`` header is the polite thing to honour, but we do not parse it
43
+ # here — a fixed delay keeps the check deterministic and easy to test.
44
+ _RETRY_DELAY = 2.0 # seconds before 429 retry
45
+
46
+
47
+ def _title_text(html: str) -> str:
48
+ """Extract just the text content of the first ``<title>`` element.
49
+
50
+ Returns an empty string if the document has no title or if parsing fails.
51
+ Used to confine ``captcha`` detection to the visible page title instead of
52
+ the full HTML body, so third-party script references do not trigger
53
+ false positives.
54
+ """
55
+ if not html:
56
+ return ""
57
+ try:
58
+ soup = BeautifulSoup(html, "lxml")
59
+ except Exception:
60
+ return ""
61
+ title_tag = soup.find("title")
62
+ if title_tag is None:
63
+ return ""
64
+ return title_tag.get_text(separator=" ", strip=True)
65
+
66
+
67
+ def _has_captcha_title(fetch: FetchResult) -> bool:
68
+ """Return True only when the page ``<title>`` mentions CAPTCHA.
69
+
70
+ Real CAPTCHA challenge pages always announce themselves in the title bar
71
+ ("reCAPTCHA", "Security check", "Are you a robot?", etc.). A reCAPTCHA
72
+ ``<script>`` tag embedded in a normal page does NOT affect the title, so
73
+ the body+header substring scan is not appropriate for ``captcha``.
74
+ """
75
+ title = _title_text(fetch.text).lower()
76
+ if not title:
77
+ return False
78
+ return "captcha" in title
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class RoutingSnapshot:
83
+ final_url: str
84
+ status_code: int | None
85
+ canonical_url: str | None
86
+ content_bytes: int
87
+ visible_words: int
88
+
89
+
90
+ def _visible_word_count(html: str) -> int:
91
+ soup = BeautifulSoup(html, "lxml")
92
+ for tag in soup(["script", "style", "head", "noscript"]):
93
+ tag.decompose()
94
+ return len(soup.get_text(separator=" ").split())
95
+
96
+
97
+ def _normalised_url(url: str) -> str:
98
+ parsed = urlparse(urljoin(url, ""))
99
+ return parsed._replace(fragment="", query="").geturl().rstrip("/")
100
+
101
+
102
+ def _display_url(url: str) -> str:
103
+ parsed = urlparse(url)
104
+ if not parsed.netloc:
105
+ return url[:120]
106
+ display = parsed.netloc + parsed.path.rstrip("/")
107
+ if parsed.query:
108
+ display += "?" + parsed.query
109
+ return display[:120]
110
+
111
+
112
+ def _canonical_url(fetch: FetchResult) -> str | None:
113
+ if not fetch.text:
114
+ return None
115
+ soup = BeautifulSoup(fetch.text, "lxml")
116
+ tag = soup.find("link", attrs={"rel": "canonical"})
117
+ if not tag:
118
+ return None
119
+ href = tag.get("href", "")
120
+ if not href:
121
+ return None
122
+ return _normalised_url(urljoin(fetch.final_url, href))
123
+
124
+
125
+ def _routing_snapshot(fetch: FetchResult) -> RoutingSnapshot:
126
+ return RoutingSnapshot(
127
+ final_url=_normalised_url(fetch.final_url),
128
+ status_code=fetch.status_code,
129
+ canonical_url=_canonical_url(fetch),
130
+ content_bytes=len(fetch.text.encode("utf-8")),
131
+ visible_words=_visible_word_count(fetch.text),
132
+ )
133
+
134
+
135
+ def _has_block_signature(fetch: FetchResult) -> bool:
136
+ """Return True if the response body or headers look like an anti-bot page.
137
+
138
+ Substring signatures in :data:`_BLOCK_SIGNATURES` are scanned against the
139
+ first ``_BODY_SCAN_LENGTH`` characters of the body plus the response header
140
+ values. ``captcha`` is intentionally NOT in that list — see
141
+ :func:`_has_captcha_title` for the title-only CAPTCHA detection path.
142
+ """
143
+ sample = (fetch.text[:_BODY_SCAN_LENGTH] + " " + " ".join(fetch.headers.values())).lower()
144
+ return any(signature in sample for signature in _BLOCK_SIGNATURES)
145
+
146
+
147
+ def _looks_like_challenge(
148
+ fetch: FetchResult,
149
+ *,
150
+ baseline: FetchResult | None = None,
151
+ ) -> bool:
152
+ """Return True if ``fetch`` looks like a challenge page for bots.
153
+
154
+ A response is treated as a challenge when **either**:
155
+
156
+ * The body / header substring scan in :func:`_has_block_signature` matches
157
+ a known anti-bot fingerprint; **or**
158
+ * The page ``<title>`` mentions CAPTCHA.
159
+
160
+ When ``baseline`` is provided and the baseline (browser) probe ALSO matches
161
+ on the same fingerprints, the finding is suppressed: the site serves the
162
+ same fingerprint to real browsers, so it is a site-wide pattern rather than
163
+ bot discrimination. The baseline comparison applies to the title-only
164
+ CAPTCHA check as well, because a site that literally puts ``captcha`` in
165
+ its title is not selectively blocking bots either.
166
+ """
167
+ body_match = _has_block_signature(fetch)
168
+ title_match = _has_captcha_title(fetch)
169
+ if not (body_match or title_match):
170
+ return False
171
+ if baseline is None:
172
+ return True
173
+ baseline_body = _has_block_signature(baseline)
174
+ baseline_title = _has_captcha_title(baseline)
175
+ # If the browser baseline carries the same challenge fingerprints, the
176
+ # site-wide response is the same for everyone — not a bot-only finding.
177
+ if body_match and baseline_body:
178
+ return False
179
+ if title_match and baseline_title:
180
+ return False
181
+ return True
182
+
183
+
184
+ def _blocked_reason(
185
+ fetch: FetchResult,
186
+ baseline_words: int,
187
+ *,
188
+ baseline: FetchResult | None = None,
189
+ ) -> str | None:
190
+ if fetch.error:
191
+ return "fetch error"
192
+ if fetch.status_code in {401, 403, 429, 503}:
193
+ return f"HTTP {fetch.status_code}"
194
+ if _looks_like_challenge(fetch, baseline=baseline):
195
+ return "challenge page"
196
+
197
+ words = _visible_word_count(fetch.text)
198
+ if baseline_words >= 80 and words < max(20, baseline_words * 0.25):
199
+ return f"thin response ({words} words vs {baseline_words} browser words)"
200
+ return None
201
+
202
+
203
+ def _probe_caveat() -> str:
204
+ return " ".join(active_crawler_caveats("fetch"))
205
+
206
+
207
+ def _format_bytes(byte_count: int) -> str:
208
+ if byte_count >= 1024 * 1024:
209
+ return f"{byte_count / (1024 * 1024):.1f} MB"
210
+ if byte_count >= 1024:
211
+ return f"{byte_count / 1024:.1f} KB"
212
+ return f"{byte_count} B"
213
+
214
+
215
+ def _large_ratio_difference(candidate: int, baseline: int, *, minimum_baseline: int) -> bool:
216
+ if baseline < minimum_baseline:
217
+ return False
218
+ return candidate < baseline * 0.6 or candidate > baseline * 1.6
219
+
220
+
221
+ def _routing_differences(
222
+ bot_name: str,
223
+ fetch: FetchResult,
224
+ baseline: RoutingSnapshot,
225
+ ) -> list[str]:
226
+ snapshot = _routing_snapshot(fetch)
227
+ differences: list[str] = []
228
+ if snapshot.status_code != baseline.status_code:
229
+ differences.append(
230
+ f"status {snapshot.status_code or 'error'} vs browser {baseline.status_code or 'error'}"
231
+ )
232
+
233
+ if snapshot.final_url != baseline.final_url:
234
+ differences.append(
235
+ f"final URL {_display_url(snapshot.final_url)} vs browser {_display_url(baseline.final_url)}"
236
+ )
237
+
238
+ if snapshot.canonical_url != baseline.canonical_url:
239
+ if snapshot.canonical_url and baseline.canonical_url:
240
+ differences.append(
241
+ "canonical "
242
+ f"{_display_url(snapshot.canonical_url)} vs browser {_display_url(baseline.canonical_url)}"
243
+ )
244
+ elif baseline.canonical_url:
245
+ differences.append("canonical missing vs browser canonical")
246
+ elif snapshot.canonical_url:
247
+ differences.append("canonical present only for bot response")
248
+
249
+ if _large_ratio_difference(snapshot.content_bytes, baseline.content_bytes, minimum_baseline=1024):
250
+ differences.append(
251
+ "body size "
252
+ f"{_format_bytes(snapshot.content_bytes)} vs browser {_format_bytes(baseline.content_bytes)}"
253
+ )
254
+
255
+ if _large_ratio_difference(snapshot.visible_words, baseline.visible_words, minimum_baseline=80):
256
+ differences.append(
257
+ f"visible words {snapshot.visible_words} vs browser {baseline.visible_words}"
258
+ )
259
+
260
+ return [f"{bot_name} ({'; '.join(differences)})"] if differences else []
261
+
262
+
263
+ def _routing_difference_detail(differences: list[str]) -> str:
264
+ if not differences:
265
+ return " No material browser-vs-bot routing differences were inferred from final URL, status, canonical, body size, or visible word count."
266
+ shown = differences[:5]
267
+ hidden_count = len(differences) - len(shown)
268
+ detail = " Inferred browser-vs-bot routing differences: " + "; ".join(shown)
269
+ if hidden_count:
270
+ detail += f"; {hidden_count} more"
271
+ return detail + "."
272
+
273
+
274
+ async def _probe_one_bot(url: str, user_agent: str) -> FetchResult:
275
+ """Fetch ``url`` as a single bot and retry HTTP 429 once after a delay.
276
+
277
+ The single retry uses the second response for scoring — the 429 itself is
278
+ discarded. If the retry also 429s (or returns any other blocking status),
279
+ that retry result is returned as-is so :func:`_blocked_reason` can score
280
+ it normally. ``asyncio.sleep`` is used between the initial probe and the
281
+ retry so the WAF gets real wall-clock breathing room.
282
+ """
283
+ fetch = await fetch_url(url, user_agent=user_agent)
284
+ if fetch.status_code == 429 and fetch.error is None:
285
+ await asyncio.sleep(_RETRY_DELAY)
286
+ retry_fetch = await fetch_url(url, user_agent=user_agent)
287
+ # Use the retry result for scoring regardless of its status. If the
288
+ # retry is still 429, _blocked_reason will count it as blocked.
289
+ return retry_fetch
290
+ return fetch
291
+
292
+
293
+ async def _probe_bots(
294
+ url: str,
295
+ bot_user_agents: dict[str, str],
296
+ matrix_bots: list[str],
297
+ *,
298
+ baseline_fetch: FetchResult,
299
+ baseline_snapshot: RoutingSnapshot,
300
+ baseline_words: int,
301
+ ) -> tuple[list[str], list[str], int]:
302
+ """Run the bot-access matrix probes serially with a stagger between each.
303
+
304
+ Replaces the previous ``asyncio.gather`` burst that fired all probes
305
+ simultaneously — see :data:`_STAGGER_DELAY` for the rationale.
306
+
307
+ Each probe gets a single 429 retry (see :func:`_probe_one_bot`). The
308
+ stagger applies only between successive initial probes; the retry sleep
309
+ happens inside the probe itself when a 429 is observed and does not push
310
+ the next bot's start time further out.
311
+
312
+ Returns ``(blocked, routing_differences, accessible_count)`` — the same
313
+ three values that :func:`check_bot_access` previously derived inline, so
314
+ the scoring / state logic in the caller stays identical.
315
+ """
316
+ blocked: list[str] = []
317
+ routing_differences: list[str] = []
318
+ accessible_count = 0
319
+ for index, bot_name in enumerate(matrix_bots):
320
+ if index > 0:
321
+ # Paced sequence instead of a simultaneous burst. The browser
322
+ # baseline fetch above is already sequential, so this is the only
323
+ # place the wave-pattern fix applies.
324
+ await asyncio.sleep(_STAGGER_DELAY)
325
+ fetch = await _probe_one_bot(url, bot_user_agents[bot_name])
326
+ reason = _blocked_reason(fetch, baseline_words, baseline=baseline_fetch)
327
+ if reason:
328
+ blocked.append(f"{bot_name} ({reason})")
329
+ else:
330
+ accessible_count += 1
331
+ routing_differences.extend(_routing_differences(bot_name, fetch, baseline_snapshot))
332
+ return blocked, routing_differences, accessible_count
333
+
334
+
335
+ async def check_bot_access(context: AuditContext) -> CheckResult:
336
+ """Compare access for common search and AI crawler user agents."""
337
+ browser_fetch = await fetch_url(context.url, user_agent=BROWSER_USER_AGENT)
338
+ baseline_fetch = browser_fetch if browser_fetch.ok else context.homepage
339
+ baseline_snapshot = _routing_snapshot(baseline_fetch)
340
+ baseline_words = baseline_snapshot.visible_words
341
+
342
+ blocked, routing_differences, accessible_count = await _probe_bots(
343
+ context.url,
344
+ BOT_USER_AGENTS,
345
+ _MATRIX_BOTS,
346
+ baseline_fetch=baseline_fetch,
347
+ baseline_snapshot=baseline_snapshot,
348
+ baseline_words=baseline_words,
349
+ )
350
+ score = round(accessible_count / len(_MATRIX_BOTS) * 6)
351
+
352
+ if not blocked:
353
+ state = "pass"
354
+ finding = (
355
+ "Tracked search and AI crawler user-agent requests from MachineRead received "
356
+ "accessible homepage responses comparable to a normal browser request."
357
+ )
358
+ fix = "No action needed. Keep bot traffic rate-limited rather than hard-blocked."
359
+ elif accessible_count:
360
+ state = "partial"
361
+ finding = (
362
+ "Some tracked bot user-agent requests from MachineRead appear blocked or challenged: "
363
+ + "; ".join(blocked)
364
+ + ". This is strong evidence of friction for generic agents, but actual "
365
+ "verified search crawlers may be treated differently by IP verification rules."
366
+ )
367
+ fix = (
368
+ "Review WAF and bot rules for the listed agents. Prefer explicit allows, "
369
+ "sensible rate limits, and Retry-After responses over CAPTCHA or hard blocks."
370
+ )
371
+ else:
372
+ state = "fail"
373
+ finding = (
374
+ "All tracked bot user-agent requests from MachineRead appear blocked or challenged. "
375
+ "This indicates high friction for generic agents, but it is not proof that "
376
+ "Googlebot or Bingbot from verified crawler IPs are blocked."
377
+ )
378
+ fix = (
379
+ "Create an allowlisted path for legitimate crawlers and agents, then rate-limit "
380
+ "abuse without hiding the public content."
381
+ )
382
+
383
+ finding += _routing_difference_detail(routing_differences)
384
+ finding += " Probe caveat: " + _probe_caveat()
385
+
386
+ return CheckResult(
387
+ pillar="scrapability",
388
+ check_name="bot_access",
389
+ label="MachineRead Bot Fetch Access",
390
+ state=state,
391
+ evidence_level="inferred",
392
+ score=score,
393
+ max_score=6,
394
+ finding=finding,
395
+ fix=fix,
396
+ effort="medium",
397
+ )