Skip to content

balsm-health/website / .claude/skills/seo

Comprehensive SEO analysis for any website or business type. Full site audits, single-page analysis, technical SEO (crawlability, indexability, Core Web Vitals with INP), schema markup, content quality (E-E-A-T), image optimization, sitemap analysis, and GEO for AI Overviews/ChatGPT/Perplexity. Industry detection for SaaS, e-commerce, local, publishers, agencies. Triggers on: SEO, audit, schema, Core Web Vitals, sitemap, E-E-A-T, AI Overviews, GEO, technical SEO, content quality, page speed.

FileKindSize
LICENSE.txtmarkdown143 B
SKILL.mdskill md16.9 KB
bin/claude-seoexecutablescript1.5 KB
extensions/banana/references/cost-tracking.mdmarkdown1.2 KB
extensions/banana/references/gemini-models.mdmarkdown5.8 KB
extensions/banana/references/mcp-tools.mdmarkdown3.7 KB
extensions/banana/references/post-processing.mdmarkdown5.1 KB
extensions/banana/references/presets.mdmarkdown2.2 KB
extensions/banana/references/prompt-engineering.mdmarkdown20.9 KB
extensions/banana/references/seo-image-presets.mdmarkdown4.0 KB
extensions/banana/scripts/batch.pyexecutablescript3.3 KB
extensions/banana/scripts/cost_tracker.pyexecutablescript7.2 KB
extensions/banana/scripts/edit.pyexecutablescript5.6 KB
extensions/banana/scripts/generate.pyexecutablescript6.4 KB
extensions/banana/scripts/presets.pyexecutablescript4.9 KB
extensions/banana/scripts/setup_mcp.pyexecutablescript4.5 KB
extensions/banana/scripts/validate_setup.pyexecutablescript3.8 KB
hooks/hooks.jsonconfig416 B
hooks/run-python-hook.jsscript1.7 KB
hooks/validate-schema.pyexecutablescript5.9 KB
pdf/google-seo-reference.mdmarkdown8.0 KB
references/backlink-quality.mdmarkdown3.4 KB
references/cwv-thresholds.mdmarkdown6.9 KB
references/eeat-framework.mdmarkdown8.1 KB
references/free-backlink-sources.mdmarkdown5.6 KB
references/local-schema-types.mdmarkdown9.2 KB
references/local-seo-signals.mdmarkdown9.6 KB
references/maps-api-endpoints.mdmarkdown5.9 KB
references/maps-free-apis.mdmarkdown6.0 KB
references/maps-gbp-checklist.mdmarkdown5.9 KB
references/maps-geo-grid.mdmarkdown4.3 KB
references/quality-gates.mdmarkdown5.1 KB
references/schema-types.mdmarkdown7.8 KB
references/thinking-framework.mdmarkdown9.3 KB
requirements.txtmanifest1.5 KB
runtime-plugin.jsonconfig1.5 KB
schema/templates.jsonconfig9.4 KB
scripts/agent_ux_check.pyscript8.2 KB
scripts/analyze_visual.pyexecutablescript7.2 KB
scripts/backlinks_auth.pyscript16.1 KB
scripts/bing_webmaster.pyscript21.8 KB
scripts/capture_screenshot.pyexecutablescript6.4 KB
scripts/commoncrawl_graph.pyscript15.6 KB
scripts/consistency_check.pyscript12.5 KB
scripts/content_humanize.pyscript7.2 KB
scripts/content_quality.pyscript9.7 KB
scripts/content_verify.pyscript7.1 KB
scripts/crux_history.pyscript10.7 KB
scripts/dataforseo_costs.pyscript15.8 KB
scripts/dataforseo_merchant.pyexecutablescript16.7 KB
scripts/dataforseo_normalize.pyexecutablescript14.7 KB
scripts/domain_history.pyscript9.6 KB
scripts/drift_baseline.pyscript13.5 KB
scripts/drift_compare.pyscript22.3 KB
scripts/drift_history.pyscript3.4 KB
scripts/drift_report.pyscript11.0 KB
scripts/fetch_page.pyexecutablescript9.4 KB
scripts/ga4_report.pyscript16.8 KB
scripts/gbp_deprecation_lint.pyexecutablescript4.7 KB
scripts/google_auth.pyscript31.0 KB
scripts/google_report.pyscript97.6 KB
scripts/gsc_inspect.pyscript11.0 KB
scripts/gsc_query.pyscript18.6 KB
scripts/indexing_notify.pyscript10.3 KB
scripts/indexnow_submit.pyscript8.8 KB
scripts/iptc_ai_label.pyscript7.6 KB
scripts/keyword_planner.pyscript10.8 KB
scripts/lcp_subparts.pyscript7.2 KB
scripts/moz_api.pyscript14.7 KB
scripts/nlp_analyze.pyscript12.1 KB
scripts/pagespeed_check.pyscript22.9 KB
scripts/parasite_risk.pyexecutablescript8.6 KB
scripts/parse_html.pyexecutablescript8.8 KB
scripts/portability_check.pyscript7.8 KB
scripts/preload_check.pyscript8.1 KB
scripts/release_sign.pyscript5.6 KB
scripts/render_page.pyscript20.9 KB
scripts/runtime.pyexecutablescript15.1 KB
scripts/schema_ecommerce_validate.pyscript11.8 KB
scripts/schema_generate.pyscript12.0 KB
scripts/seo_updates.pyscript4.8 KB
scripts/sitemap_discovery.pyscript10.0 KB
scripts/sync_flow.pyscript11.9 KB
scripts/ucp_check.pyscript8.4 KB
scripts/unlighthouse_run.pyscript5.6 KB
scripts/url_safety.pyscript22.0 KB
scripts/validate_backlink_report.pyscript11.7 KB
scripts/verify_backlinks.pyscript12.9 KB
scripts/verify_release.pyscript4.8 KB
scripts/youtube_search.pyscript12.3 KB

