Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
feat(v2): Checkpoint 3 — technical/CWV depth (Phase C)
Daniel2d81314aea12
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 95b28b6..4fa6c1e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -62,7 +62,11 @@ jobs:python3 -m py_compile scripts/content_verify.pypython3 -m py_compile scripts/domain_history.pypython3 -m py_compile scripts/seo_updates.py- echo "All 39 scripts passed syntax check"+ python3 -m py_compile scripts/preload_check.py+ python3 -m py_compile scripts/indexnow_submit.py+ python3 -m py_compile scripts/lcp_subparts.py+ python3 -m py_compile scripts/unlighthouse_run.py+ echo "All 43 scripts passed syntax check"test:name: Test suite (manifests + sync_flow)diff --git a/scripts/indexnow_submit.py b/scripts/indexnow_submit.pynew file mode 100644index 0000000..b46ff58--- /dev/null+++ b/scripts/indexnow_submit.py@@ -0,0 +1,247 @@+#!/usr/bin/env python3+"""+IndexNow submitter.++POSTs a list of URLs to the IndexNow open API (Bing, Yandex, Seznam,+Naver consume the same endpoint). Google does NOT consume IndexNow as+of 2026 per Gary Illyes (multiple Search Off the Record episodes), so+this is specifically a non-Google indexing signal.++Setup+=====+1. Generate a 32+ character host key. Any random string works.+2. Place the key in a file named ``<key>.txt`` at the root of your+ site, served at ``https://example.com/<key>.txt`` — the file body+ is the key itself. IndexNow crawls this once to prove host ownership.+3. Pass the key + the key-location URL to this script (or set the+ ``INDEXNOW_KEY`` and ``INDEXNOW_KEY_LOCATION`` env vars).++Usage+=====+::++ python scripts/indexnow_submit.py \\+ --host example.com \\+ --key abcd1234… \\+ --key-location https://example.com/abcd1234.txt \\+ --urls https://example.com/new-post https://example.com/updated-page++ # Or read URLs from a file (one per line):+ python scripts/indexnow_submit.py \\+ --host example.com --key abcd1234… --key-location https://… \\+ --urls-file changed.txt++Spec: https://www.indexnow.org/documentation+"""++from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path+from typing import Iterable++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+from url_safety import URLSafetyError, safe_requests_get, validate_url_strict # noqa: E402++# The umbrella endpoint forwards to every participating engine. Individual+# engine endpoints exist (bing.com/IndexNow, yandex.com/indexnow, etc.) but+# api.indexnow.org dispatches automatically — one POST covers all four.+INDEXNOW_ENDPOINT = "https://api.indexnow.org/indexnow"+++def submit(+ host: str,+ key: str,+ key_location: str,+ urls: Iterable[str],+ *,+ timeout: int = 30,+) -> dict:+ """Submit a batch of URLs to IndexNow. Returns a result dict."""+ import requests++ url_list = list(urls)+ if not url_list:+ return {"ok": False, "error": "empty url list", "submitted": 0}+ if len(url_list) > 10000:+ return {"ok": False, "error": "IndexNow spec caps batch at 10000 URLs", "submitted": 0}+ if len(key) < 8 or len(key) > 128:+ return {"ok": False, "error": "key must be 8-128 chars per IndexNow spec",+ "submitted": 0}++ # Every submitted URL must belong to the declared host. IndexNow rejects+ # cross-host submissions to prevent abuse.+ bad = [u for u in url_list if host not in u]+ if bad:+ return {+ "ok": False,+ "error": f"{len(bad)} URLs don't contain host {host!r}",+ "examples": bad[:3],+ "submitted": 0,+ }++ # Validate every submitted URL through url_safety so we don't ship+ # private-IP links to the API by accident.+ for u in url_list:+ try:+ validate_url_strict(u)+ except URLSafetyError as exc:+ return {"ok": False, "error": f"url_safety refused {u!r}: {exc}",+ "submitted": 0}++ payload = {+ "host": host,+ "key": key,+ "keyLocation": key_location,+ "urlList": url_list,+ }++ try:+ resp = requests.post(+ INDEXNOW_ENDPOINT,+ json=payload,+ timeout=timeout,+ headers={"Content-Type": "application/json; charset=utf-8"},+ )+ except requests.exceptions.RequestException as exc:+ return {"ok": False, "error": f"HTTP error: {exc}", "submitted": 0}++ return {+ "ok": resp.status_code in (200, 202),+ "status_code": resp.status_code,+ "submitted": len(url_list),+ "endpoint": INDEXNOW_ENDPOINT,+ "engines": ["Bing", "Yandex", "Seznam", "Naver"],+ "response_body_preview": (resp.text or "")[:200],+ }+++def verify_key_published(+ host: str, key: str, key_location: str+) -> dict:+ """Fetch the published key file and confirm it matches.++ IndexNow requires the key to be retrievable at the keyLocation URL.+ Missing or wrong content silently rejects every later submission, so+ this pre-flight catches the common ownership-setup mistake.+ """+ try:+ resp = safe_requests_get(key_location, timeout=15)+ except URLSafetyError as exc:+ return {"ok": False, "error": f"url_safety: {exc}"}+ except Exception as exc: # noqa: BLE001 — surface every transport error verbatim+ return {"ok": False, "error": f"fetch failed: {exc}"}+ if resp.status_code != 200:+ return {"ok": False, "status_code": resp.status_code,+ "error": "keyLocation returned non-200"}+ if resp.text.strip() != key:+ return {+ "ok": False,+ "status_code": 200,+ "error": "keyLocation contents do not match key",+ "expected_length": len(key),+ "actual_length": len(resp.text.strip()),+ }+ if host not in key_location:+ return {"ok": False, "error": "keyLocation host does not match declared host"}+ return {"ok": True, "status_code": 200}+++def _load_urls(arg_urls: list[str], urls_file: str | None) -> list[str]:+ items: list[str] = list(arg_urls or [])+ if urls_file:+ for line in Path(urls_file).read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if line and not line.startswith("#"):+ items.append(line)+ return items+++def main() -> int:+ parser = argparse.ArgumentParser(description="Submit URLs to IndexNow.")+ parser.add_argument(+ "--host", required=True,+ help="Site host (without scheme), e.g. example.com",+ )+ parser.add_argument(+ "--key",+ default=os.environ.get("INDEXNOW_KEY"),+ help="IndexNow host key (or set INDEXNOW_KEY).",+ )+ parser.add_argument(+ "--key-location",+ default=os.environ.get("INDEXNOW_KEY_LOCATION"),+ help="Public URL that serves the key file "+ "(or set INDEXNOW_KEY_LOCATION).",+ )+ parser.add_argument(+ "--urls", nargs="*", default=[],+ help="URLs to submit (space-separated).",+ )+ parser.add_argument(+ "--urls-file",+ help="File path with one URL per line (lines starting with # ignored).",+ )+ parser.add_argument(+ "--verify-only", action="store_true",+ help="Check that the key file is published correctly; do not submit.",+ )+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args()++ if not args.key or not args.key_location:+ print("Error: --key and --key-location required (or set env vars).",+ file=sys.stderr)+ return 2++ if args.verify_only:+ result = verify_key_published(args.host, args.key, args.key_location)+ if args.json:+ json.dump(result, sys.stdout, indent=2)+ sys.stdout.write("\n")+ else:+ status = "OK" if result["ok"] else "FAIL"+ print(f"Key verification: {status}")+ if "error" in result:+ print(f" {result['error']}")+ return 0 if result["ok"] else 1++ urls = _load_urls(args.urls, args.urls_file)+ if not urls:+ print("Error: pass at least one URL via --urls or --urls-file.",+ file=sys.stderr)+ return 2++ # Pre-flight: verify key publication before sending the batch.+ verify = verify_key_published(args.host, args.key, args.key_location)+ if not verify["ok"]:+ print(f"Pre-flight failed: {verify.get('error', 'unknown')}",+ file=sys.stderr)+ if args.json:+ json.dump({"ok": False, "verify": verify}, sys.stdout, indent=2)+ sys.stdout.write("\n")+ return 1++ result = submit(args.host, args.key, args.key_location, urls)+ if args.json:+ json.dump(result, sys.stdout, indent=2)+ sys.stdout.write("\n")+ else:+ status = "OK" if result["ok"] else "FAIL"+ print(f"IndexNow: {status} (status={result.get('status_code')})")+ print(f" Submitted: {result['submitted']} URLs to {result['endpoint']}")+ if result.get("engines"):+ print(f" Engines: {', '.join(result['engines'])}")+ if not result["ok"]:+ print(f" Error: {result.get('error', 'see response_body_preview')}")++ return 0 if result["ok"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/lcp_subparts.py b/scripts/lcp_subparts.pynew file mode 100644index 0000000..57e1146--- /dev/null+++ b/scripts/lcp_subparts.py@@ -0,0 +1,207 @@+#!/usr/bin/env python3+"""+LCP subparts breakdown via CrUX API.++Since 2024 CrUX has exposed the four LCP sub-metrics:+ - largest_contentful_paint_image_time_to_first_byte+ - largest_contentful_paint_image_resource_load_delay+ - largest_contentful_paint_image_resource_load_duration+ - largest_contentful_paint_image_element_render_delay++These let you decompose a slow LCP into network, scheduling, fetch,+and render phases — turning "your LCP is 4.2s" into "your TTFB is 1.1s+and your render delay is 2.4s, fix server response and the image+preload sequence". Per the gap analysis, this is the single most+actionable upgrade to claude-seo's CWV reporting.++Usage::++ python scripts/lcp_subparts.py https://example.com/+ python scripts/lcp_subparts.py https://example.com/ --form-factor PHONE --json++Requires the same Google API key used by ``scripts/crux_history.py``.+"""++from __future__ import annotations++import argparse+import json+import os+import sys++import urllib.request+import urllib.error++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+from url_safety import URLSafetyError, validate_url_strict # noqa: E402+from google_auth import get_api_key # noqa: E402+++CRUX_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryRecord"+++_LCP_SUBPART_METRICS = [+ "largest_contentful_paint_image_time_to_first_byte",+ "largest_contentful_paint_image_resource_load_delay",+ "largest_contentful_paint_image_resource_load_duration",+ "largest_contentful_paint_image_element_render_delay",+]+++def _query_crux(url: str, form_factor: str, api_key: str) -> dict:+ payload = {+ "url": url,+ "formFactor": form_factor,+ "metrics": _LCP_SUBPART_METRICS + ["largest_contentful_paint"],+ }+ body = json.dumps(payload).encode("utf-8")+ request = urllib.request.Request(+ f"{CRUX_ENDPOINT}?key={api_key}",+ data=body,+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(request, timeout=30) as resp:+ return json.loads(resp.read().decode("utf-8"))+ except urllib.error.HTTPError as exc:+ return {+ "error": f"CrUX HTTP {exc.code}: {exc.read().decode('utf-8', 'replace')}"+ }+ except urllib.error.URLError as exc:+ return {"error": f"CrUX request failed: {exc.reason}"}+++def _percentile(metric: dict) -> float | None:+ p = metric.get("percentiles", {}).get("p75")+ if p is None:+ return None+ try:+ return float(p)+ except (TypeError, ValueError):+ return None+++def analyse(url: str, form_factor: str = "PHONE") -> dict:+ try:+ url, _ = validate_url_strict(url)+ except URLSafetyError as exc:+ return {"error": f"url_safety: {exc}"}++ api_key = get_api_key()+ if not api_key:+ return {+ "error": "Google API key not configured. "+ "Run `python scripts/google_auth.py --setup`.",+ }++ raw = _query_crux(url, form_factor, api_key)+ if "error" in raw:+ return raw++ metrics = raw.get("record", {}).get("metrics", {})+ breakdown: dict[str, float | None] = {}+ for key in _LCP_SUBPART_METRICS:+ m = metrics.get(key)+ breakdown[key] = _percentile(m) if m else None++ overall_lcp = _percentile(metrics.get("largest_contentful_paint", {})) \+ if metrics.get("largest_contentful_paint") else None++ # Identify the dominant subpart. "Dominant" = subpart that contributes+ # >40% of overall LCP, which is where remediation effort pays back.+ dominant: list[dict] = []+ if overall_lcp:+ for key, val in breakdown.items():+ if val is None:+ continue+ share = val / overall_lcp+ if share >= 0.40:+ dominant.append({"metric": key, "p75_ms": val,+ "share": round(share, 2)})++ recommendations: list[str] = []+ for d in dominant:+ if d["metric"].endswith("time_to_first_byte"):+ recommendations.append(+ "TTFB dominates LCP. Check origin response time, server-side "+ "compute, CDN edge cache hit rate. Aim for TTFB < 0.8s."+ )+ elif d["metric"].endswith("resource_load_delay"):+ recommendations.append(+ "Resource load delay dominates. The LCP element is discovered "+ "late; preload the hero image with fetchpriority=high or move "+ "it ahead of blocking resources."+ )+ elif d["metric"].endswith("resource_load_duration"):+ recommendations.append(+ "Resource load duration dominates. The LCP image is large. "+ "Serve responsive sizes (srcset), modern formats (AVIF/WebP), "+ "and add async decoding hints."+ )+ elif d["metric"].endswith("element_render_delay"):+ recommendations.append(+ "Element render delay dominates. The element is loaded but "+ "painting is blocked. Reduce render-blocking CSS/JS above the "+ "fold and avoid font-blocking layout shifts."+ )++ return {+ "url": url,+ "form_factor": form_factor,+ "p75_lcp_ms": overall_lcp,+ "subparts_p75_ms": breakdown,+ "dominant_subparts": dominant,+ "recommendations": recommendations,+ "raw": raw,+ }+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Decompose LCP into its four subparts via CrUX."+ )+ parser.add_argument("url")+ parser.add_argument(+ "--form-factor",+ choices=("PHONE", "DESKTOP", "TABLET", "ALL_FORM_FACTORS"),+ default="PHONE",+ )+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args()++ result = analyse(args.url, args.form_factor)++ if "error" in result:+ print(f"Error: {result['error']}", file=sys.stderr)+ return 1++ if args.json:+ # Strip the noisy CrUX raw response from JSON output by default.+ out = {k: v for k, v in result.items() if k != "raw"}+ json.dump(out, sys.stdout, indent=2)+ sys.stdout.write("\n")+ else:+ print(f"URL: {result['url']}")+ print(f"Form factor: {result['form_factor']}")+ print(f"Overall p75 LCP: {result['p75_lcp_ms']} ms")+ print("Subparts (p75 ms):")+ for k, v in result["subparts_p75_ms"].items():+ label = k.replace("largest_contentful_paint_image_", "")+ print(f" {label:35s} {v if v is not None else '—'}")+ if result["dominant_subparts"]:+ print("\nDominant subparts (>= 40% of LCP):")+ for d in result["dominant_subparts"]:+ short = d["metric"].replace("largest_contentful_paint_image_", "")+ print(f" {short} = {d['p75_ms']:.0f} ms ({d['share']*100:.0f}%)")+ if result["recommendations"]:+ print("\nRecommendations:")+ for r in result["recommendations"]:+ print(f" - {r}")++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/preload_check.py b/scripts/preload_check.pynew file mode 100644index 0000000..a1ad80e--- /dev/null+++ b/scripts/preload_check.py@@ -0,0 +1,236 @@+#!/usr/bin/env python3+"""+Speculation Rules / bfcache / prerender2 / preload detector.++Per the v2 gap analysis, **LCP is the binding CWV constraint** as of+2025: 77% of mobile pages pass INP, only 62% pass LCP, and 48% pass+all three. The fastest large LCP win available without a content+rewrite is to wire up **bfcache** and **Speculation Rules** so the+next-navigation paint is effectively instant.++This script audits a page's HTML and response headers for the four+preload mechanisms Google rewards in 2025-2026:++ - ``<script type="speculationrules">`` blocks (Chrome 121+)+ - ``Speculation-Rules`` HTTP response header (Chrome 122+)+ - ``<link rel="preload" as="…">`` (legacy but still useful for LCP)+ - ``<link rel="prerender" href="…">`` (deprecated; flag for migration)+ - bfcache hints: ``Cache-Control: no-store`` removed, no+ ``unload`` listeners, no permission-prompting APIs.++The script does NOT measure bfcache eligibility from JS; that requires+a headless browser run with the ``NotRestoredReasons`` API. Instead,+it surfaces the easy static signals so an audit can quickly identify+high-value fixes.++Result JSON::++ {+ "url": "<final URL>",+ "speculation_rules": {+ "inline_blocks": <int>,+ "header_present": <bool>,+ "actions": ["prefetch", "prerender", …]+ },+ "preload_hints": <int>,+ "prerender_links": <int>, # deprecated rel=prerender count+ "bfcache_signals": {+ "cache_control_no_store": <bool>,+ "unload_listener": <bool>,+ "beforeunload_listener": <bool>+ },+ "lcp_resource_hints": {+ "preload_lcp_candidate": <bool>,+ "fetchpriority_high": <int>+ },+ "score": 0..100,+ "recommendations": ["…"]+ }+"""++from __future__ import annotations++import argparse+import json+import os+import re+import sys+from typing import Optional++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+from url_safety import URLSafetyError, safe_requests_get # noqa: E402+++_SPECULATION_BLOCK_RE = re.compile(+ r'<script\b[^>]*\btype\s*=\s*["\']speculationrules["\'][^>]*>(?P<body>.*?)</script>',+ re.IGNORECASE | re.DOTALL,+)+_PRELOAD_LINK_RE = re.compile(+ r'<link\b[^>]*\brel\s*=\s*["\']preload["\'][^>]*>', re.IGNORECASE,+)+_PRERENDER_LINK_RE = re.compile(+ r'<link\b[^>]*\brel\s*=\s*["\']prerender["\'][^>]*>', re.IGNORECASE,+)+_FETCHPRIORITY_HIGH_RE = re.compile(+ r'\bfetchpriority\s*=\s*["\']high["\']', re.IGNORECASE,+)+_LCP_IMG_HINT_RE = re.compile(+ r'<(?:img|video|source)\b[^>]*\bfetchpriority\s*=\s*["\']high["\']',+ re.IGNORECASE,+)+_UNLOAD_LISTENER_RE = re.compile(+ r'\b(?:addEventListener|on)\s*\(\s*["\']?unload["\']?', re.IGNORECASE,+)+_BEFOREUNLOAD_LISTENER_RE = re.compile(+ r'\b(?:addEventListener|on)\s*\(\s*["\']?beforeunload["\']?', re.IGNORECASE,+)+++def _extract_speculation_actions(body: str) -> list[str]:+ """Pull the unique 'action' field values out of a speculationrules JSON."""+ actions: set[str] = set()+ try:+ payload = json.loads(body.strip())+ except json.JSONDecodeError:+ return []+ for action_kind in ("prefetch", "prerender"):+ if isinstance(payload.get(action_kind), list):+ actions.add(action_kind)+ return sorted(actions)+++def analyse(html: str, headers: Optional[dict] = None) -> dict:+ headers = headers or {}+ speculation_blocks = list(_SPECULATION_BLOCK_RE.finditer(html))+ actions: set[str] = set()+ for m in speculation_blocks:+ for a in _extract_speculation_actions(m.group("body")):+ actions.add(a)+ speculation_header = "speculation-rules" in {k.lower() for k in headers}++ preload_count = len(_PRELOAD_LINK_RE.findall(html))+ prerender_count = len(_PRERENDER_LINK_RE.findall(html))+ fetchpriority_count = len(_FETCHPRIORITY_HIGH_RE.findall(html))+ lcp_img_hint = bool(_LCP_IMG_HINT_RE.search(html))++ cc_value = ""+ for key, value in headers.items():+ if key.lower() == "cache-control":+ cc_value = value or ""+ break+ cache_control_no_store = "no-store" in cc_value.lower()++ has_unload = bool(_UNLOAD_LISTENER_RE.search(html))+ has_beforeunload = bool(_BEFOREUNLOAD_LISTENER_RE.search(html))++ # Score: 25 pts each for speculation rules, preload-with-LCP hint,+ # absence of bfcache-killers, and the absence of deprecated prerender.+ score = 0+ recs: list[str] = []+ if speculation_blocks or speculation_header:+ score += 25+ else:+ recs.append(+ "Add <script type=\"speculationrules\"> for prefetch+prerender on "+ "top user-paths. Saves entire next-navigation paint cost."+ )++ if lcp_img_hint:+ score += 25+ else:+ recs.append(+ "Mark the LCP hero image with fetchpriority=\"high\" so the "+ "browser preloads it ahead of other resources."+ )++ if not cache_control_no_store and not has_unload:+ score += 25+ else:+ if cache_control_no_store:+ recs.append(+ "Cache-Control: no-store disqualifies the page from bfcache. "+ "Remove it or scope it to authenticated routes only."+ )+ if has_unload:+ recs.append(+ "An unload listener disqualifies the page from bfcache. "+ "Switch to pagehide or visibilitychange."+ )++ if prerender_count == 0:+ score += 25+ else:+ recs.append(+ f"Found {prerender_count} <link rel=\"prerender\"> (deprecated). "+ "Migrate to speculation rules (rel=prerender was sunset in Chrome 120)."+ )++ return {+ "speculation_rules": {+ "inline_blocks": len(speculation_blocks),+ "header_present": speculation_header,+ "actions": sorted(actions),+ },+ "preload_hints": preload_count,+ "prerender_links": prerender_count,+ "bfcache_signals": {+ "cache_control_no_store": cache_control_no_store,+ "unload_listener": has_unload,+ "beforeunload_listener": has_beforeunload,+ },+ "lcp_resource_hints": {+ "preload_lcp_candidate": lcp_img_hint,+ "fetchpriority_high": fetchpriority_count,+ },+ "score": score,+ "recommendations": recs,+ }+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Audit Speculation Rules, bfcache, prerender, and LCP "+ "preload signals on a single URL."+ )+ parser.add_argument("url")+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args()++ try:+ resp = safe_requests_get(args.url, timeout=20, allow_redirects=True)+ except URLSafetyError as exc:+ print(f"Error: url_safety: {exc}", file=sys.stderr)+ return 2++ result = {"url": resp.url, **analyse(resp.text, dict(resp.headers))}++ if args.json:+ json.dump(result, sys.stdout, indent=2)+ sys.stdout.write("\n")+ else:+ print(f"URL: {result['url']}")+ print(f"Score: {result['score']}/100")+ sr = result["speculation_rules"]+ print(f" Speculation Rules: blocks={sr['inline_blocks']} "+ f"header={sr['header_present']} actions={sr['actions']}")+ print(f" Preload hints: {result['preload_hints']}")+ print(f" Deprecated prerender: {result['prerender_links']}")+ bf = result["bfcache_signals"]+ print(f" bfcache killers: no-store={bf['cache_control_no_store']} "+ f"unload={bf['unload_listener']} "+ f"beforeunload={bf['beforeunload_listener']}")+ lr = result["lcp_resource_hints"]+ print(f" LCP preload: marked={lr['preload_lcp_candidate']} "+ f"fetchpriority=high count={lr['fetchpriority_high']}")+ if result["recommendations"]:+ print("Recommendations:")+ for r in result["recommendations"]:+ print(f" - {r}")++ return 0 if result["score"] >= 75 else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unlighthouse_run.py b/scripts/unlighthouse_run.pynew file mode 100644index 0000000..4fdae67--- /dev/null+++ b/scripts/unlighthouse_run.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""+Thin wrapper around the Unlighthouse CLI (https://unlighthouse.dev).++Unlighthouse is an MIT-licensed OSS Lighthouse runner that crawls an+entire site and outputs a single aggregate report. It's the closest+free-tier equivalent to running PageSpeed against every URL on a site+and aggregating the results — a workflow PSI's API quota does not+support without a paid Google Cloud bill.++This wrapper:+ - Validates the target via url_safety before any subprocess starts.+ - Invokes ``npx --yes unlighthouse-cli@^0.13 …`` with sensible+ defaults (mobile form factor, 8 parallel workers, JSON output).+ - Captures the JSON summary the CLI writes and returns it parsed+ so claude-seo agents can ingest the result without re-running+ Lighthouse.++Prerequisites+=============+Node.js 18+ available on ``$PATH``. The first run downloads+unlighthouse-cli; subsequent runs use the npx cache.++Usage::++ python scripts/unlighthouse_run.py https://example.com+ python scripts/unlighthouse_run.py https://example.com --json+ python scripts/unlighthouse_run.py https://example.com --device desktop --max-routes 50+"""++from __future__ import annotations++import argparse+import json+import os+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+from url_safety import URLSafetyError, validate_url_strict # noqa: E402+++UNLIGHTHOUSE_PIN = "unlighthouse-cli@^0.13"+++def _check_node() -> str | None:+ """Return None if Node is OK, else an error message."""+ npx = shutil.which("npx")+ if not npx:+ return ("npx not found on PATH. Install Node.js 18+ "+ "(https://nodejs.org) and re-run.")+ return None+++def run(+ target: str,+ *,+ device: str = "mobile",+ max_routes: int | None = 200,+ output_dir: str | None = None,+ timeout: int = 600,+) -> dict:+ try:+ target, _ = validate_url_strict(target)+ except URLSafetyError as exc:+ return {"ok": False, "error": f"url_safety: {exc}"}++ node_err = _check_node()+ if node_err:+ return {"ok": False, "error": node_err}++ out_dir = Path(output_dir) if output_dir else Path(tempfile.mkdtemp(+ prefix="claude-seo-unlighthouse-"))+ out_dir.mkdir(parents=True, exist_ok=True)++ cmd = [+ "npx", "--yes", "--package", UNLIGHTHOUSE_PIN, "unlighthouse-ci",+ "--site", target,+ "--device", device,+ "--output-path", str(out_dir),+ # Reasonable defaults for a one-shot audit; callers can override.+ "--build-static-files",+ ]+ if max_routes is not None:+ cmd.extend(["--scanner", json.dumps({"maxRoutes": max_routes})])++ try:+ proc = subprocess.run(+ cmd, capture_output=True, text=True, timeout=timeout, check=False,+ )+ except subprocess.TimeoutExpired:+ return {"ok": False, "error": f"unlighthouse timed out after {timeout}s",+ "output_dir": str(out_dir)}+ except FileNotFoundError as exc:+ return {"ok": False, "error": f"npx invocation failed: {exc}"}++ summary_path = out_dir / "ci-result.json"+ summary: dict = {}+ if summary_path.is_file():+ try:+ summary = json.loads(summary_path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ return {"ok": False, "error": f"ci-result.json invalid JSON: {exc}",+ "output_dir": str(out_dir)}++ return {+ "ok": proc.returncode == 0,+ "exit_code": proc.returncode,+ "target": target,+ "output_dir": str(out_dir),+ "summary": summary,+ "stdout_tail": proc.stdout[-2000:] if proc.stdout else "",+ "stderr_tail": proc.stderr[-2000:] if proc.stderr else "",+ }+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Run Unlighthouse (multi-page Lighthouse) on a site."+ )+ parser.add_argument("target", help="Site URL to crawl (https://example.com).")+ parser.add_argument(+ "--device", choices=("mobile", "desktop"), default="mobile",+ )+ parser.add_argument(+ "--max-routes", type=int, default=200,+ help="Cap the crawl at N URLs (default 200).",+ )+ parser.add_argument(+ "--output-dir", help="Directory for the HTML/JSON report (default temp).",+ )+ parser.add_argument(+ "--timeout", type=int, default=600,+ help="Subprocess timeout in seconds (default 600).",+ )+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args()++ result = run(+ args.target,+ device=args.device,+ max_routes=args.max_routes,+ output_dir=args.output_dir,+ timeout=args.timeout,+ )++ if args.json:+ json.dump(result, sys.stdout, indent=2)+ sys.stdout.write("\n")+ else:+ status = "OK" if result["ok"] else "FAIL"+ print(f"Unlighthouse: {status}")+ print(f" Target: {result.get('target', args.target)}")+ print(f" Output dir: {result.get('output_dir')}")+ if result.get("error"):+ print(f" Error: {result['error']}")+ elif result.get("summary"):+ scores = result["summary"].get("scores") or result["summary"].get("score") or {}+ if scores:+ for k, v in scores.items():+ print(f" {k:14s} {v}")++ return 0 if result["ok"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_technical_depth.py b/tests/test_technical_depth.pynew file mode 100644index 0000000..5896fbf--- /dev/null+++ b/tests/test_technical_depth.py@@ -0,0 +1,175 @@+"""+Tests for the v2 Checkpoint 3 technical-depth scripts.++Coverage:+ scripts/preload_check.py — Speculation Rules / bfcache / preload+ scripts/indexnow_submit.py — payload validation + key verification+ scripts/lcp_subparts.py — pure SSRF guard + result-shape (no live CrUX)+ scripts/unlighthouse_run.py — SSRF guard + Node-availability check++lcp_subparts and unlighthouse are heavy network/process integrations;+we test their non-network paths only. Real-API integration is+deferred to manual smoke tests.+"""++from __future__ import annotations++import os+import sys+from unittest.mock import patch++import pytest++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++import preload_check # noqa: E402+import indexnow_submit # noqa: E402+import lcp_subparts # noqa: E402+import unlighthouse_run # noqa: E402+++# ---------------------------------------------------------------------------+# preload_check+# ---------------------------------------------------------------------------+++def test_preload_detects_speculation_rules_inline_block() -> None:+ html = '<script type="speculationrules">{"prefetch":[{"urls":["/next"]}]}</script>'+ result = preload_check.analyse(html, {})+ assert result["speculation_rules"]["inline_blocks"] == 1+ assert "prefetch" in result["speculation_rules"]["actions"]+++def test_preload_detects_speculation_rules_header() -> None:+ result = preload_check.analyse("", {"Speculation-Rules": "/rules.json"})+ assert result["speculation_rules"]["header_present"] is True+++def test_preload_detects_deprecated_prerender_link() -> None:+ html = '<link rel="prerender" href="/next">'+ result = preload_check.analyse(html, {})+ assert result["prerender_links"] == 1+ assert any("deprecated" in r.lower() for r in result["recommendations"])+++def test_preload_detects_bfcache_killer_no_store() -> None:+ result = preload_check.analyse("<html></html>", {"Cache-Control": "no-store"})+ assert result["bfcache_signals"]["cache_control_no_store"] is True+ assert any("no-store" in r for r in result["recommendations"])+++def test_preload_detects_bfcache_killer_unload_listener() -> None:+ html = "<script>addEventListener('unload', () => {});</script>"+ result = preload_check.analyse(html, {})+ assert result["bfcache_signals"]["unload_listener"] is True+++def test_preload_detects_lcp_fetchpriority_high() -> None:+ html = '<img src="/hero.webp" fetchpriority="high">'+ result = preload_check.analyse(html, {})+ assert result["lcp_resource_hints"]["preload_lcp_candidate"] is True+ assert result["lcp_resource_hints"]["fetchpriority_high"] >= 1+++def test_preload_score_100_on_well_optimised_page() -> None:+ html = (+ '<script type="speculationrules">{"prefetch":[{"urls":["/next"]}]}</script>'+ '<link rel="preload" as="image" href="/hero.webp" fetchpriority="high">'+ '<img src="/hero.webp" fetchpriority="high">'+ )+ result = preload_check.analyse(html, {})+ assert result["score"] == 100+ assert result["recommendations"] == []+++def test_preload_score_low_on_bfcache_killer() -> None:+ html = "<script>addEventListener('unload', () => {});</script>"+ result = preload_check.analyse(html, {"Cache-Control": "no-store"})+ # Loses points for: no speculation rules, no fetchpriority, two bfcache+ # killers, but gains 25 for no deprecated prerender = ~25/100.+ assert result["score"] <= 50+++# ---------------------------------------------------------------------------+# indexnow_submit — validation only (no network)+# ---------------------------------------------------------------------------+++def test_indexnow_rejects_empty_url_list() -> None:+ result = indexnow_submit.submit("example.com", "k" * 32,+ "https://example.com/k.txt", [])+ assert result["ok"] is False+ assert "empty" in result["error"]+++def test_indexnow_rejects_key_too_short() -> None:+ result = indexnow_submit.submit("example.com", "short",+ "https://example.com/k.txt",+ ["https://example.com/a"])+ assert result["ok"] is False+ assert "key must be" in result["error"]+++def test_indexnow_rejects_cross_host_urls() -> None:+ result = indexnow_submit.submit(+ "example.com", "k" * 32, "https://example.com/k.txt",+ ["https://example.com/ok", "https://other.example/bad"],+ )+ assert result["ok"] is False+ assert "host" in result["error"]+++def test_indexnow_rejects_batch_above_spec_cap() -> None:+ big = [f"https://example.com/p{i}" for i in range(10001)]+ result = indexnow_submit.submit(+ "example.com", "k" * 32, "https://example.com/k.txt", big,+ )+ assert result["ok"] is False+ assert "10000" in result["error"]+++def test_indexnow_rejects_private_ip_in_url_list() -> None:+ result = indexnow_submit.submit(+ "10.0.0.1", "k" * 32, "https://10.0.0.1/k.txt",+ ["http://10.0.0.1/admin"],+ )+ assert result["ok"] is False+ assert "url_safety" in result["error"]+++# ---------------------------------------------------------------------------+# lcp_subparts — SSRF + missing-key paths+# ---------------------------------------------------------------------------+++def test_lcp_subparts_blocks_ssrf() -> None:+ result = lcp_subparts.analyse("http://10.0.0.1/")+ assert "error" in result+ assert "url_safety" in result["error"]+++def test_lcp_subparts_reports_missing_api_key() -> None:+ with patch.object(lcp_subparts, "get_api_key", return_value=None):+ result = lcp_subparts.analyse("https://example.com/")+ assert "error" in result+ assert "API key" in result["error"]+++# ---------------------------------------------------------------------------+# unlighthouse_run — SSRF + Node-missing paths+# ---------------------------------------------------------------------------+++def test_unlighthouse_blocks_ssrf() -> None:+ result = unlighthouse_run.run("http://192.168.1.1/")+ assert result["ok"] is False+ assert "url_safety" in result["error"]+++def test_unlighthouse_reports_missing_node(monkeypatch) -> None:+ monkeypatch.setattr(unlighthouse_run.shutil, "which", lambda _name: None)+ result = unlighthouse_run.run("https://example.com/")+ assert result["ok"] is False+ assert "npx" in result["error"].lower() or "node" in result["error"].lower()