scripts/crux_history.py

View on GitHub
#!/usr/bin/env python3
"""
CrUX History API for Core Web Vitals trends over time.

Fetches up to 25 weekly data points from the Chrome UX Report History API
and identifies improving, stable, or degrading trends per metric.

Usage:
    python crux_history.py https://example.com
    python crux_history.py https://example.com --form-factor PHONE --json
    python crux_history.py https://example.com --origin
"""

import argparse
import json
import sys
from typing import Optional
from urllib.parse import urlparse

try:
    import requests
except ImportError:
    print("Error: requests library required. Install with: pip install requests")
    sys.exit(1)

try:
    from google_auth import (
        get_api_key,
        google_api_key_headers,
        redact_google_api_key,
        validate_url,
    )
except ImportError:
    import os
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    from google_auth import (
        get_api_key,
        google_api_key_headers,
        redact_google_api_key,
        validate_url,
    )

CRUX_HISTORY_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord"

CWV_THRESHOLDS = {
    "largest_contentful_paint": {"good": 2500, "poor": 4000, "label": "LCP", "unit": "ms"},
    "interaction_to_next_paint": {"good": 200, "poor": 500, "label": "INP", "unit": "ms"},
    "cumulative_layout_shift": {"good": 0.1, "poor": 0.25, "label": "CLS", "unit": ""},
    "first_contentful_paint": {"good": 1800, "poor": 3000, "label": "FCP", "unit": "ms"},
    "experimental_time_to_first_byte": {"good": 800, "poor": 1800, "label": "TTFB", "unit": "ms"},
}


def query_history(
    url_or_origin: str,
    api_key: str,
    form_factor: Optional[str] = None,
) -> dict:
    """
    Query CrUX History API for weekly CWV trends.

    Args:
        url_or_origin: Full URL or origin.
        api_key: Google API key.
        form_factor: DESKTOP, PHONE, or TABLET. None for all.

    Returns:
        Dictionary with metrics timeseries, collection periods, and trend analysis.
    """
    result = {
        "target": url_or_origin,
        "form_factor": form_factor or "ALL",
        "metrics": {},
        "collection_periods": [],
        "trends": {},
        "error": None,
    }

    if not validate_url(url_or_origin):
        result["error"] = "Invalid URL. Only http/https URLs to public hosts are accepted."
        return result

    parsed = urlparse(url_or_origin)
    is_origin = parsed.path in ("", "/") and not parsed.query

    body = {}
    if is_origin:
        body["origin"] = f"{parsed.scheme}://{parsed.netloc}"
    else:
        body["url"] = url_or_origin

    if form_factor:
        body["formFactor"] = form_factor.upper()

    try:
        resp = requests.post(
            CRUX_HISTORY_ENDPOINT,
            headers=google_api_key_headers(api_key),
            json=body,
            timeout=30,
        )

        if resp.status_code == 404:
            target_type = "origin" if is_origin else "URL"
            result["error"] = (
                f"No CrUX history data for this {target_type}. "
                "Insufficient Chrome traffic volume for eligibility."
            )
            return result

        if resp.status_code == 429:
            result["error"] = "CrUX API rate limit exceeded (150 QPM shared). Wait and retry."
            return result

        resp.raise_for_status()
        data = resp.json()
    except requests.exceptions.RequestException as e:
        result["error"] = f"CrUX History API request failed: {redact_google_api_key(e)}"
        return result

    record = data.get("record", {})

    # Collection periods
    periods = record.get("collectionPeriods", [])
    for period in periods:
        first = period.get("firstDate", {})
        last = period.get("lastDate", {})
        result["collection_periods"].append({
            "first": f"{first.get('year')}-{first.get('month', 0):02d}-{first.get('day', 0):02d}",
            "last": f"{last.get('year')}-{last.get('month', 0):02d}-{last.get('day', 0):02d}",
        })

    # Metrics timeseries
    for metric_name, metric_data in record.get("metrics", {}).items():
        if metric_name not in CWV_THRESHOLDS:
            continue

        thresholds = CWV_THRESHOLDS[metric_name]
        p75s_data = metric_data.get("percentilesTimeseries", {})
        p75s_raw = p75s_data.get("p75s", [])

        # Parse p75 values (CLS is string-encoded)
        p75s = []
        for val in p75s_raw:
            if val is None:
                p75s.append(None)
            elif metric_name == "cumulative_layout_shift":
                try:
                    p75s.append(float(str(val)))
                except (ValueError, TypeError):
                    p75s.append(None)
            else:
                try:
                    p75s.append(int(val))
                except (ValueError, TypeError):
                    try:
                        p75s.append(float(val))
                    except (ValueError, TypeError):
                        p75s.append(None)

        # Distributions timeseries
        histogram_ts = metric_data.get("histogramTimeseries", [])
        good_pcts = []
        if len(histogram_ts) >= 3:
            good_densities = histogram_ts[0].get("densities", [])
            for d in good_densities:
                if d is None or str(d) == "NaN":
                    good_pcts.append(None)
                else:
                    try:
                        good_pcts.append(round(float(d) * 100, 1))
                    except (ValueError, TypeError):
                        good_pcts.append(None)

        # Extract needs_improvement (bin 1) and poor (bin 2) percentages
        ni_pcts = []
        poor_pcts = []
        if len(histogram_ts) >= 3:
            for bin_idx, target_list in [(1, ni_pcts), (2, poor_pcts)]:
                bin_densities = histogram_ts[bin_idx].get("densities", [])
                for d in bin_densities:
                    if d is None or str(d) == "NaN":
                        target_list.append(None)
                    else:
                        try:
                            target_list.append(round(float(d) * 100, 1))
                        except (ValueError, TypeError):
                            target_list.append(None)

        result["metrics"][metric_name] = {
            "label": thresholds["label"],
            "unit": thresholds["unit"],
            "p75_values": p75s,
            "good_percentages": good_pcts,
            "needs_improvement_percentages": ni_pcts,
            "poor_percentages": poor_pcts,
            "latest_p75": p75s[-1] if p75s and p75s[-1] is not None else None,
            "good_threshold": thresholds["good"],
            "poor_threshold": thresholds["poor"],
        }

    # Trend analysis
    result["trends"] = detect_trends(result["metrics"])

    return result


def detect_trends(metrics: dict) -> dict:
    """
    Analyze p75 timeseries to detect trends.

    Compares the average of the last 4 weeks to the average of the first 4 weeks.

    Returns:
        Dictionary mapping metric names to trend info:
        direction (improving/stable/degrading), change_pct, latest, earliest.
    """
    trends = {}

    for metric_name, data in metrics.items():
        p75s = data.get("p75_values", [])
        valid = [v for v in p75s if v is not None]

        if len(valid) < 8:
            trends[metric_name] = {
                "direction": "insufficient_data",
                "label": data.get("label", metric_name),
            }
            continue

        # First 4 valid vs last 4 valid
        first_4 = valid[:4]
        last_4 = valid[-4:]
        avg_first = sum(first_4) / len(first_4)
        avg_last = sum(last_4) / len(last_4)

        if avg_first == 0:
            change_pct = 0
        else:
            change_pct = ((avg_last - avg_first) / avg_first) * 100

        # For CWV, lower is better (except CLS where lower is also better)
        # So a negative change_pct means improvement
        if abs(change_pct) < 5:
            direction = "stable"
        elif change_pct < 0:
            direction = "improving"
        else:
            direction = "degrading"

        trends[metric_name] = {
            "direction": direction,
            "change_pct": round(change_pct, 1),
            "earliest_avg": round(avg_first, 3) if data.get("unit") == "" else round(avg_first),
            "latest_avg": round(avg_last, 3) if data.get("unit") == "" else round(avg_last),
            "label": data.get("label", metric_name),
            "data_points": len(valid),
        }

    return trends


def main():
    parser = argparse.ArgumentParser(
        description="CrUX History API - Core Web Vitals trends over time"
    )
    parser.add_argument("url", help="URL or origin to analyze")
    parser.add_argument(
        "--form-factor",
        choices=["PHONE", "DESKTOP", "TABLET"],
        help="Filter by form factor",
    )
    parser.add_argument(
        "--api-key",
        help="Google API key (overrides config/env)",
    )
    parser.add_argument(
        "--origin",
        action="store_true",
        help="Force origin-level query (strip path/query)",
    )
    parser.add_argument(
        "--json", "-j",
        action="store_true",
        help="Output as JSON",
    )

    args = parser.parse_args()

    api_key = args.api_key or get_api_key()
    if not api_key:
        print("Error: API key required. Use --api-key or configure GOOGLE_API_KEY.", file=sys.stderr)
        sys.exit(1)

    target = args.url
    if args.origin:
        parsed = urlparse(target)
        target = f"{parsed.scheme}://{parsed.netloc}"

    result = query_history(target, api_key, form_factor=args.form_factor)

    if args.json:
        print(json.dumps(result, indent=2))
    else:
        if result.get("error"):
            print(f"Error: {result['error']}", file=sys.stderr)
            sys.exit(1)

        print(f"=== CrUX History ({result.get('form_factor', 'ALL')}) ===")
        print(f"Target: {result.get('target')}")

        periods = result.get("collection_periods", [])
        if periods:
            print(f"Range: {periods[0]['first']} to {periods[-1]['last']} ({len(periods)} weeks)")

        print("\nTrend Analysis:")
        for name, trend in result.get("trends", {}).items():
            label = trend.get("label", name)
            direction = trend.get("direction", "?")
            if direction == "insufficient_data":
                print(f"  {label}: Insufficient data")
                continue

            arrow = {"improving": "IMPROVING", "stable": "STABLE", "degrading": "DEGRADING"}.get(direction, "?")
            change = trend.get("change_pct", 0)
            earliest = trend.get("earliest_avg")
            latest = trend.get("latest_avg")
            print(f"  {label}: {arrow} ({change:+.1f}%) | {earliest} -> {latest}")


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall