Skip to content

Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.

feat: v1.7.0 - Google API integration, YouTube video embedding, plugin compliance

Daniel6a31b9a23946
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index e811aeb..ea9120f 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "claude-blog",
- "description": "AI-powered blog skill with 20 commands, persona-driven writing, fact-checking, cannibalization detection, CMS taxonomy sync, NotebookLM research, Gemini TTS audio narration, 5-category scoring, 4 agents, and Gemini image generation. Optimized for Google rankings and AI citations (GEO/AEO).",
- "version": "1.6.2",
+ "description": "AI-powered blog skill with 21 commands, Google API integration (PageSpeed, CrUX, GSC, GA4, YouTube, NLP, Keywords), YouTube video embedding, persona-driven writing, fact-checking, cannibalization detection, CMS taxonomy sync, NotebookLM research, Gemini TTS audio narration, 5-category scoring, 4 agents, and Gemini image generation. Optimized for Google rankings and AI citations (GEO/AEO).",
+ "version": "1.7.0",
"author": {
"name": "AgriciDaniel"
},
@@ -11,6 +11,7 @@
"keywords": [
"blog", "seo", "content", "writing", "ai-citations",
"geo", "aeo", "eeat", "google-rankings", "content-optimization",
- "blog-writing", "markdown", "mdx", "wordpress"
+ "blog-writing", "markdown", "mdx", "wordpress",
+ "google-api", "youtube", "pagespeed", "search-console"
]
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 730b456..c8f0384 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [1.7.0] - 2026-03-28
+
+### Added
+- **blog-google sub-skill**: Google API integration with 13 commands across 4 credential tiers -- PageSpeed Insights, CrUX Core Web Vitals (25-week history), Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis, YouTube video search, Google Ads Keyword Planner, and PDF/HTML report generation. 11 Python scripts in isolated venv. Shares config with claude-seo at `~/.config/claude-seo/google-api.json`.
+- **YouTube video embedding**: Blog posts now discover and embed 2-3 relevant YouTube videos using srcdoc lazy-loading pattern (~5KB vs ~500KB per embed). Integrated into blog-write (Phase 2 research + Phase 5 embedding), blog-rewrite (audit + inject), and blog-schema (VideoObject generation). Supports MDX, HTML, Markdown, and Hugo embed formats with noscript fallback for AI crawlers.
+- **VideoObject JSON-LD schema**: blog-schema now generates VideoObject for embedded videos (up to 7 schema types per page, from 6). Added to schema-stack.md reference with @id pattern `#video-{N}`.
+- **video-embeds.md reference**: New reference file with quality criteria (0-100 scoring), embed placement strategy, platform-specific code patterns, and graceful degradation.
+- **Google API integrations in existing workflows**: blog-seo-check (optional PSI/CrUX), blog-rewrite (NLP entity analysis), blog-geo (GSC performance), blog-researcher (YouTube video discovery).
+
## [1.6.2] - 2026-03-27
### Fixed
diff --git a/CLAUDE.md b/CLAUDE.md
index 1fcad37..b36191c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@
This repository contains **Claude Blog**, a Tier 4 Claude Code skill for blog content
creation, optimization, and management. It follows the Agent Skills open standard and the
-3-layer architecture (directive, orchestration, execution). 21 sub-skills, 4 specialized
+3-layer architecture (directive, orchestration, execution). 22 sub-skills, 4 specialized
subagents, and 12 content templates are dual-optimized for Google rankings (December 2025
Core Update, E-E-A-T) and AI citations (GEO/AEO).
@@ -13,13 +13,13 @@ Core Update, E-E-A-T) and AI citations (GEO/AEO).
```
claude-blog/
CLAUDE.md # Project instructions (this file)
- .claude-plugin/plugin.json # Plugin manifest (v1.6.2)
+ .claude-plugin/plugin.json # Plugin manifest (v1.7.0)
.claude-plugin/marketplace.json # Marketplace catalog for distribution
.mcp.json # MCP server configuration (nanobanana-mcp)
pyproject.toml # Python packaging (3.11+)
- skills/ # 21 sub-skills (blog/ is the orchestrator)
+ skills/ # 22 sub-skills (blog/ is the orchestrator)
blog/SKILL.md # Main orchestrator, routing, scoring
- references/ # 12 on-demand knowledge files
+ references/ # 13 on-demand knowledge files
templates/ # 12 content templates
scripts/ # Python analysis scripts
blog-write/SKILL.md # Write new articles from scratch
@@ -51,6 +51,11 @@ claude-blog/
SKILL.md # Audio generation sub-skill
references/ # 1 reference doc (30 voice catalog)
scripts/ # 5 Python scripts + requirements.txt
+ blog-google/ # Google API integration
+ SKILL.md # Google API sub-skill (13 commands, 4 tiers)
+ references/ # 3 reference docs (auth, API, quotas)
+ scripts/ # 11 Google API scripts + venv wrapper
+ assets/templates/ # 3 report templates
agents/ # 4 specialized subagents
blog-researcher.md # Statistics and source research
blog-writer.md # Content generation
@@ -83,11 +88,13 @@ claude-blog/
| `/blog taxonomy` | Tag/category CMS management |
| `/blog notebooklm` | Query NotebookLM for source-grounded research |
| `/blog audio` | Generate audio narration via Gemini TTS |
+| `/blog google` | Google API data: PSI, CrUX, GSC, GA4, NLP, YouTube, Keywords |
## Development Rules
- Keep SKILL.md files under 500 lines / 5000 tokens
-- Reference files should be focused and under 200 lines
+- SKILL.md frontmatter: only valid fields (name, description, user-invokable, argument-hint, compatibility, license, metadata, disable-model-invocation). Do NOT use `allowed-tools` -- it is not a Claude Code spec field
+- New reference files should be focused and under 200 lines. Existing comprehensive references (platform-guides, schema-stack, content-templates, distribution-playbook) are exempt from this guideline
- Scripts must have docstrings, CLI interface, and JSON output
- Follow kebab-case naming for all skill directories
- Agents invoked via Task tool, never via Bash
diff --git a/PRIVACY.md b/PRIVACY.md
index 8f1eda8..ec0c376 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -22,6 +22,7 @@ When you explicitly invoke certain commands, the plugin may interact with extern
| SERP and keyword data | DataForSEO API (~$0.01/call) | Only when you run `/blog cannibalization --api` with your own DataForSEO credentials. Local mode (default) requires no API |
| CMS taxonomy sync | WordPress, Shopify, Ghost, Strapi, Sanity APIs | Only when you run `/blog taxonomy` with your own CMS credentials |
| NotebookLM research | Google NotebookLM | Only when you run `/blog notebooklm` with your own configuration |
+| Google API data | Google PageSpeed Insights, CrUX, Search Console, GA4, YouTube Data API, Cloud NLP, Indexing API, Keyword Planner | Only when you run `/blog google` commands and have configured your own API credentials at `~/.config/claude-seo/google-api.json` |
All API keys and credentials are stored locally in your environment variables or `.env` files. This plugin never transmits your credentials to any party other than the service you are explicitly calling.
@@ -35,4 +36,4 @@ For privacy questions, open an issue at: https://github.com/AgriciDaniel/claude-
## Last Updated
-2026-03-27
+2026-03-28
diff --git a/agents/blog-researcher.md b/agents/blog-researcher.md
index 8f35de7..374b54a 100644
--- a/agents/blog-researcher.md
+++ b/agents/blog-researcher.md
@@ -189,6 +189,24 @@ Verification process:
3. Check if the data appears on the original source (not just re-reported)
4. Flag stats that only appear on low-authority sites
+## Finding YouTube Videos
+
+When researching for blog posts, find 2-3 relevant YouTube videos for embedding:
+
+1. Use blog-google if available:
+ ```bash
+ python3 skills/blog-google/scripts/run.py youtube_search search "[primary keyword]" --json
+ ```
+2. If blog-google unavailable, use WebSearch: `site:youtube.com [topic] [year] -shorts`
+3. Apply quality criteria (from `references/video-embeds.md`):
+ - Minimum 1,000 views, published within last 3 years
+ - Title or description contains the topic keyword
+ - From a channel with > 1,000 subscribers
+ - Prefer videos 5-15 minutes long
+4. Select 2-3 best videos and include in research output:
+ - video_id, title, channel name, view count, duration, publish date
+5. If no suitable videos found, note: "No suitable YouTube videos found for embedding"
+
## Red Flags (Reject These Sources)
- Round numbers without methodology
diff --git a/pyproject.toml b/pyproject.toml
index 4270440..25a7531 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "claude-blog"
-version = "1.6.2"
+version = "1.7.0"
description = "AI-powered blog creation and optimization skill for Claude Code"
readme = "README.md"
license = {text = "MIT"}
@@ -22,6 +22,14 @@ advanced = [
"scikit-learn",
"language-tool-python",
]
+google = [
+ "requests>=2.32.4",
+ "google-api-python-client>=2.100.0",
+ "google-auth>=2.20.0",
+ "google-auth-oauthlib>=1.0.0",
+ "google-auth-httplib2>=0.2.0",
+ "google-analytics-data>=0.18.0",
+]
dev = [
"pytest>=8.0",
"textstat>=0.7.3",
diff --git a/skills/blog-analyze/SKILL.md b/skills/blog-analyze/SKILL.md
index 0707909..0d6ec25 100644
--- a/skills/blog-analyze/SKILL.md
+++ b/skills/blog-analyze/SKILL.md
@@ -10,13 +10,6 @@ description: >
markdown, HTML, URL). Use when user says "analyze blog", "audit blog",
"blog score", "check blog quality", "blog review", "rate this blog",
"blog health check".
-allowed-tools:
- - Read
- - Write
- - Bash
- - Grep
- - Glob
- - WebFetch
---
# Blog Analyzer -- Quality Audit & Scoring
diff --git a/skills/blog-audio/SKILL.md b/skills/blog-audio/SKILL.md
index f9df29a..a0a8470 100644
--- a/skills/blog-audio/SKILL.md
+++ b/skills/blog-audio/SKILL.md
@@ -11,12 +11,6 @@ description: >
"voice", "narration", "generate audio".
user-invokable: true
argument-hint: "[generate|voices|setup] [file-or-text] [--mode summary|full|dialogue] [--voice name]"
-allowed-tools:
- - Read
- - Write
- - Bash
- - Glob
- - Grep
license: MIT
metadata:
author: AgriciDaniel
diff --git a/skills/blog-audit/SKILL.md b/skills/blog-audit/SKILL.md
index b7a2d40..6a1ba95 100644
--- a/skills/blog-audit/SKILL.md
+++ b/skills/blog-audit/SKILL.md
@@ -6,13 +6,6 @@ description: >
Spawns parallel subagents for comprehensive analysis. Produces per-post scores
and a prioritized action queue. Use when user says "audit blog", "blog audit",
"site audit", "blog health", "audit all posts", "check all blogs".
-allowed-tools:
- - Read
- - Write
- - Bash
- - Grep
- - Glob
- - Task
---
# Blog Audit -- Full-Site Health Assessment
diff --git a/skills/blog-brief/SKILL.md b/skills/blog-brief/SKILL.md
index 8ec0fc8..f0ddff1 100644
--- a/skills/blog-brief/SKILL.md
+++ b/skills/blog-brief/SKILL.md
@@ -9,15 +9,6 @@ description: >
Briefs are optimized for Google rankings and AI citations (GEO/AEO). Use
when user says "content brief", "blog brief", "write brief", "outline blog",
"plan blog post", "blog outline", "content outline".
-allowed-tools:
- - Read
- - Write
- - Bash
- - Grep
- - Glob
- - WebFetch
- - WebSearch
- - Task
---
# Blog Brief Generator -- Content Planning
diff --git a/skills/blog-calendar/SKILL.md b/skills/blog-calendar/SKILL.md
index 0b5bc0c..5525a9e 100644
--- a/skills/blog-calendar/SKILL.md
+++ b/skills/blog-calendar/SKILL.md
@@ -8,14 +8,6 @@ description: >
authority and AI citation freshness requirements (30-day update cycles).
Use when user says "editorial calendar", "content calendar", "blog calendar",
"publishing schedule", "blog plan", "content plan", "what should I write".
-allowed-tools:
- - Read
- - Write
- - Bash
- - Grep
- - Glob
- - WebFetch
- - WebSearch
---
# Blog Calendar -- Editorial Planning
diff --git a/skills/blog-cannibalization/SKILL.md b/skills/blog-cannibalization/SKILL.md
index fb73391..0c65426 100644
--- a/skills/blog-cannibalization/SKILL.md
+++ b/skills/blog-cannibalization/SKILL.md
@@ -10,11 +10,6 @@ description: >
keywords", "cannibalize".
user-invokable: true
argument-hint: "[directory] [--api]"
-allowed-tools:
- - Read
- - Grep
- - Glob
- - WebFetch
---
# Blog Cannibalization - Keyword Overlap Detection
diff --git a/skills/blog-chart/SKILL.md b/skills/blog-chart/SKILL.md
index f2b601e..cf0648a 100644
--- a/skills/blog-chart/SKILL.md
+++ b/skills/blog-chart/SKILL.md
@@ -10,12 +10,6 @@ description: >
"blog graph", "visualize data", or when the blog-write workflow identifies
chart-worthy data points (3+ comparable metrics, trends, before/after data).
user-invokable: false
-allowed-tools:
- - Read
- - Write
- - Edit
- - Bash
- - Grep
---
# Blog Chart -- Built-In SVG Data Visualization
diff --git a/skills/blog-factcheck/SKILL.md b/skills/blog-factcheck/SKILL.md
index 8c18f77..2433bbd 100644
--- a/skills/blog-factcheck/SKILL.md
+++ b/skills/blog-factcheck/SKILL.md
@@ -10,11 +10,6 @@ description: >
"factcheck", "source verification".
user-invokable: true
argument-hint: "[file]"
-allowed-tools:
- - Read
- - WebFetch
- - Grep
- - Glob
---
# Blog Fact-Check
diff --git a/skills/blog-geo/SKILL.md b/skills/blog-geo/SKILL.md
index 62899e2..de2f99a 100644
--- a/skills/blog-geo/SKILL.md
+++ b/skills/blog-geo/SKILL.md
@@ -7,12 +7,6 @@ description: >
Generates citation capsules and a 0-100 AI Citation Readiness score. Use when
user says "geo", "ai citation", "ai optimization", "citation audit", "aeo",
"perplexity optimization", "chatgpt citation".
-allowed-tools:
- - Read
- - Write
- - Grep
- - Glob
- - WebFetch
---
# Blog GEO -- AI Citation Optimization Audit
@@ -250,3 +244,15 @@ Output the following report:
Run `/blog analyze <file>` for full content quality scoring.
```
+
+### Optional: Search Performance Context (blog-google)
+
+If blog-google credentials include Tier 1 (GSC) and the post has a published URL:
+
+1. Query GSC: `python3 skills/blog-google/scripts/run.py gsc_query --property <property> --filter-page <url> --json`
+2. Add to platform-specific analysis:
+ - Current impressions, clicks, CTR, average position
+ - Search queries driving traffic to this URL
+3. Check indexation: `python3 skills/blog-google/scripts/run.py gsc_inspect <url> --json`
+4. Report indexation status, canonical selection, mobile usability.
+5. Falls back silently if not configured.
diff --git a/skills/blog-google/SKILL.md b/skills/blog-google/SKILL.md
new file mode 100644
index 0000000..c8cffb8
--- /dev/null
+++ b/skills/blog-google/SKILL.md
@@ -0,0 +1,275 @@
+---
+name: blog-google
+description: >
+ Google API integration for blog performance: PageSpeed Insights, CrUX Core Web
+ Vitals with 25-week history, Search Console performance, URL Inspection, Indexing
+ API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search
+ for embedding, and Google Ads Keyword Planner. Progressive feature availability
+ based on credential tier (API key, OAuth/service account, GA4, Ads). Shares
+ config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user
+ says "google data", "page speed", "core web vitals", "search console",
+ "indexation", "GA4", "keyword research", "nlp entities", "blog performance",
+ "youtube search", "google api setup".
+user-invokable: true
+argument-hint: "[setup|pagespeed|crux|crux-history|gsc|inspect|index|ga4|nlp|youtube|keywords|report|quotas] [url|property|query]"
+license: MIT
+metadata:
+ author: AgriciDaniel
+ version: "1.0.0"
+ category: blog
+---
+
+# Blog Google -- Google API Data for Blog Performance
+
+Direct access to Google's SEO APIs for blog performance analysis. Provides real
+Chrome user metrics, indexation status, search performance, entity analysis, YouTube
+video discovery, keyword volumes, and PDF/HTML performance reports.
+
+All APIs are free at normal usage levels. Setup requires a Google Cloud project
+with an API key and/or service account.
+
+## Prerequisites
+
+**Always check credentials before running any command:**
+```bash
+python3 skills/blog-google/scripts/run.py google_auth --check --json
+```
+
+**Config file:** `~/.config/claude-seo/google-api.json` (shared with claude-seo)
+```json
+{
+ "api_key": "AIzaSy...",
+ "oauth_client_path": "/path/to/client_secret.json",
+ "default_property": "sc-domain:example.com",
+ "ga4_property_id": "properties/123456789",
+ "ads_developer_token": "...",
+ "ads_customer_id": "123-456-7890"
+}
+```
+
+If missing, read `references/auth-setup.md` and walk the user through setup.
+
+### Credential Tiers
+
+| Tier | Detection | Available Commands |
+|------|-----------|-------------------|
+| **0** (API Key) | `api_key` present | `pagespeed`, `crux`, `crux-history`, `youtube`, `nlp` |
+| **1** (OAuth/SA) | + OAuth token or service account | Tier 0 + `gsc`, `inspect`, `index` |
+| **2** (Full) | + `ga4_property_id` configured | Tier 1 + `ga4` |
+| **3** (Ads) | + `ads_developer_token` + `ads_customer_id` | Tier 2 + `keywords` |
+
+Always communicate the detected tier before running commands.
+
+## Quick Reference
+
+| Command | What it does | Tier |
+|---------|-------------|------|
+| `/blog google setup` | Check/configure API credentials | -- |
+| `/blog google pagespeed <url>` | PSI Lighthouse + CrUX field data | 0 |
+| `/blog google crux <url>` | CrUX field data only (p75 metrics) | 0 |
+| `/blog google crux-history <url>` | 25-week CWV trend analysis | 0 |
+| `/blog google youtube <query>` | YouTube video search (views, likes, duration) | 0 |
+| `/blog google nlp <url-or-text>` | NLP entity extraction + sentiment | 0 |
+| `/blog google gsc <property>` | Search Console: clicks, impressions, CTR, position | 1 |
+| `/blog google inspect <url>` | URL Inspection: index status, canonical | 1 |
+| `/blog google index <url>` | Submit URL to Indexing API | 1 |
+| `/blog google ga4 [property-id]` | GA4 organic traffic report | 2 |
+| `/blog google keywords <seed>` | Keyword ideas from Google Ads Keyword Planner | 3 |
+| `/blog google report <type>` | PDF/HTML performance report | -- |
+| `/blog google quotas` | Show rate limits for all APIs | -- |
+
+---
+
+## PageSpeed + CrUX
+
+### `/blog google pagespeed <url>`
+
+Combined Lighthouse lab data + CrUX field data for a published blog post.
+
+**Script:** `python3 skills/blog-google/scripts/run.py pagespeed_check <url> --json`
+**Reference:** `references/api-reference.md`
+
+Output merges lab scores (point-in-time Lighthouse) with field data (28-day
+Chrome user metrics). CrUX tries URL-level first, falls back to origin-level.
+
+### `/blog google crux <url>`
+
+CrUX field data only (no Lighthouse run). Faster.
+
+**Script:** `python3 skills/blog-google/scripts/run.py pagespeed_check <url> --crux-only --json`
+
+### `/blog google crux-history <url>`
+
+25-week CrUX History trends. Shows whether CWV metrics are improving, stable, or degrading.
+
+**Script:** `python3 skills/blog-google/scripts/run.py crux_history <url> --json`
+
+---
+
+## Search Console
+
+### `/blog google gsc <property>`
+
+Search Analytics: clicks, impressions, CTR, position for last 28 days.
+
+**Script:** `python3 skills/blog-google/scripts/run.py gsc_query --property <property> --json`
+**Default:** 28 days, dimensions=query,page, type=web, limit=1000.
+
+Includes quick-win detection: queries at position 4-10 with high impressions.
+
+### `/blog google inspect <url>`
+
+URL Inspection: real indexation status from Google.
+
+**Script:** `python3 skills/blog-google/scripts/run.py gsc_inspect <url> --json`
+
+Returns: verdict (PASS/FAIL), coverage state, robots.txt status, indexing state,
+page fetch state, canonical selection, mobile usability, rich results.
+
+For batch inspection: `python3 skills/blog-google/scripts/run.py gsc_inspect --batch <file> --json`
+
+---
+
+## Indexing API
+
+### `/blog google index <url>`
+
+Notify Google of a URL update. Submit new blog posts for faster indexation.
+
+**Script:** `python3 skills/blog-google/scripts/run.py indexing_notify <url> --json`
+**Reference:** `references/api-reference.md`
+
+The Indexing API is officially for JobPosting and BroadcastEvent/VideoObject pages.
+Always inform the user of this restriction. Daily quota: 200 publish requests.
+
+For batch: `python3 skills/blog-google/scripts/run.py indexing_notify --batch <file> --json`
+
+---
+
+## GA4 Traffic
+
+### `/blog google ga4 [property-id]`
+
+Organic traffic report: daily sessions, users, pageviews, bounce rate, engagement.
+
+**Script:** `python3 skills/blog-google/scripts/run.py ga4_report --property <id> --json`
+**Default:** 28 days, filtered to Organic Search channel group.
+
+For top landing pages: `python3 skills/blog-google/scripts/run.py ga4_report --property <id> --report top-pages --json`
+
+---
+
+## YouTube (Video Discovery)
+
+YouTube mentions have the strongest AI visibility correlation (0.737, Ahrefs 75K brands).
+Free, API key only. Used by blog-write and blog-rewrite for video embedding.
+
+### `/blog google youtube <query>`
+
+Search YouTube for videos relevant to a blog topic.
+
+**Script:** `python3 skills/blog-google/scripts/run.py youtube_search search "<query>" --json`
+**Quota:** 100 units per search (10,000 units/day free).
+
+Returns: title, channel, views, likes, duration, description, tags.
+
+For video details + comments: `python3 skills/blog-google/scripts/run.py youtube_search video <video_id> --json`
+
+---
+
+## NLP Content Analysis
+
+Google's own entity/sentiment analysis. Enhances E-E-A-T scoring for blog content.
+
+### `/blog google nlp <url-or-text>`
+
+Full NLP analysis: entities, sentiment, content classification.
+
+**Script:** `python3 skills/blog-google/scripts/run.py nlp_analyze --url <url> --json`
+**Free tier:** 5,000 units/month. Requires billing enabled on GCP project.
+
+For entity extraction only: `python3 skills/blog-google/scripts/run.py nlp_analyze --url <url> --features entities --json`
+
+---
+
+## Keyword Research (Google Ads)
+
+Gold-standard keyword volume data. Requires Google Ads account (Tier 3).
+
+### `/blog google keywords <seed>`
+
+Generate keyword ideas from seed terms for blog topic research.
+
+**Script:** `python3 skills/blog-google/scripts/run.py keyword_planner ideas "<seed>" --json`
+
+For volume lookup: `python3 skills/blog-google/scripts/run.py keyword_planner volume "<kw1>,<kw2>" --json`
+
+---
+
+## Reports
+
+### `/blog google report <type>`
+
+Generate a professional PDF/HTML report with charts.
+
+**Script:** `python3 skills/blog-google/scripts/run.py google_report --type <type> --data <json> --domain <domain> --format pdf`
+
+| Type | Input | Output |
+|------|-------|--------|
+| `cwv-audit` | PSI + CrUX + CrUX History data | Core Web Vitals audit with gauges, timelines |
+| `gsc-performance` | GSC query data | Search Console report with query tables |
+| `indexation` | Batch inspection data | Indexation status with coverage donut |
+| `full` | All data combined | Comprehensive Google SEO report |
+
+**Note:** PDF generation requires system libraries: `sudo apt install libpango1.0-dev libcairo2-dev`.
+Falls back to HTML if weasyprint is unavailable.
+
+---
+
+## Rate Limits
+
+| API | Per-Minute | Per-Day | Auth |
+|-----|-----------|---------|------|
+| PSI v5 | 240 QPM | 25,000 QPD | API Key |
+| CrUX + History | 150 QPM (shared) | Unlimited | API Key |
+| GSC Search Analytics | 1,200 QPM/site | 30M QPD | Service Account |
+| GSC URL Inspection | 600 QPM | 2,000 QPD/site | Service Account |
+| Indexing API | 380 RPM | 200 publish/day | Service Account |
+| GA4 Data API | 10 concurrent | ~25K tokens/day | Service Account |
+| YouTube Data | -- | 10,000 units/day | API Key |
+| NLP API | -- | 5,000 units/month | API Key (billing) |
+
+Read `references/rate-limits-quotas.md` for detailed quota management.
+
+## Blog Workflow Integration
+
+This skill is both user-invocable (`/blog google pagespeed`) and callable
+internally by other blog sub-skills:
+
+- **blog-seo-check**: Runs PSI + CrUX on published post URL for live CWV data
+- **blog-rewrite**: NLP entity analysis to identify E-E-A-T entity gaps
+- **blog-geo**: GSC performance data for real search appearance insights
+- **blog-audit**: Batch CWV + indexation checks across all published blog URLs
+- **blog-write / blog-rewrite**: YouTube search for video embedding
+
+Falls back gracefully when credentials are not configured.
+
+## Technical Notes
+
+- INP replaced FID on March 12, 2024. Never reference FID.
+- CLS values from CrUX are string-encoded (e.g., "0.05"). Scripts handle parsing.
+- CrUX 404 = insufficient Chrome traffic, not an auth error.
+- Search Analytics data has 2-3 day lag.
+- Indexing API is officially for JobPosting/BroadcastEvent pages only.
+- All Google APIs used are FREE at normal usage levels.
+
+## Error Handling
+
+| Scenario | Action |
+|----------|--------|
+| No credentials configured | Run `/blog google setup`. List Tier 0 commands (API key only). |
+| Service account lacks GSC access | Add `client_email` to GSC > Settings > Users > Add. |
+| CrUX data unavailable (404) | Insufficient Chrome traffic. Use PSI lab data as fallback. |
+| GA4 property not found | Find property ID in GA4 Admin > Property Details. |
+| Indexing API quota exceeded | 200/day limit. Prioritize most important URLs. |
+| Rate limit (429) | Wait and retry with exponential backoff. |
diff --git a/skills/blog-google/assets/templates/cwv-audit-report.md b/skills/blog-google/assets/templates/cwv-audit-report.md
new file mode 100644
index 0000000..0e97889
--- /dev/null
+++ b/skills/blog-google/assets/templates/cwv-audit-report.md
@@ -0,0 +1,48 @@
+# Core Web Vitals Audit
+
+**URL/Origin:** {target}
+**Strategy:** {strategy}
+
+## CrUX Field Data (28-day rolling average)
+
+Real Chrome user experience data from the Chrome UX Report.
+
+| Metric | p75 Value | Rating | Good Threshold | Distribution |
+|--------|-----------|--------|----------------|-------------|
+| LCP | {lcp_value} | {lcp_rating} | ≤ 2,500ms | Good: {lcp_good}% / NI: {lcp_ni}% / Poor: {lcp_poor}% |
+| INP | {inp_value} | {inp_rating} | ≤ 200ms | Good: {inp_good}% / NI: {inp_ni}% / Poor: {inp_poor}% |
+| CLS | {cls_value} | {cls_rating} | ≤ 0.1 | Good: {cls_good}% / NI: {cls_ni}% / Poor: {cls_poor}% |
+| FCP | {fcp_value} | {fcp_rating} | ≤ 1,800ms | Good: {fcp_good}% / NI: {fcp_ni}% / Poor: {fcp_poor}% |
+| TTFB | {ttfb_value} | {ttfb_rating} | ≤ 800ms | Good: {ttfb_good}% / NI: {ttfb_ni}% / Poor: {ttfb_poor}% |
+
+**Collection Period:** {collection_start} to {collection_end}
+
+## Lighthouse Lab Scores
+
+| Category | Score |
+|----------|-------|
+| Performance | {perf_score}/100 |
+| Accessibility | {a11y_score}/100 |
+| Best Practices | {bp_score}/100 |
+| SEO | {seo_score}/100 |
+
+## CrUX History Trends (25-week)
+
+| Metric | Direction | Change | Earliest → Latest |
+|--------|-----------|--------|-------------------|
+{trends_table}
+
+## Top Opportunities
+
+| Opportunity | Estimated Savings |
+|-------------|-------------------|
+{opportunities_table}
+
+## Recommendations
+
+{recommendations}
+
+---
+*CrUX data updated daily ~04:00 UTC. 28-day rolling average.*
+*INP replaced FID as the responsiveness Core Web Vital on March 12, 2024.*
+*Generated {timestamp}.*
diff --git a/skills/blog-google/assets/templates/gsc-performance-report.md b/skills/blog-google/assets/templates/gsc-performance-report.md
new file mode 100644
index 0000000..9a19a80
--- /dev/null
+++ b/skills/blog-google/assets/templates/gsc-performance-report.md
@@ -0,0 +1,44 @@
+# Google Search Console Performance Report
+
+**Property:** {property}
+**Date Range:** {start_date} — {end_date}
+**Search Type:** {search_type}
+
+## Summary
+
+| Metric | Value |
+|--------|-------|
+| Total Clicks | {total_clicks} |
+| Total Impressions | {total_impressions} |
+| Average CTR | {avg_ctr}% |
+| Average Position | {avg_position} |
+
+## Top Queries
+
+| # | Query | Clicks | Impressions | CTR | Position |
+|---|-------|--------|-------------|-----|----------|
+{queries_table}
+
+## Top Pages
+
+| # | Page | Clicks | Impressions | CTR | Position |
+|---|------|--------|-------------|-----|----------|
+{pages_table}
+
+## Quick Wins (Position 4-10, High Impressions)
+
+These queries rank on page 1 but below position 3. A small ranking improvement could yield significant traffic gains.
+
+| Query | Position | Impressions | Clicks | CTR | Opportunity |
+|-------|----------|-------------|--------|-----|-------------|
+{quick_wins_table}
+
+## Device Breakdown
+
+| Device | Clicks | Impressions | CTR | Position |
+|--------|--------|-------------|-----|----------|
+{device_table}
+
+---
+*Data freshness: Search Analytics has a 2-3 day lag. Data available for ~16 months.*
+*Generated {timestamp} via Google Search Console API.*
diff --git a/skills/blog-google/assets/templates/indexation-status-report.md b/skills/blog-google/assets/templates/indexation-status-report.md
new file mode 100644
index 0000000..c7d2ec0
--- /dev/null
+++ b/skills/blog-google/assets/templates/indexation-status-report.md
@@ -0,0 +1,43 @@
+# URL Indexation Status Report
+
+**Property:** {property}
+**URLs Inspected:** {total_urls}
+
+## Summary
+
+| Status | Count | Percentage |
+|--------|-------|-----------|
+| Indexed (PASS) | {pass_count} | {pass_pct}% |
+| Not Indexed (FAIL) | {fail_count} | {fail_pct}% |
+| Neutral | {neutral_count} | {neutral_pct}% |
+| Errors | {error_count} | {error_pct}% |
+
+## Detailed Results
+
+| URL | Verdict | Coverage State | Fetch State | Google Canonical | Last Crawl |
+|-----|---------|---------------|-------------|-----------------|------------|
+{results_table}
+
+## Canonical Mismatches
+
+URLs where Google selected a different canonical than declared:
+
+| URL | User Canonical | Google Canonical |
+|-----|---------------|-----------------|
+{canonical_mismatches_table}
+
+## Common Issues
+
+| Issue | Count | Priority | Action |
+|-------|-------|----------|--------|
+{issues_table}
+
+## Rich Results Detected
+
+| URL | Rich Result Type | Status |
+|-----|-----------------|--------|
+{rich_results_table}
+
+---
+*URL Inspection API: 2,000 inspections/day per site, 600/min.*
+*Generated {timestamp} via Google Search Console URL Inspection API.*
diff --git a/skills/blog-google/references/api-reference.md b/skills/blog-google/references/api-reference.md
new file mode 100644
index 0000000..fa974d1
--- /dev/null
+++ b/skills/blog-google/references/api-reference.md
@@ -0,0 +1,190 @@
+# Blog Google - API Reference
+
+Consolidated reference for all Google APIs used by the blog-google skill.
+
+---
+
+## PageSpeed Insights v5
+
+**Endpoint:** `GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed`
+
+| Param | Type | Description |
+|-------|------|-------------|
+| `url` | string | Required. URL to analyze |
+| `category` | string | `ACCESSIBILITY`, `BEST_PRACTICES`, `PERFORMANCE`, `SEO` (can specify multiple) |
+| `strategy` | string | `DESKTOP` or `MOBILE` (default) |
+| `key` | string | API key (optional but recommended) |
+
+Response contains `loadingExperience` (URL-level CrUX), `originLoadingExperience` (origin CrUX), and `lighthouseResult` with category scores and audit details.
+
+**Note:** Google is migrating CrUX field data out of PSI. Use CrUX API directly for field data; use PSI primarily for Lighthouse lab data.
+
+---
+
+## CrUX API (Daily)
+
+**Endpoint:** `POST https://chromeuxreport.googleapis.com/v1/records:queryRecord?key={API_KEY}`
+
+```json
+{
+ "origin": "https://example.com",
+ "formFactor": "PHONE",
+ "metrics": ["largest_contentful_paint", "interaction_to_next_paint", "cumulative_layout_shift"]
+}
+```
+
+- `origin` and `url` are mutually exclusive. Use `origin` for site-wide, `url` for a specific page.
+- `formFactor`: `DESKTOP`, `PHONE`, `TABLET` (omit for all).
+- Each metric returns `histogram` (density buckets), `percentiles.p75`, and `category`.
+- **CLS p75 is a string** (e.g., `"0.05"` not `0.05`). Always parse as float.
+- 404 = insufficient Chrome traffic (not an auth error).
+- Updated daily ~04:00 UTC with ~2-day lag.
+
+---
+
+## CrUX History API (Weekly)
+
+**Endpoint:** `POST https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key={API_KEY}`
+
+Same request format as CrUX API. Returns up to **25 weekly collection periods** as timeseries arrays (`p75s[]`, `densities[]`).
+
+- Updated **Mondays** ~04:00 UTC.
+- Each period = 28-day rolling average ending on a Sunday.
+- Watch for `"NaN"` strings in densities and `null` in percentiles for ineligible periods.
+
+---
+
+## Core Web Vitals Thresholds
+
+Current as of March 2026. INP replaced FID on March 12, 2024.
+
+| Metric | Good | Needs Improvement | Poor |
+|--------|------|-------------------|------|
+| **LCP** | ≤ 2,500ms | 2,500-4,000ms | > 4,000ms |
+| **INP** | ≤ 200ms | 200-500ms | > 500ms |
+| **CLS** | ≤ 0.1 | 0.1-0.25 | > 0.25 |
+| **FCP** | ≤ 1,800ms | 1,800-3,000ms | > 3,000ms |
+| **TTFB** | ≤ 800ms | 800-1,800ms | > 1,800ms |
+
+---
+
+## GSC Search Analytics
+
+**Endpoint:** `POST https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/searchAnalytics/query`
+
+### Request Body
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `startDate` | string | Required. YYYY-MM-DD |
+| `endDate` | string | Required. YYYY-MM-DD |
+| `dimensions` | string[] | `query`, `page`, `country`, `device`, `date`, `searchAppearance` |
+| `type` | string | `web`, `image`, `video`, `news`, `discover`, `googleNews` |
+| `dimensionFilterGroups` | object[] | Filter groups with `dimension`, `operator`, `expression` |
+| `rowLimit` | int | 1-25000 (default: 1000) |
+| `startRow` | int | Pagination offset (default: 0) |
+| `dataState` | string | `final` (default), `all` |
+
+### Filter Operators
+`contains`, `equals`, `notContains`, `notEquals`, `includingRegex`, `excludingRegex`
+
+### Response Fields
+Each row: `keys[]`, `clicks`, `impressions`, `ctr`, `position`.
+
+- Data has a **2-3 day lag**, available for ~16 months.
+- Country codes are **ISO 3166-1 alpha-3** (e.g., `USA`, `GBR`).
+
+---
+
+## GSC URL Inspection
+
+**Endpoint:** `POST https://searchconsole.googleapis.com/v1/urlInspection/index:inspect`
+
+```json
+{
+ "inspectionUrl": "https://example.com/blog/post",
+ "siteUrl": "sc-domain:example.com",
+ "languageCode": "en"
+}
+```
+
+### Key Response Fields (`indexStatusResult`)
+
+| Field | Values |
+|-------|--------|
+| `verdict` | `PASS`, `FAIL`, `NEUTRAL`, `PARTIAL` |
+| `coverageState` | Human-readable coverage description |
+| `robotsTxtState` | `ALLOWED`, `DISALLOWED` |
+| `indexingState` | `INDEXING_ALLOWED`, `BLOCKED_BY_META_TAG`, `BLOCKED_BY_HTTP_HEADER` |
+| `pageFetchState` | `SUCCESSFUL`, `SOFT_404`, `BLOCKED_ROBOTS_TXT`, `NOT_FOUND`, `SERVER_ERROR` |
+| `lastCrawlTime` | ISO 8601 timestamp |
+| `googleCanonical` | URL Google selected as canonical |
+| `crawledAs` | `DESKTOP`, `MOBILE` |
+
+---
+
+## GA4 Data API v1beta
+
+**Base URL:** `https://analyticsdata.googleapis.com/v1beta`
+
+### runReport Overview
+
+Key fields: `property`, `dimensions[]`, `metrics[]`, `dateRanges[]`, `dimensionFilter`, `orderBys[]`, `limit`.
+
+### Blog-Relevant Dimensions
+`date`, `landingPage`, `pagePath`, `pageTitle`, `sessionDefaultChannelGroup`, `sessionSource`, `sessionMedium`, `country`, `deviceCategory`
+
+### Blog-Relevant Metrics
+`sessions`, `totalUsers`, `screenPageViews`, `bounceRate`, `averageSessionDuration`, `engagementRate`, `keyEvents`
+
+### Organic Traffic Filter
+```json
+{
+ "filter": {
+ "fieldName": "sessionDefaultChannelGroup",
+ "stringFilter": { "matchType": "EXACT", "value": "Organic Search" }
+ }
+}
+```
+
+Uses token-based quotas (25K tokens/day per property). Set `returnPropertyQuota: true` to monitor.
+
+---
+
+## Cloud Natural Language API
+
+**Endpoint:** `POST https://language.googleapis.com/v2/documents:annotateText?key={API_KEY}`
+
+| Feature | What It Does | Blog Use |
+|---------|-------------|----------|
+| `extractEntities` | People, orgs, places with salience scores | Topic coverage depth, entity optimization |
+| `extractDocumentSentiment` | Document + sentence-level sentiment | Content tone assessment |
+| `classifyText` | Map content to 700+ Google categories | Topic relevance verification |
+
+Each entity includes `name`, `type`, `salience` (0-1), `sentiment`, and `metadata` (Wikipedia URL, Knowledge Graph MID).
+
+**Pricing:** 5,000 free units/month for entities and sentiment. Requires billing enabled.
+
+---
+
+## YouTube Data API v3
+
+YouTube mentions correlate strongly with AI citation visibility (GEO research).
+
+| Method | Quota Cost | Description |
+|--------|-----------|-------------|
+| `search.list` | 100 units | Search videos matching a query |
+| `videos.list` | 1 unit | Video details, statistics, tags |
+| `channels.list` | 1 unit | Channel info, subscriber count |
+
+Default quota: **10,000 units/day** (free). API key only, no OAuth needed.
+
+---
+
+## Keyword Planner (Google Ads API)
+
+Gold-standard source for keyword search volume. Methods: **GenerateKeywordIdeas** (suggestions from seeds) and **GenerateKeywordHistoricalMetrics** (volume for specific keywords). Returns volume, competition, CPC bids.
+
+- Without active ad spend, volumes are **bucketed ranges** ("1K-10K") not exact numbers
+- `competition` measures **advertiser competition**, not organic difficulty
+- Requires: Google Ads Manager Account + Developer Token + OAuth credentials
diff --git a/skills/blog-google/references/auth-setup.md b/skills/blog-google/references/auth-setup.md
new file mode 100644
index 0000000..4c191a4
--- /dev/null
+++ b/skills/blog-google/references/auth-setup.md
@@ -0,0 +1,126 @@
+# Blog Google - Authentication Setup
+
+## Overview
+
+Four credential tiers serve different API combinations:
+
+| Tier | Credentials | APIs Unlocked |
+|------|------------|---------------|
+| **0** | API Key only | PageSpeed Insights, CrUX, CrUX History, Knowledge Graph, YouTube Data |
+| **1** | + Service Account | + Search Console, Indexing API |
+| **2** | + GA4 property ID | + GA4 Data API |
+| **3** | + Google Ads tokens | + Keyword Planner |
+
+## Step 1: Create a Google Cloud Project
+
+1. Go to [console.cloud.google.com](https://console.cloud.google.com)
+2. Click **Select a project** > **New Project**
+3. Name it (e.g., "Claude Blog") and note the project ID
+4. Select the project after creation
+
+## Step 2: Enable APIs
+
+Navigate to **APIs & Services > Library** and enable:
+
+| API | Required For |
+|-----|-------------|
+| PageSpeed Insights API | Lighthouse lab data, CWV scores |
+| Chrome UX Report API | CrUX field data + History |
+| Google Search Console API | Search Analytics, URL Inspection, Sitemaps |
+| Web Search Indexing API | Indexing API v3 (new post notifications) |
+| Google Analytics Data API | GA4 organic traffic analysis |
+| YouTube Data API v3 | Video research for GEO/AEO optimization |
+| Cloud Natural Language API | Entity salience, sentiment, classification |
+| Knowledge Graph Search API | Entity/brand verification |
+
+## Step 3: Create an API Key (Tier 0)
+
+1. **APIs & Services > Credentials > Create Credentials > API key**
+2. Click **Restrict key** > under **API restrictions**, select the APIs above
+3. Copy the key (starts with `AIzaSy...`)
+
+## Step 4: Create a Service Account (Tier 1)
+
+1. **IAM & Admin > Service Accounts > Create Service Account**
+2. Name: `claude-blog` (or similar)
+3. Skip optional permissions steps
+4. Click on the created service account > **Keys > Add Key > Create new key > JSON**
+5. Download and store securely (e.g., `~/.config/claude-seo/service_account.json`)
+
+### Grant Search Console Access
+
+1. Go to [Google Search Console](https://search.google.com/search-console)
+2. Select your property > **Settings > Users and permissions > Add user**
+3. Paste the service account `client_email` from the JSON file
+4. Set permission: **Full** (read-only) or **Owner** (if using Indexing API)
+
+## Step 5: Set Up OAuth for Interactive Flows
+
+1. **APIs & Services > Credentials > Create Credentials > OAuth client ID**
+2. Application type: **Desktop app**
+3. Download the `client_secret_*.json` file
+4. Store at `~/.config/claude-seo/oauth_client.json`
+
+OAuth is needed for Keyword Planner and any user-consent flows.
+
+## Step 6: GA4 Property ID (Tier 2)
+
+1. Go to [Google Analytics](https://analytics.google.com)
+2. **Admin > Property Access Management > Add users** (+ icon)
+3. Paste the service account `client_email`, set role: **Viewer**
+4. Note the numeric property ID from **Admin > Property Details** (e.g., `123456789`)
+
+## Step 7: Google Ads Credentials (Tier 3)
+
+1. Create a Google Ads Manager Account at ads.google.com
+2. Apply for a Developer Token at Google Ads API Center
+3. Note: Without active ad spend, Keyword Planner returns bucketed ranges ("1K-10K")
+
+## Config File
+
+Config is shared with claude-seo at `~/.config/claude-seo/google-api.json`:
+
+```json
+{
+ "service_account_path": "~/.config/claude-seo/service_account.json",
+ "api_key": "AIzaSy...",
+ "default_property": "sc-domain:example.com",
+ "ga4_property_id": "properties/123456789",
+ "ads_developer_token": "YOUR_DEV_TOKEN",
+ "ads_customer_id": "123-456-7890"
+}
+```
+
+### GSC Property URL Formats
+
+| Format | Example | When to Use |
+|--------|---------|-------------|
+| Domain property | `sc-domain:example.com` | All URLs on the domain (recommended) |
+| URL-prefix property | `https://example.com/` | Only that specific prefix |
+
+## Environment Variable Fallbacks
+
+| Variable | Purpose |
+|----------|---------|
+| `GOOGLE_API_KEY` | API key for PSI/CrUX/YouTube/NLP/Knowledge Graph |
+| `GOOGLE_APPLICATION_CREDENTIALS` | Path to service account JSON |
+| `GA4_PROPERTY_ID` | GA4 property (e.g., `properties/123456789`) |
+| `GSC_PROPERTY` | Default GSC property (e.g., `sc-domain:example.com`) |
+
+## Verify Setup
+
+```bash
+python scripts/google_auth.py --check
+```
+
+## Quick Troubleshooting
+
+| Error | Fix |
+|-------|-----|
+| `403 Forbidden` on GSC | Service account email not added to property, or wrong permission level |
+| `403 Forbidden` on GA4 | Service account not added as Viewer in GA4 property |
+| `404 Not Found` on GSC | Wrong property URL format -- use `sc-domain:` or include trailing slash |
+| `404 Not Found` on CrUX | Site has insufficient Chrome traffic (not a credentials issue) |
+| `429 Rate Limit` | Wait and retry with backoff. See rate-limits-quotas.md |
+| `API not enabled` | Enable the specific API in GCP Console > APIs & Services > Library |
+| `Billing required` | NLP API requires billing enabled (free tier still applies) |
diff --git a/skills/blog-google/references/rate-limits-quotas.md b/skills/blog-google/references/rate-limits-quotas.md
new file mode 100644
index 0000000..8b04f72
--- /dev/null
+++ b/skills/blog-google/references/rate-limits-quotas.md
@@ -0,0 +1,75 @@
+# Blog Google - Rate Limits & Quotas
+
+## Consolidated Quota Table
+
+| API | Per-Minute | Per-Day | Cost | Auth Type | Scope |
+|-----|-----------|---------|------|-----------|-------|
+| GSC Search Analytics | 1,200 QPM/user, 1,200 QPM/site | 30M QPD/project | Free | Service Account | Per user + per site |
+| GSC URL Inspection | 600 QPM/site | 2,000 QPD/site | Free | Service Account | Per site |
+| GSC Sitemaps | Standard | Standard | Free | Service Account | Per site |
+| PageSpeed Insights v5 | 240 QPM | 25,000 QPD | Free | API Key | Per project |
+| CrUX API | 150 QPM (shared) | Unlimited | Free | API Key | Per project |
+| CrUX History API | 150 QPM (shared with CrUX) | Unlimited | Free | API Key | Per project |
+| Indexing API | 380 RPM total, 180 read/min | 200 publish/day | Free | Service Account | Per project |
+| GA4 Data API | 10 concurrent | ~25K tokens/day | Free | Service Account | Per property/project |
+| Knowledge Graph | -- | 100,000 QPD | Free | API Key | Per project |
+| Custom Search | -- | 10,000 QPD max | 100 free, $5/1K | API Key | Per project |
+| Web Risk | 6,000 QPM | 100K/month | Free tier | API Key | Per project |
+
+**Key distinction:** "Per site" quotas are scoped to a specific GSC property. "Per project" quotas are shared across all properties in a GCP project. "Per user" quotas are per authenticated user (service account).
+
+## Exponential Backoff Strategy
+
+When receiving 429 or 5xx errors:
+
+```
+Attempt 1: wait 1 second
+Attempt 2: wait 2 seconds
+Attempt 3: wait 4 seconds
+Attempt 4: wait 8 seconds
+Attempt 5: wait 16 seconds
+Max: give up after 5 retries
+```
+
+Add random jitter (0-500ms) to each wait to avoid thundering herd.
+
+## Common Error Codes
+
+| Code | Meaning | Applies To | Action |
+|------|---------|------------|--------|
+| 400 | Bad request | All | Check URL format, request body |
+| 401 | Unauthorized | Service Account APIs | Refresh credentials |
+| 403 | Forbidden | GSC, GA4, Indexing | Check permissions (service account access) |
+| 404 | Not found | CrUX, GSC | Insufficient traffic (CrUX) or invalid property (GSC) |
+| 429 | Rate limited | All | Backoff and retry. Check Retry-After header. |
+| 500 | Server error | All | Retry with backoff |
+| 503 | Service unavailable | All | Retry with backoff |
+
+## Retry-After Header
+
+Some Google APIs return a `Retry-After` header with 429 responses. When present, use this value (in seconds) instead of exponential backoff.
+
+## GA4 Token Budgeting
+
+GA4 uses a token system rather than simple request counts:
+- Simple 1-dimension, 1-metric report: ~1-5 tokens
+- Complex multi-dimension, multi-metric: ~10-100 tokens
+- Set `returnPropertyQuota: true` to monitor consumption
+- Daily limit: 25,000 tokens per property per project
+- Hourly limit: 5,000 tokens per property per project
+- Concurrent: max 10 simultaneous requests
+
+## CrUX Shared Quota
+
+The CrUX API and CrUX History API share the same 150 QPM quota per project. Plan accordingly if querying both APIs in the same workflow.
+
+## Cost Summary
+
+**All APIs used by blog-google are free** at normal usage levels. No billing is required for:
+- PSI, CrUX, CrUX History (API key, unlimited free)
+- GSC (service account, 30M QPD)
+- Indexing API (service account, 200 publish/day)
+- GA4 Data API (service account, 25K tokens/day)
+- Knowledge Graph (API key, 100K QPD)
+
+Only Custom Search and Web Risk have paid tiers at high volumes.
diff --git a/skills/blog-google/scripts/__init__.py b/skills/blog-google/scripts/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/skills/blog-google/scripts/crux_history.py b/skills/blog-google/scripts/crux_history.py
new file mode 100644
index 0000000..9bbc2d7
--- /dev/null
+++ b/skills/blog-google/scripts/crux_history.py
@@ -0,0 +1,317 @@
+#!/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
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key
+
+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,
+ }
+
+ 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(
+ f"{CRUX_HISTORY_ENDPOINT}?key={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: {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()
diff --git a/skills/blog-google/scripts/ga4_report.py b/skills/blog-google/scripts/ga4_report.py
new file mode 100644
index 0000000..9de2d93
--- /dev/null
+++ b/skills/blog-google/scripts/ga4_report.py
@@ -0,0 +1,478 @@
+#!/usr/bin/env python3
+"""
+GA4 Data API v1beta - organic traffic reporting.
+
+Queries the Google Analytics Data API for organic search traffic,
+top landing pages, and session metrics with channel filtering.
+
+Usage:
+ python ga4_report.py --property 123456789
+ python ga4_report.py --property 123456789 --days 90 --report top-pages
+ python ga4_report.py --property 123456789 --report organic --json
+"""
+
+import argparse
+import json
+import sys
+from datetime import datetime, timedelta
+from typing import Optional
+
+try:
+ from google.analytics.data_v1beta import BetaAnalyticsDataClient
+ from google.analytics.data_v1beta.types import (
+ DateRange,
+ Dimension,
+ Filter,
+ FilterExpression,
+ Metric,
+ OrderBy,
+ RunReportRequest,
+ )
+except ImportError:
+ print(
+ "Error: google-analytics-data required. "
+ "Install with: pip install google-analytics-data",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials, load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials, load_config
+
+GA4_SCOPES = ["https://www.googleapis.com/auth/analytics.readonly"]
+
+
+def _build_ga4_client():
+ """Build the GA4 BetaAnalyticsDataClient."""
+ credentials = get_oauth_credentials(GA4_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return BetaAnalyticsDataClient(credentials=credentials)
+ except Exception as e:
+ print(f"Error building GA4 client: {e}", file=sys.stderr)
+ return None
+
+
+def _resolve_property(property_id: str) -> str:
+ """Ensure property ID is in the correct format."""
+ if not property_id:
+ return ""
+ if property_id.startswith("properties/"):
+ return property_id
+ return f"properties/{property_id}"
+
+
+def organic_traffic_report(
+ property_id: str,
+ days: int = 28,
+ limit: int = 100,
+) -> dict:
+ """
+ Generate organic traffic report from GA4.
+
+ Filters by sessionDefaultChannelGroup == "Organic Search" and returns
+ daily sessions, top landing pages, and key metrics.
+
+ Args:
+ property_id: GA4 property ID (numeric or 'properties/123456789').
+ days: Number of days to query (default: 28).
+ limit: Max rows (default: 100).
+
+ Returns:
+ Dictionary with daily_data, top_pages, totals, and quota usage.
+ """
+ result = {
+ "property": property_id,
+ "report": "organic_traffic",
+ "date_range": None,
+ "totals": {},
+ "daily_data": [],
+ "top_pages": [],
+ "quota_tokens_used": None,
+ "error": None,
+ }
+
+ client = _build_ga4_client()
+ if not client:
+ result["error"] = (
+ "Could not build GA4 client. Ensure the service account has "
+ "Viewer access in GA4 Admin > Property Access Management."
+ )
+ return result
+
+ prop = _resolve_property(property_id)
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ end_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ # Daily organic sessions
+ try:
+ daily_request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="date")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ Metric(name="screenPageViews"),
+ Metric(name="bounceRate"),
+ Metric(name="averageSessionDuration"),
+ Metric(name="engagementRate"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(dimension=OrderBy.DimensionOrderBy(dimension_name="date"))],
+ limit=days + 5,
+ return_property_quota=True,
+ )
+
+ daily_response = client.run_report(daily_request)
+
+ for row in daily_response.rows:
+ result["daily_data"].append({
+ "date": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ "pageviews": int(row.metric_values[2].value),
+ "bounce_rate": round(float(row.metric_values[3].value) * 100, 1),
+ "avg_session_duration": round(float(row.metric_values[4].value), 1),
+ "engagement_rate": round(float(row.metric_values[5].value) * 100, 1),
+ })
+
+ # Quota info
+ if daily_response.property_quota:
+ pq = daily_response.property_quota
+ result["quota_tokens_used"] = {
+ "daily_consumed": pq.tokens_per_day.consumed if pq.tokens_per_day else None,
+ "daily_remaining": pq.tokens_per_day.remaining if pq.tokens_per_day else None,
+ "hourly_consumed": pq.tokens_per_hour.consumed if pq.tokens_per_hour else None,
+ "hourly_remaining": pq.tokens_per_hour.remaining if pq.tokens_per_hour else None,
+ }
+
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str or "PERMISSION_DENIED" in error_str:
+ result["error"] = (
+ f"Permission denied for property '{property_id}'. "
+ "Add the service account email as Viewer in "
+ "GA4 Admin > Property Access Management."
+ )
+ elif "404" in error_str or "NOT_FOUND" in error_str:
+ result["error"] = (
+ f"Property '{property_id}' not found. "
+ "Verify the numeric property ID in GA4 Admin > Property Details."
+ )
+ else:
+ result["error"] = f"GA4 API error: {e}"
+ return result
+
+ # Top landing pages by organic sessions
+ try:
+ pages_request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="landingPage")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ Metric(name="screenPageViews"),
+ Metric(name="bounceRate"),
+ Metric(name="engagementRate"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[
+ OrderBy(
+ metric=OrderBy.MetricOrderBy(metric_name="sessions"),
+ desc=True,
+ )
+ ],
+ limit=limit,
+ )
+
+ pages_response = client.run_report(pages_request)
+
+ for row in pages_response.rows:
+ result["top_pages"].append({
+ "landing_page": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ "pageviews": int(row.metric_values[2].value),
+ "bounce_rate": round(float(row.metric_values[3].value) * 100, 1),
+ "engagement_rate": round(float(row.metric_values[4].value) * 100, 1),
+ })
+
+ except Exception as e:
+ # Non-fatal: daily data succeeded, pages failed
+ result["pages_error"] = f"Error fetching top pages: {e}"
+
+ # Calculate totals
+ if result["daily_data"]:
+ total_sessions = sum(d["sessions"] for d in result["daily_data"])
+ total_users = sum(d["users"] for d in result["daily_data"])
+ total_pageviews = sum(d["pageviews"] for d in result["daily_data"])
+ result["totals"] = {
+ "sessions": total_sessions,
+ "users": total_users,
+ "pageviews": total_pageviews,
+ "avg_daily_sessions": round(total_sessions / len(result["daily_data"]), 1),
+ }
+
+ return result
+
+
+def top_pages_report(
+ property_id: str,
+ days: int = 28,
+ limit: int = 50,
+) -> dict:
+ """
+ Get top organic landing pages from GA4.
+
+ Args:
+ property_id: GA4 property ID.
+ days: Number of days.
+ limit: Max pages to return.
+
+ Returns:
+ Dictionary with top pages ranked by organic sessions.
+ """
+ report = organic_traffic_report(property_id, days, limit)
+ # Slim it down to just pages
+ return {
+ "property": property_id,
+ "report": "top_organic_pages",
+ "date_range": report.get("date_range"),
+ "pages": report.get("top_pages", []),
+ "total_organic_sessions": report.get("totals", {}).get("sessions", 0),
+ "quota_tokens_used": report.get("quota_tokens_used"),
+ "error": report.get("error"),
+ }
+
+
+def device_breakdown(
+ property_id: str,
+ days: int = 28,
+) -> dict:
+ """
+ Organic sessions broken down by device category.
+
+ Args:
+ property_id: GA4 property ID.
+ days: Number of days.
+
+ Returns:
+ Dictionary with device breakdown data.
+ """
+ result = {"property": property_id, "report": "device_breakdown", "devices": [], "error": None}
+
+ client = _build_ga4_client()
+ if not client:
+ result["error"] = "Could not build GA4 client."
+ return result
+
+ prop = _resolve_property(property_id)
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ end_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ try:
+ request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="deviceCategory")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ Metric(name="bounceRate"),
+ Metric(name="engagementRate"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
+ )
+ response = client.run_report(request)
+ for row in response.rows:
+ result["devices"].append({
+ "category": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ "bounce_rate": round(float(row.metric_values[2].value) * 100, 1),
+ "engagement_rate": round(float(row.metric_values[3].value) * 100, 1),
+ })
+ except Exception as e:
+ result["error"] = f"GA4 device breakdown error: {e}"
+
+ return result
+
+
+def country_breakdown(
+ property_id: str,
+ days: int = 28,
+ limit: int = 20,
+) -> dict:
+ """
+ Organic sessions broken down by country.
+
+ Args:
+ property_id: GA4 property ID.
+ days: Number of days.
+ limit: Max countries to return.
+
+ Returns:
+ Dictionary with country breakdown data.
+ """
+ result = {"property": property_id, "report": "country_breakdown", "countries": [], "error": None}
+
+ client = _build_ga4_client()
+ if not client:
+ result["error"] = "Could not build GA4 client."
+ return result
+
+ prop = _resolve_property(property_id)
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ end_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ try:
+ request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="country")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
+ limit=limit,
+ )
+ response = client.run_report(request)
+ for row in response.rows:
+ result["countries"].append({
+ "country": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ })
+ except Exception as e:
+ result["error"] = f"GA4 country breakdown error: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="GA4 Data API - organic traffic reporting"
+ )
+ parser.add_argument(
+ "--property", "-p",
+ help="GA4 property ID (numeric, e.g., 123456789). Uses config default if not specified.",
+ )
+ parser.add_argument("--days", "-d", type=int, default=28, help="Number of days (default: 28)")
+ parser.add_argument(
+ "--report", "-r",
+ choices=["organic", "top-pages", "device", "country"],
+ default="organic",
+ help="Report type (default: organic)",
+ )
+ parser.add_argument("--limit", type=int, default=50, help="Max rows (default: 50)")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ # Resolve property
+ prop = args.property
+ if not prop:
+ config = load_config()
+ prop = config.get("ga4_property_id") or ""
+ # Strip 'properties/' prefix if present for consistency
+ if prop and prop.startswith("properties/"):
+ prop = prop[len("properties/"):]
+ if not prop:
+ print(
+ "Error: No GA4 property specified. Use --property or set ga4_property_id in config.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+ if args.report == "top-pages":
+ result = top_pages_report(prop, args.days, args.limit)
+ elif args.report == "device":
+ result = device_breakdown(prop, args.days)
+ elif args.report == "country":
+ result = country_breakdown(prop, args.days, args.limit)
+ else:
+ result = organic_traffic_report(prop, args.days, args.limit)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ if args.report == "top-pages":
+ print(f"=== Top Organic Landing Pages ===")
+ print(f"Property: {prop} | Period: {result.get('date_range', {}).get('start')} to {result.get('date_range', {}).get('end')}")
+ print(f"Total organic sessions: {result.get('total_organic_sessions', 0):,}")
+ print()
+ for i, page in enumerate(result.get("pages", [])[:20], 1):
+ print(f" {i:2d}. {page['landing_page']}")
+ print(f" Sessions: {page['sessions']:,} | Users: {page['users']:,} | Bounce: {page['bounce_rate']}%")
+ else:
+ totals = result.get("totals", {})
+ print(f"=== GA4 Organic Traffic Report ===")
+ print(f"Property: {prop}")
+ dr = result.get("date_range", {})
+ print(f"Period: {dr.get('start')} to {dr.get('end')}")
+ print(f"\nSessions: {totals.get('sessions', 0):,} | Users: {totals.get('users', 0):,} | Pageviews: {totals.get('pageviews', 0):,}")
+ print(f"Avg Daily Sessions: {totals.get('avg_daily_sessions', 0):,.0f}")
+
+ quota = result.get("quota_tokens_used")
+ if quota and quota.get("daily_remaining") is not None:
+ print(f"\nQuota: {quota['daily_consumed']} tokens used / {quota['daily_remaining']} remaining (daily)")
+
+ pages = result.get("top_pages", [])
+ if pages:
+ print(f"\nTop {min(10, len(pages))} Organic Landing Pages:")
+ for i, page in enumerate(pages[:10], 1):
+ print(f" {i:2d}. {page['landing_page']} ({page['sessions']:,} sessions)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/google_auth.py b/skills/blog-google/scripts/google_auth.py
new file mode 100644
index 0000000..efd0a44
--- /dev/null
+++ b/skills/blog-google/scripts/google_auth.py
@@ -0,0 +1,753 @@
+#!/usr/bin/env python3
+"""
+Google API credential management for Claude SEO.
+
+Loads and validates credentials for Google Search Console, PageSpeed Insights,
+CrUX, Indexing API, and GA4. Supports service accounts, OAuth web credentials
+with token refresh, API keys, and environment variable fallbacks.
+
+Usage:
+ python google_auth.py --check # Check all credentials
+ python google_auth.py --check gsc # Check specific service
+ python google_auth.py --check --json # JSON output
+ python google_auth.py --setup # Show setup instructions
+ python google_auth.py --tier # Show detected credential tier
+ python google_auth.py --auth --creds /path/to/client_secret.json # OAuth browser flow
+"""
+
+import argparse
+import json
+import os
+import sys
+import time
+from typing import Optional
+
+CONFIG_PATH = os.path.expanduser("~/.config/claude-seo/google-api.json")
+TOKEN_PATH = os.path.expanduser("~/.config/claude-seo/oauth-token.json")
+
+# Service-to-scope mapping
+SCOPES = {
+ "gsc_readonly": "https://www.googleapis.com/auth/webmasters.readonly",
+ "gsc_write": "https://www.googleapis.com/auth/webmasters",
+ "indexing": "https://www.googleapis.com/auth/indexing",
+ "ga4": "https://www.googleapis.com/auth/analytics.readonly",
+}
+
+# Which services need which auth type
+SERVICE_AUTH = {
+ "psi": "api_key",
+ "crux": "api_key",
+ "crux_history": "api_key",
+ "gsc": "oauth_or_sa",
+ "indexing": "oauth_or_sa",
+ "ga4": "oauth_or_sa",
+}
+
+OAUTH_SCOPES = (
+ "https://www.googleapis.com/auth/indexing "
+ "https://www.googleapis.com/auth/webmasters "
+ "https://www.googleapis.com/auth/analytics.readonly"
+)
+OAUTH_REDIRECT_URI = "http://localhost:8085"
+
+# Human-readable service names
+SERVICE_NAMES = {
+ "psi": "PageSpeed Insights v5",
+ "crux": "Chrome UX Report (CrUX) API",
+ "crux_history": "CrUX History API",
+ "gsc": "Google Search Console API",
+ "indexing": "Google Indexing API v3",
+ "ga4": "GA4 Data API v1beta",
+}
+
+
+def load_config() -> dict:
+ """
+ Load configuration from config file with environment variable fallbacks.
+
+ Reads ~/.config/claude-seo/google-api.json first. Any missing fields
+ are filled from environment variables.
+
+ Returns:
+ Dictionary with keys: service_account_path, api_key,
+ default_property, ga4_property_id. Missing values are None.
+ """
+ config = {
+ "service_account_path": None,
+ "api_key": None,
+ "default_property": None,
+ "ga4_property_id": None,
+ }
+
+ # Load from config file
+ if os.path.exists(CONFIG_PATH):
+ try:
+ with open(CONFIG_PATH, "r") as f:
+ file_config = json.load(f)
+ config.update({k: v for k, v in file_config.items() if v})
+ except (json.JSONDecodeError, IOError) as e:
+ print(f"Warning: Could not read config file: {e}", file=sys.stderr)
+
+ # Environment variable fallbacks
+ if not config["service_account_path"]:
+ config["service_account_path"] = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
+
+ if not config["api_key"]:
+ config["api_key"] = os.environ.get("GOOGLE_API_KEY")
+
+ if not config["ga4_property_id"]:
+ config["ga4_property_id"] = os.environ.get("GA4_PROPERTY_ID")
+
+ if not config["default_property"]:
+ config["default_property"] = os.environ.get("GSC_PROPERTY")
+
+ return config
+
+
+def get_service_account_credentials(scopes: list):
+ """
+ Load Google service account credentials.
+
+ Args:
+ scopes: List of OAuth scope URLs.
+
+ Returns:
+ google.oauth2.service_account.Credentials object, or None on failure.
+ """
+ try:
+ from google.oauth2 import service_account
+ except ImportError:
+ print(
+ "Error: google-auth library required. "
+ "Install with: pip install google-auth",
+ file=sys.stderr,
+ )
+ return None
+
+ config = load_config()
+ sa_path = config.get("service_account_path")
+
+ if not sa_path:
+ return None
+
+ sa_path = os.path.expanduser(sa_path)
+ if not os.path.exists(sa_path):
+ print(
+ f"Error: Service account file not found: {sa_path}",
+ file=sys.stderr,
+ )
+ return None
+
+ try:
+ credentials = service_account.Credentials.from_service_account_file(
+ sa_path, scopes=scopes
+ )
+ return credentials
+ except Exception as e:
+ print(f"Error loading service account: {e}", file=sys.stderr)
+ return None
+
+
+def _load_oauth_client(creds_path: str) -> Optional[dict]:
+ """Load OAuth client credentials from a client_secret JSON file."""
+ try:
+ with open(creds_path, "r") as f:
+ data = json.load(f)
+ return data.get("web", data.get("installed", {}))
+ except (json.JSONDecodeError, IOError) as e:
+ print(f"Error reading OAuth client file: {e}", file=sys.stderr)
+ return None
+
+
+def _load_oauth_token() -> Optional[dict]:
+ """Load saved OAuth token from TOKEN_PATH."""
+ if not os.path.exists(TOKEN_PATH):
+ return None
+ try:
+ with open(TOKEN_PATH, "r") as f:
+ return json.load(f)
+ except (json.JSONDecodeError, IOError):
+ return None
+
+
+def _save_oauth_token(token_data: dict):
+ """Save OAuth token to TOKEN_PATH."""
+ os.makedirs(os.path.dirname(TOKEN_PATH), exist_ok=True)
+ with open(TOKEN_PATH, "w") as f:
+ json.dump(token_data, f, indent=2)
+
+
+def _refresh_oauth_token(client: dict, token_data: dict) -> Optional[dict]:
+ """Refresh an expired OAuth token using the refresh_token."""
+ import urllib.parse
+ import urllib.request
+
+ if not token_data.get("refresh_token"):
+ return None
+
+ params = urllib.parse.urlencode({
+ "client_id": client["client_id"],
+ "client_secret": client["client_secret"],
+ "refresh_token": token_data["refresh_token"],
+ "grant_type": "refresh_token",
+ }).encode()
+
+ try:
+ req = urllib.request.Request(client.get("token_uri", "https://oauth2.googleapis.com/token"), data=params)
+ with urllib.request.urlopen(req) as resp:
+ new_data = json.loads(resp.read())
+ token_data["access_token"] = new_data["access_token"]
+ token_data["expires_at"] = time.time() + new_data.get("expires_in", 3600)
+ _save_oauth_token(token_data)
+ return token_data
+ except Exception as e:
+ print(f"Error refreshing OAuth token: {e}", file=sys.stderr)
+ return None
+
+
+def get_oauth_credentials(scopes: list):
+ """
+ Get OAuth credentials from saved token, refreshing if needed.
+
+ Falls back to service account if no OAuth token is available.
+
+ Args:
+ scopes: List of OAuth scope URLs (used for service account fallback).
+
+ Returns:
+ google.oauth2.credentials.Credentials or service_account.Credentials, or None.
+ """
+ config = load_config()
+
+ # Try OAuth token first
+ token_data = _load_oauth_token()
+ if token_data and token_data.get("access_token"):
+ # Check if token needs refresh
+ if time.time() > token_data.get("expires_at", 0) - 60:
+ oauth_creds_path = config.get("oauth_client_path")
+ if oauth_creds_path:
+ client = _load_oauth_client(os.path.expanduser(oauth_creds_path))
+ if client:
+ token_data = _refresh_oauth_token(client, token_data)
+ if not token_data:
+ print("OAuth token refresh failed. Re-run --auth.", file=sys.stderr)
+ return get_service_account_credentials(scopes)
+
+ if token_data and token_data.get("access_token"):
+ try:
+ from google.oauth2.credentials import Credentials
+ return Credentials(
+ token=token_data["access_token"],
+ refresh_token=token_data.get("refresh_token"),
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=token_data.get("client_id"),
+ client_secret=token_data.get("client_secret"),
+ )
+ except ImportError:
+ print("Error: google-auth required. Install with: pip install google-auth", file=sys.stderr)
+
+ # Fall back to service account
+ return get_service_account_credentials(scopes)
+
+
+def run_oauth_flow(creds_path: str):
+ """
+ Run OAuth browser-based authentication flow.
+
+ Opens a browser for consent, captures the auth code via local HTTP server,
+ exchanges for tokens, and saves them.
+
+ Args:
+ creds_path: Path to the OAuth client_secret JSON file.
+ """
+ import http.server
+ import urllib.parse
+ import urllib.request
+ import webbrowser
+
+ client = _load_oauth_client(creds_path)
+ if not client:
+ print("Error: Could not load OAuth client credentials.", file=sys.stderr)
+ sys.exit(1)
+
+ auth_url = (
+ f"{client.get('auth_uri', 'https://accounts.google.com/o/oauth2/auth')}"
+ f"?client_id={client['client_id']}"
+ f"&redirect_uri={urllib.parse.quote(OAUTH_REDIRECT_URI)}"
+ f"&response_type=code"
+ f"&scope={urllib.parse.quote(OAUTH_SCOPES)}"
+ f"&access_type=offline&prompt=consent"
+ )
+
+ auth_code = [None]
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
+ if "code" in params:
+ auth_code[0] = params["code"][0]
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(b"<h1>Authentication successful!</h1><p>Close this tab.</p>")
+ else:
+ self.send_response(400)
+ self.end_headers()
+ def log_message(self, *a):
+ pass
+
+ server = http.server.HTTPServer(("localhost", 8085), Handler)
+ server.timeout = 300
+
+ print(f"\nOpen this URL in your browser:\n\n{auth_url}\n")
+ print("Waiting up to 5 minutes for authentication...")
+
+ try:
+ webbrowser.open(auth_url)
+ except Exception:
+ pass
+
+ server.handle_request()
+ server.server_close()
+
+ if not auth_code[0]:
+ print("\nAuthentication failed or timed out.", file=sys.stderr)
+ print("If the browser showed 'localhost refused to connect', copy the full URL")
+ print("from the browser address bar and run:")
+ print(f" python scripts/google_auth.py --exchange --creds {creds_path} --code 'THE_CODE'")
+ sys.exit(1)
+
+ # Exchange code for tokens
+ _exchange_code(client, auth_code[0])
+
+
+def _exchange_code(client: dict, code: str):
+ """Exchange an authorization code for tokens."""
+ import urllib.parse
+ import urllib.request
+
+ params = urllib.parse.urlencode({
+ "code": code,
+ "client_id": client["client_id"],
+ "client_secret": client["client_secret"],
+ "redirect_uri": OAUTH_REDIRECT_URI,
+ "grant_type": "authorization_code",
+ }).encode()
+
+ try:
+ req = urllib.request.Request(
+ client.get("token_uri", "https://oauth2.googleapis.com/token"), data=params
+ )
+ with urllib.request.urlopen(req) as resp:
+ token_data = json.loads(resp.read())
+ token_data["expires_at"] = time.time() + token_data.get("expires_in", 3600)
+ token_data["client_id"] = client["client_id"]
+ token_data["client_secret"] = client["client_secret"]
+ _save_oauth_token(token_data)
+ print("OAuth token saved successfully!")
+
+ # Also save the OAuth client path to config
+ config = load_config()
+ # Don't overwrite existing config, just suggest
+ print(f"\nToken saved to: {TOKEN_PATH}")
+ except Exception as e:
+ print(f"Error exchanging authorization code: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+def get_api_key() -> Optional[str]:
+ """
+ Get the Google API key from config or environment.
+
+ Returns:
+ API key string, or None if not configured.
+ """
+ config = load_config()
+ return config.get("api_key")
+
+
+def build_service(api_name: str, version: str, scopes: list):
+ """
+ Build a Google API discovery service client.
+
+ Args:
+ api_name: API name (e.g., 'searchconsole', 'indexing', 'pagespeedonline').
+ version: API version (e.g., 'v1', 'v3', 'v5').
+ scopes: OAuth scopes needed.
+
+ Returns:
+ googleapiclient.discovery.Resource object, or None on failure.
+ """
+ try:
+ from googleapiclient.discovery import build
+ except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ return None
+
+ credentials = get_oauth_credentials(scopes)
+ if not credentials:
+ return None
+
+ try:
+ service = build(api_name, version, credentials=credentials)
+ return service
+ except Exception as e:
+ print(f"Error building {api_name} service: {e}", file=sys.stderr)
+ return None
+
+
+def check_credentials(service: str) -> dict:
+ """
+ Validate credentials for a specific Google API service.
+
+ Args:
+ service: One of 'psi', 'crux', 'crux_history', 'gsc', 'indexing', 'ga4'.
+
+ Returns:
+ Dictionary with:
+ - available: bool
+ - method: 'api_key' or 'service_account'
+ - service: service name
+ - error: error message or None
+ """
+ result = {
+ "available": False,
+ "method": SERVICE_AUTH.get(service, "unknown"),
+ "service": SERVICE_NAMES.get(service, service),
+ "error": None,
+ }
+
+ config = load_config()
+
+ if SERVICE_AUTH.get(service) == "api_key":
+ api_key = config.get("api_key")
+ if api_key:
+ result["available"] = True
+ else:
+ result["error"] = (
+ "No API key found. Set GOOGLE_API_KEY environment variable "
+ f"or add 'api_key' to {CONFIG_PATH}"
+ )
+
+ elif SERVICE_AUTH.get(service) == "oauth_or_sa":
+ # Check OAuth token first
+ token_data = _load_oauth_token()
+ if token_data and token_data.get("access_token"):
+ result["available"] = True
+ result["method"] = "oauth_token"
+ expired = time.time() > token_data.get("expires_at", 0) - 60
+ if expired and token_data.get("refresh_token"):
+ result["note"] = "Token expired but refresh_token available (will auto-refresh)"
+ elif expired:
+ result["available"] = False
+ result["error"] = "OAuth token expired and no refresh_token. Re-run --auth."
+ else:
+ # Fall back to service account
+ sa_path = config.get("service_account_path")
+ if not sa_path:
+ result["error"] = (
+ "No OAuth token or service account found. Either:\n"
+ " 1. Run: python scripts/google_auth.py --auth --creds /path/to/client_secret.json\n"
+ f" 2. Or add 'service_account_path' to {CONFIG_PATH}"
+ )
+ else:
+ sa_path = os.path.expanduser(sa_path)
+ if not os.path.exists(sa_path):
+ result["error"] = f"Service account file not found: {sa_path}"
+ else:
+ try:
+ with open(sa_path, "r") as f:
+ sa_data = json.load(f)
+ if "client_email" not in sa_data or "private_key" not in sa_data:
+ result["error"] = "Service account JSON missing required fields (client_email, private_key)"
+ else:
+ result["available"] = True
+ result["method"] = "service_account"
+ result["client_email"] = sa_data.get("client_email")
+ except (json.JSONDecodeError, IOError) as e:
+ result["error"] = f"Invalid service account file: {e}"
+
+ # GA4 also needs property ID
+ if service == "ga4" and result["available"]:
+ ga4_id = config.get("ga4_property_id")
+ if not ga4_id:
+ result["available"] = False
+ result["error"] = (
+ "Credentials found but no GA4 property ID configured. "
+ f"Set GA4_PROPERTY_ID or add 'ga4_property_id' to {CONFIG_PATH}"
+ )
+ else:
+ result["error"] = f"Unknown service: {service}"
+
+ return result
+
+
+def detect_tier() -> dict:
+ """
+ Detect the credential tier available.
+
+ Returns:
+ Dictionary with:
+ - tier: 0, 1, or 2
+ - description: human-readable tier description
+ - capabilities: list of available API groups
+ - missing: what's needed for the next tier
+ """
+ config = load_config()
+
+ has_api_key = bool(config.get("api_key"))
+ has_authenticated = False
+ has_ga4 = False
+ auth_method = None
+
+ # Check OAuth token
+ token_data = _load_oauth_token()
+ if token_data and token_data.get("access_token"):
+ has_authenticated = True
+ auth_method = "oauth_token"
+
+ # Check service account
+ if not has_authenticated:
+ sa_path = config.get("service_account_path")
+ if sa_path:
+ sa_path = os.path.expanduser(sa_path)
+ if os.path.exists(sa_path):
+ try:
+ with open(sa_path, "r") as f:
+ sa_data = json.load(f)
+ if "client_email" in sa_data and "private_key" in sa_data:
+ has_authenticated = True
+ auth_method = "service_account"
+ except (json.JSONDecodeError, IOError):
+ pass
+
+ if has_authenticated and config.get("ga4_property_id"):
+ has_ga4 = True
+
+ if has_ga4:
+ return {
+ "tier": 2,
+ "description": "Full (API key + Service Account + GA4)",
+ "capabilities": [
+ "PageSpeed Insights", "CrUX", "CrUX History",
+ "Search Console", "URL Inspection", "Sitemaps",
+ "Indexing API", "GA4 Organic Traffic",
+ ],
+ "missing": None,
+ }
+ elif has_authenticated:
+ return {
+ "tier": 1,
+ "description": "Authenticated (API key + OAuth/Service Account)",
+ "capabilities": [
+ "PageSpeed Insights", "CrUX", "CrUX History",
+ "Search Console", "URL Inspection", "Sitemaps",
+ "Indexing API",
+ ],
+ "missing": "Add 'ga4_property_id' to unlock GA4 organic traffic reports",
+ }
+ elif has_api_key:
+ return {
+ "tier": 0,
+ "description": "API Key Only",
+ "capabilities": [
+ "PageSpeed Insights", "CrUX", "CrUX History",
+ ],
+ "missing": "Add a service account to unlock Search Console, URL Inspection, and Indexing API",
+ }
+ else:
+ return {
+ "tier": -1,
+ "description": "No credentials configured",
+ "capabilities": [],
+ "missing": (
+ f"Create config at {CONFIG_PATH} with at minimum an 'api_key' field. "
+ "Run with --setup for full instructions."
+ ),
+ }
+
+
+def print_setup_instructions():
+ """Print step-by-step setup instructions."""
+ print("""
+Google SEO API Setup Instructions
+=================================
+
+1. CREATE A GOOGLE CLOUD PROJECT
+ - Go to https://console.cloud.google.com
+ - Create a new project (or select existing)
+ - Note the project ID
+
+2. ENABLE APIs
+ In API Library (APIs & Services > Library), enable:
+ - Google Search Console API
+ - PageSpeed Insights API
+ - Chrome UX Report API
+ - Web Search Indexing API (for Indexing API)
+ - Google Analytics Data API (for GA4)
+
+3. CREATE AN API KEY (for PSI, CrUX -- free, no service account needed)
+ - APIs & Services > Credentials > Create Credentials > API key
+ - Restrict to: PageSpeed Insights API, Chrome UX Report API
+
+4. CREATE A SERVICE ACCOUNT (for GSC, Indexing API, GA4)
+ - IAM & Admin > Service Accounts > Create Service Account
+ - Download JSON key file, store securely
+
+5. GRANT ACCESS
+ - Search Console: Settings > Users and permissions > Add user
+ Paste the service account client_email, set as Owner (for Indexing API) or Full (read-only)
+ - GA4: Admin > Property Access Management > Add
+ Paste email, set Viewer role
+
+6. CREATE CONFIG FILE
+ mkdir -p ~/.config/claude-seo
+ Save to ~/.config/claude-seo/google-api.json:
+
+ {
+ "service_account_path": "/path/to/service_account.json",
+ "api_key": "AIzaSy...",
+ "default_property": "sc-domain:example.com",
+ "ga4_property_id": "properties/123456789"
+ }
+
+7. VERIFY
+ python scripts/google_auth.py --check
+
+ENVIRONMENT VARIABLE ALTERNATIVES:
+ GOOGLE_API_KEY - API key
+ GOOGLE_APPLICATION_CREDENTIALS - Path to service account JSON
+ GA4_PROPERTY_ID - GA4 property ID (e.g., properties/123456789)
+ GSC_PROPERTY - Default Search Console property
+""")
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google API credential management for Claude SEO"
+ )
+ parser.add_argument(
+ "--check",
+ nargs="?",
+ const="all",
+ metavar="SERVICE",
+ help="Check credentials. Optionally specify service: psi, crux, gsc, indexing, ga4",
+ )
+ parser.add_argument(
+ "--setup",
+ action="store_true",
+ help="Show setup instructions",
+ )
+ parser.add_argument(
+ "--tier",
+ action="store_true",
+ help="Show detected credential tier",
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Output as JSON",
+ )
+ parser.add_argument(
+ "--auth",
+ action="store_true",
+ help="Run OAuth browser-based authentication flow",
+ )
+ parser.add_argument(
+ "--exchange",
+ action="store_true",
+ help="Manually exchange an auth code for tokens",
+ )
+ parser.add_argument(
+ "--creds",
+ help="Path to OAuth client_secret JSON file (for --auth and --exchange)",
+ )
+ parser.add_argument(
+ "--code",
+ help="Authorization code to exchange (for --exchange)",
+ )
+
+ args = parser.parse_args()
+
+ if args.auth:
+ if not args.creds:
+ print("Error: --creds is required with --auth", file=sys.stderr)
+ sys.exit(1)
+ run_oauth_flow(args.creds)
+ return
+
+ if args.exchange:
+ if not args.creds or not args.code:
+ print("Error: --creds and --code are required with --exchange", file=sys.stderr)
+ sys.exit(1)
+ client = _load_oauth_client(args.creds)
+ if client:
+ _exchange_code(client, args.code)
+ return
+
+ if args.setup:
+ print_setup_instructions()
+ return
+
+ if args.tier:
+ tier_info = detect_tier()
+ if args.json:
+ print(json.dumps(tier_info, indent=2))
+ else:
+ print(f"Credential Tier: {tier_info['tier']} -- {tier_info['description']}")
+ if tier_info["capabilities"]:
+ print(f"Available APIs: {', '.join(tier_info['capabilities'])}")
+ if tier_info["missing"]:
+ print(f"Next tier: {tier_info['missing']}")
+ return
+
+ if args.check:
+ services = (
+ list(SERVICE_AUTH.keys())
+ if args.check == "all"
+ else [args.check]
+ )
+
+ results = {}
+ for svc in services:
+ if svc not in SERVICE_AUTH:
+ results[svc] = {"available": False, "error": f"Unknown service: {svc}"}
+ continue
+ results[svc] = check_credentials(svc)
+
+ if args.json:
+ tier_info = detect_tier()
+ output = {"tier": tier_info, "services": results}
+ print(json.dumps(output, indent=2))
+ else:
+ tier_info = detect_tier()
+ print(f"Credential Tier: {tier_info['tier']} -- {tier_info['description']}")
+ print()
+ for svc, result in results.items():
+ status = "OK" if result["available"] else "MISSING"
+ print(f" [{status}] {result.get('service', svc)}")
+ if result.get("error"):
+ print(f" {result['error']}")
+ if result.get("client_email"):
+ print(f" Service account: {result['client_email']}")
+ print()
+ if tier_info["missing"]:
+ print(f"Tip: {tier_info['missing']}")
+ return
+
+ # Default: show tier
+ tier_info = detect_tier()
+ if args.json:
+ print(json.dumps(tier_info, indent=2))
+ else:
+ print(f"Credential Tier: {tier_info['tier']} -- {tier_info['description']}")
+ if tier_info["missing"]:
+ print(f"Run --setup for configuration instructions.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/google_report.py b/skills/blog-google/scripts/google_report.py
new file mode 100644
index 0000000..d33fda1
--- /dev/null
+++ b/skills/blog-google/scripts/google_report.py
@@ -0,0 +1,789 @@
+#!/usr/bin/env python3
+"""
+Google SEO Report Generator - Professional PDF/HTML reports from API data.
+
+Consumes JSON output from seo-google scripts and generates formatted reports
+with charts, analytics, and actionable recommendations.
+
+Usage:
+ python google_report.py --type cwv-audit --data cwv-data.json --domain example.com
+ python google_report.py --type gsc-performance --data gsc-data.json --domain example.com
+ python google_report.py --type indexation --data inspect-data.json --domain example.com
+ python google_report.py --type full --data full-data.json --domain example.com
+ cat data.json | python google_report.py --type cwv-audit --domain example.com
+"""
+
+import argparse
+import json
+import os
+import sys
+from datetime import datetime
+from pathlib import Path
+from typing import Optional
+
+try:
+ import matplotlib
+ matplotlib.use("Agg")
+ import matplotlib.pyplot as plt
+ import matplotlib.patches as mpatches
+ import numpy as np
+except ImportError:
+ print("Error: matplotlib required. Install with: pip install matplotlib", file=sys.stderr)
+ sys.exit(1)
+
+try:
+ from weasyprint import HTML
+except ImportError:
+ print("Error: weasyprint required. Install with: pip install weasyprint", file=sys.stderr)
+ sys.exit(1)
+
+# ─── Brand Colors ────────────────────────────────────────────────────────────
+
+BRAND = {
+ "primary": "#1a56db",
+ "secondary": "#6366f1",
+ "accent": "#06b6d4",
+ "success": "#10b981",
+ "warning": "#f59e0b",
+ "danger": "#ef4444",
+ "dark": "#1e293b",
+ "light_bg": "#f8fafc",
+ "grid": "#e2e8f0",
+ "muted": "#94a3b8",
+}
+
+
+def _score_color(score):
+ if score >= 90:
+ return BRAND["success"]
+ elif score >= 50:
+ return BRAND["warning"]
+ return BRAND["danger"]
+
+
+def _rating_color(rating):
+ r = str(rating).lower().replace("-", "_").replace(" ", "_")
+ if r in ("good", "pass", "fast"):
+ return BRAND["success"]
+ elif r in ("needs_improvement", "needs-improvement", "average", "warn"):
+ return BRAND["warning"]
+ return BRAND["danger"]
+
+
+# ─── Chart Setup ─────────────────────────────────────────────────────────────
+
+def _setup_matplotlib():
+ plt.rcParams.update({
+ "font.family": "sans-serif",
+ "font.sans-serif": ["DejaVu Sans", "Arial", "Helvetica"],
+ "font.size": 11,
+ "axes.titlesize": 14,
+ "axes.titleweight": "bold",
+ "axes.labelsize": 11,
+ "axes.facecolor": "white",
+ "figure.facecolor": "white",
+ "axes.grid": False,
+ "axes.spines.top": False,
+ "axes.spines.right": False,
+ })
+
+
+_setup_matplotlib()
+
+
+# ─── Chart Functions ─────────────────────────────────────────────────────────
+
+def chart_lighthouse_gauges(data: dict, output_dir: Path) -> str:
+ """Generate 2x2 Lighthouse score gauges."""
+ scores = data.get("lighthouse_scores", {})
+ if not scores:
+ return ""
+
+ fig, axes = plt.subplots(2, 2, figsize=(8, 6), subplot_kw={"projection": "polar"})
+ categories = [
+ ("performance", "Performance"),
+ ("accessibility", "Accessibility"),
+ ("best-practices", "Best Practices"),
+ ("seo", "SEO"),
+ ]
+
+ for ax, (key, label) in zip(axes.flat, categories):
+ score = scores.get(key, 0)
+ theta_bg = np.linspace(np.pi, 0, 100)
+ theta_fill = np.linspace(np.pi, np.pi - (score / 100) * np.pi, 100)
+
+ ax.plot(theta_bg, [1] * 100, linewidth=16, color="#e2e8f0", solid_capstyle="round")
+ ax.plot(theta_fill, [1] * 100, linewidth=16, color=_score_color(score), solid_capstyle="round")
+
+ ax.text(np.pi / 2, 0.35, f"{score}", ha="center", va="center",
+ fontsize=28, fontweight="bold", color=BRAND["dark"])
+ ax.text(np.pi / 2, -0.05, label, ha="center", va="center",
+ fontsize=10, color=BRAND["muted"])
+
+ ax.set_ylim(0, 1.3)
+ ax.set_rticks([])
+ ax.set_thetagrids([])
+ ax.spines["polar"].set_visible(False)
+
+ plt.tight_layout(pad=2)
+ path = output_dir / "lighthouse_gauges.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_cwv_distributions(data: dict, output_dir: Path) -> str:
+ """Generate stacked horizontal bars for CWV metric distributions."""
+ crux = data.get("crux", {})
+ metrics = crux.get("metrics", {})
+ if not metrics:
+ return ""
+
+ cwv_order = [
+ "largest_contentful_paint", "interaction_to_next_paint",
+ "cumulative_layout_shift", "first_contentful_paint",
+ "experimental_time_to_first_byte",
+ ]
+
+ labels, goods, nis, poors = [], [], [], []
+ for name in cwv_order:
+ m = metrics.get(name)
+ if not m or "distribution" not in m:
+ continue
+ d = m["distribution"]
+ labels.append(m.get("label", name))
+ goods.append(d.get("good", 0))
+ nis.append(d.get("needs_improvement", 0))
+ poors.append(d.get("poor", 0))
+
+ if not labels:
+ return ""
+
+ fig, ax = plt.subplots(figsize=(8, max(2.5, len(labels) * 0.7)))
+ y = range(len(labels))
+
+ ax.barh(y, goods, color=BRAND["success"], label="Good", height=0.5)
+ ax.barh(y, nis, left=goods, color=BRAND["warning"], label="Needs Improvement", height=0.5)
+ left2 = [g + n for g, n in zip(goods, nis)]
+ ax.barh(y, poors, left=left2, color=BRAND["danger"], label="Poor", height=0.5)
+
+ ax.set_yticks(y)
+ ax.set_yticklabels(labels)
+ ax.set_xlim(0, 100)
+ ax.set_xlabel("% of page loads")
+ ax.legend(loc="lower right", fontsize=9)
+ ax.invert_yaxis()
+
+ for i, (g, n, p) in enumerate(zip(goods, nis, poors)):
+ if g > 10:
+ ax.text(g / 2, i, f"{g:.0f}%", ha="center", va="center", fontsize=8, color="white", fontweight="bold")
+ if n > 10:
+ ax.text(g + n / 2, i, f"{n:.0f}%", ha="center", va="center", fontsize=8, color="white", fontweight="bold")
+ if p > 10:
+ ax.text(g + n + p / 2, i, f"{p:.0f}%", ha="center", va="center", fontsize=8, color="white", fontweight="bold")
+
+ plt.tight_layout()
+ path = output_dir / "cwv_distributions.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_cwv_timeline(data: dict, output_dir: Path) -> str:
+ """Generate CWV timeline chart from CrUX History data."""
+ metrics = data.get("metrics", {})
+ periods = data.get("collection_periods", [])
+ if not metrics or not periods:
+ return ""
+
+ cwv_metrics = ["largest_contentful_paint", "interaction_to_next_paint", "cumulative_layout_shift"]
+ available = [m for m in cwv_metrics if m in metrics]
+ if not available:
+ return ""
+
+ fig, axes = plt.subplots(len(available), 1, figsize=(10, 3 * len(available)), sharex=True)
+ if len(available) == 1:
+ axes = [axes]
+
+ x_labels = [p.get("last", "")[-5:] for p in periods] # MM-DD format
+ x = range(len(x_labels))
+
+ for ax, metric_name in zip(axes, available):
+ m = metrics[metric_name]
+ p75s = m.get("p75_values", [])
+ label = m.get("label", metric_name)
+ good_t = m.get("good_threshold", 0)
+ poor_t = m.get("poor_threshold", 0)
+
+ valid_x = [i for i, v in enumerate(p75s) if v is not None]
+ valid_y = [v for v in p75s if v is not None]
+
+ if not valid_y:
+ continue
+
+ # Threshold bands
+ if good_t and poor_t:
+ ax.axhspan(0, good_t, alpha=0.1, color=BRAND["success"])
+ ax.axhspan(good_t, poor_t, alpha=0.1, color=BRAND["warning"])
+ ax.axhline(y=good_t, color=BRAND["success"], linestyle="--", alpha=0.5, linewidth=1)
+ ax.axhline(y=poor_t, color=BRAND["danger"], linestyle="--", alpha=0.5, linewidth=1)
+
+ ax.plot(valid_x, valid_y, color=BRAND["primary"], linewidth=2, marker="o", markersize=3)
+ ax.fill_between(valid_x, valid_y, alpha=0.1, color=BRAND["primary"])
+
+ unit = m.get("unit", "")
+ ax.set_ylabel(f"{label} (p75{unit})")
+ ax.set_title(label, fontsize=12, fontweight="bold")
+
+ if x_labels:
+ step = max(1, len(x_labels) // 8)
+ axes[-1].set_xticks(range(0, len(x_labels), step))
+ axes[-1].set_xticklabels([x_labels[i] for i in range(0, len(x_labels), step)], rotation=45, fontsize=8)
+
+ plt.tight_layout()
+ path = output_dir / "cwv_timeline.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_top_queries(data: dict, output_dir: Path) -> str:
+ """Generate horizontal bar chart of top queries by clicks."""
+ rows = data.get("rows", [])
+ if not rows:
+ return ""
+
+ top = sorted(rows, key=lambda r: r.get("clicks", 0), reverse=True)[:15]
+ if not top:
+ return ""
+
+ labels = [r.get("query", r.get("keys", ["?"])[0])[:40] for r in top]
+ clicks = [r.get("clicks", 0) for r in top]
+
+ fig, ax = plt.subplots(figsize=(8, max(3, len(labels) * 0.4)))
+ y = range(len(labels))
+ bars = ax.barh(y, clicks, color=BRAND["primary"], height=0.6)
+ ax.set_yticks(y)
+ ax.set_yticklabels(labels, fontsize=9)
+ ax.set_xlabel("Clicks")
+ ax.invert_yaxis()
+
+ for bar, val in zip(bars, clicks):
+ if val > 0:
+ ax.text(bar.get_width() + max(clicks) * 0.02, bar.get_y() + bar.get_height() / 2,
+ str(val), va="center", fontsize=8, color=BRAND["dark"])
+
+ plt.tight_layout()
+ path = output_dir / "top_queries.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_index_status(data: dict, output_dir: Path) -> str:
+ """Generate donut chart for URL inspection results."""
+ summary = data.get("summary", {})
+ if not summary:
+ return ""
+
+ labels, sizes, colors = [], [], []
+ for key, label, color in [
+ ("pass", "Indexed", BRAND["success"]),
+ ("fail", "Not Indexed", BRAND["danger"]),
+ ("neutral", "Neutral", BRAND["grid"]),
+ ("error", "Error", BRAND["muted"]),
+ ]:
+ val = summary.get(key, 0)
+ if val > 0:
+ labels.append(f"{label} ({val})")
+ sizes.append(val)
+ colors.append(color)
+
+ if not sizes:
+ return ""
+
+ fig, ax = plt.subplots(figsize=(5, 4))
+ wedges, texts, autotexts = ax.pie(
+ sizes, labels=labels, colors=colors, autopct="%1.0f%%",
+ startangle=90, pctdistance=0.75, textprops={"fontsize": 9},
+ )
+ centre = plt.Circle((0, 0), 0.50, fc="white")
+ ax.add_artist(centre)
+ total = sum(sizes)
+ ax.text(0, 0, f"{total}\nURLs", ha="center", va="center",
+ fontsize=16, fontweight="bold", color=BRAND["dark"])
+
+ plt.tight_layout()
+ path = output_dir / "index_status.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+# ─── CSS Template ────────────────────────────────────────────────────────────
+
+def _base_css(domain: str) -> str:
+ """Battle-tested A4 report CSS extracted from generate_pdf.py."""
+ return f"""
+ @page {{ size: A4; margin: 22mm 18mm 25mm 18mm;
+ @bottom-center {{ content: counter(page); font-size: 9pt; color: #94a3b8; font-family: 'DejaVu Sans', Arial, sans-serif; }}
+ @bottom-right {{ content: "{domain} Google SEO Report"; font-size: 8pt; color: #cbd5e1; font-family: 'DejaVu Sans', Arial, sans-serif; }}
+ }}
+ @page :first {{ margin: 0; @bottom-center {{ content: none; }} @bottom-right {{ content: none; }} }}
+ * {{ box-sizing: border-box; margin: 0; padding: 0; }}
+ body {{ font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; font-size: 10pt; line-height: 1.55; color: #1e293b; background: white; }}
+ .title-page {{ page: first; width: 210mm; height: 297mm; background: linear-gradient(135deg, #0f172a 0%, #1e3a5f 50%, #1a56db 100%); display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; color: white; position: relative; padding: 40mm 25mm; }}
+ .title-page .badge {{ background: rgba(255,255,255,0.12); border: 1px solid rgba(255,255,255,0.2); border-radius: 20px; padding: 6px 18px; font-size: 10pt; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 20mm; color: #93c5fd; }}
+ .title-page h1 {{ font-size: 30pt; font-weight: bold; margin-bottom: 6mm; letter-spacing: -0.5px; line-height: 1.2; }}
+ .title-page .subtitle {{ font-size: 16pt; color: #93c5fd; margin-bottom: 12mm; font-weight: 300; }}
+ .title-page .url {{ font-size: 14pt; color: #60a5fa; margin-bottom: 20mm; padding: 5mm 10mm; border: 1px solid rgba(96, 165, 250, 0.3); border-radius: 8px; background: rgba(96, 165, 250, 0.08); }}
+ .title-page .score-box {{ background: rgba(255,255,255,0.1); border: 2px solid rgba(255,255,255,0.2); border-radius: 16px; padding: 8mm 15mm; margin-bottom: 15mm; }}
+ .title-page .score-number {{ font-size: 48pt; font-weight: bold; color: #fbbf24; line-height: 1; }}
+ .title-page .score-label {{ font-size: 11pt; color: #93c5fd; margin-top: 2mm; }}
+ .title-page .meta {{ font-size: 10pt; color: #94a3b8; margin-top: 10mm; }}
+ div.section {{ page-break-before: always; }}
+ .section-header {{ background: #f8fafc; border-left: 4px solid #1a56db; padding: 5mm 6mm; margin-bottom: 6mm; page-break-after: avoid; }}
+ .section-header h2 {{ font-size: 16pt; color: #0f172a; margin-bottom: 1mm; }}
+ .section-header .section-score {{ font-size: 12pt; font-weight: bold; float: right; margin-top: -6mm; }}
+ h3 {{ font-size: 12pt; color: #1a56db; margin-top: 6mm; margin-bottom: 3mm; padding-bottom: 1.5mm; border-bottom: 1px solid #e2e8f0; page-break-after: avoid; }}
+ h4 {{ font-size: 10.5pt; color: #334155; margin-top: 4mm; margin-bottom: 2mm; page-break-after: avoid; }}
+ p {{ margin-bottom: 3mm; color: #334155; }}
+ .highlight {{ background: #fef3c7; border-left: 3px solid #f59e0b; padding: 3mm 4mm; margin: 4mm 0; font-size: 9.5pt; page-break-inside: avoid; }}
+ .critical-box {{ background: #fef2f2; border-left: 3px solid #ef4444; padding: 3mm 4mm; margin: 4mm 0; font-size: 9.5pt; page-break-inside: avoid; }}
+ .success-box {{ background: #f0fdf4; border-left: 3px solid #10b981; padding: 3mm 4mm; margin: 4mm 0; font-size: 9.5pt; page-break-inside: avoid; }}
+ table {{ width: 100%; border-collapse: collapse; margin: 4mm 0 6mm 0; font-size: 9pt; page-break-inside: avoid; }}
+ thead th {{ background: #f1f5f9; color: #0f172a; font-weight: bold; padding: 2.5mm 3mm; text-align: left; border-bottom: 2px solid #cbd5e1; font-size: 9pt; }}
+ tbody td {{ padding: 2.5mm 3mm; border-bottom: 1px solid #f1f5f9; vertical-align: top; }}
+ tbody tr:nth-child(even) {{ background: #fafbfc; }}
+ .status-pass {{ color: #10b981; font-weight: bold; }}
+ .status-fail {{ color: #ef4444; font-weight: bold; }}
+ .status-warn {{ color: #f59e0b; font-weight: bold; }}
+ .chart-container {{ text-align: center; margin: 5mm 0; page-break-inside: avoid; }}
+ .chart-container img {{ max-width: 100%; height: auto; }}
+ .chart-caption {{ font-size: 8.5pt; color: #94a3b8; font-style: italic; margin-top: 2mm; text-align: center; }}
+ .chart-half {{ display: inline-block; width: 48%; vertical-align: top; text-align: center; margin: 2mm 0; }}
+ .chart-half img {{ max-width: 100%; height: auto; }}
+ .two-col {{ display: table; width: 100%; table-layout: fixed; margin: 3mm 0; }}
+ .two-col .col {{ display: table-cell; vertical-align: top; padding: 0 2mm; }}
+ .metric-card {{ background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 3mm 4mm; text-align: center; margin: 2mm 0; }}
+ .metric-card .value {{ font-size: 18pt; font-weight: bold; line-height: 1.2; }}
+ .metric-card .label {{ font-size: 8pt; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }}
+ .action-item {{ background: #f8fafc; border-radius: 4px; padding: 3mm 4mm; margin: 3mm 0; border-left: 3px solid #cbd5e1; page-break-inside: avoid; }}
+ .action-item.critical {{ border-left-color: #ef4444; background: #fef2f2; }}
+ .action-item.high {{ border-left-color: #f59e0b; background: #fffbeb; }}
+ .action-item.medium {{ border-left-color: #1a56db; background: #eff6ff; }}
+ .priority-tag {{ display: inline-block; padding: 0.5mm 3mm; border-radius: 3px; font-size: 8pt; font-weight: bold; color: white; margin-right: 2mm; }}
+ .priority-critical {{ background: #ef4444; }}
+ .priority-high {{ background: #f59e0b; }}
+ .priority-medium {{ background: #1a56db; }}
+ .data-freshness {{ font-size: 8pt; color: #94a3b8; font-style: italic; margin-top: 4mm; padding-top: 2mm; border-top: 1px solid #e2e8f0; }}
+ """
+
+
+# ─── Section Builders ────────────────────────────────────────────────────────
+
+def _img(path):
+ """Convert file path to file:// URI for WeasyPrint."""
+ if not path:
+ return ""
+ return f'<div class="chart-container"><img src="file://{path}"></div>'
+
+
+def _metric_card(value, label, color=None):
+ style = f' style="color: {color};"' if color else ""
+ return f'<div class="metric-card"><div class="value"{style}>{value}</div><div class="label">{label}</div></div>'
+
+
+def _rating_class(rating):
+ r = str(rating).lower()
+ if "good" in r or "pass" in r:
+ return "status-pass"
+ elif "poor" in r or "fail" in r:
+ return "status-fail"
+ return "status-warn"
+
+
+def section_title_page(domain, report_title, subtitle, score=None, meta_items=None):
+ score_html = ""
+ if score is not None:
+ score_html = f'''
+ <div class="score-box">
+ <div class="score-number">{score}</div>
+ <div class="score-label">Lighthouse Performance Score</div>
+ </div>'''
+
+ meta_html = ""
+ if meta_items:
+ spans = " &bull; ".join(f"<span>{item}</span>" for item in meta_items)
+ meta_html = f'<div class="meta">{spans}</div>'
+
+ return f'''
+ <div class="title-page">
+ <div class="badge">{report_title}</div>
+ <h1>Google SEO Report</h1>
+ <div class="subtitle">{subtitle}</div>
+ <div class="url">{domain}</div>
+ {score_html}
+ {meta_html}
+ </div>'''
+
+
+def section_cwv_audit(psi_data, crux_data, charts, history_data=None):
+ """Build the Core Web Vitals audit section."""
+ html = '<div class="section"><div class="section-header"><h2>Core Web Vitals Audit</h2></div>'
+
+ # Lighthouse scores
+ psi = psi_data if isinstance(psi_data, dict) else {}
+ mobile = psi.get("psi", {}).get("mobile", psi)
+ scores = mobile.get("lighthouse_scores", {})
+ if scores:
+ html += '<h3>Lighthouse Scores</h3>'
+ html += charts.get("gauges", "")
+
+ # Lab metrics
+ lab = mobile.get("lab_metrics", {})
+ if lab:
+ html += '<h3>Lab Metrics</h3><table><thead><tr><th>Metric</th><th>Value</th><th>Score</th></tr></thead><tbody>'
+ for k, v in lab.items():
+ score_val = v.get("score")
+ score_pct = f"{score_val:.0%}" if score_val is not None else "N/A"
+ cls = "status-pass" if score_val and score_val >= 0.9 else ("status-warn" if score_val and score_val >= 0.5 else "status-fail")
+ html += f'<tr><td>{k}</td><td>{v.get("display", "")}</td><td class="{cls}">{score_pct}</td></tr>'
+ html += '</tbody></table>'
+
+ # CrUX field data
+ crux = crux_data if isinstance(crux_data, dict) else {}
+ crux_metrics = crux.get("metrics", {})
+ if crux_metrics:
+ html += '<h3>CrUX Field Data (28-day Rolling Average)</h3>'
+ html += charts.get("distributions", "")
+ html += '<table><thead><tr><th>Metric</th><th>p75</th><th>Rating</th><th>Good %</th><th>NI %</th><th>Poor %</th></tr></thead><tbody>'
+ for name, m in crux_metrics.items():
+ rating = m.get("rating", "?")
+ dist = m.get("distribution", {})
+ unit = m.get("unit", "")
+ p75 = m.get("p75", "?")
+ display_val = f"{p75:.3f}" if name == "cumulative_layout_shift" else f"{p75}{unit}"
+ html += f'<tr><td>{m.get("label", name)}</td><td>{display_val}</td>'
+ html += f'<td class="{_rating_class(rating)}">{rating.upper()}</td>'
+ html += f'<td>{dist.get("good", "N/A")}%</td><td>{dist.get("needs_improvement", "N/A")}%</td><td>{dist.get("poor", "N/A")}%</td></tr>'
+ html += '</tbody></table>'
+ cp = crux.get("collection_period", {})
+ if cp:
+ html += f'<p class="data-freshness">Collection period: {cp.get("first", "?")} to {cp.get("last", "?")}. CrUX data is a 28-day rolling average updated daily ~04:00 UTC.</p>'
+ elif crux.get("error"):
+ html += f'<div class="highlight"><strong>CrUX Field Data:</strong> {crux["error"]}</div>'
+
+ # CrUX History timeline
+ if history_data and not history_data.get("error"):
+ html += '<h3>Core Web Vitals Trends (25-week)</h3>'
+ html += charts.get("timeline", "")
+ trends = history_data.get("trends", {})
+ if trends:
+ html += '<table><thead><tr><th>Metric</th><th>Direction</th><th>Change</th><th>Earliest Avg</th><th>Latest Avg</th></tr></thead><tbody>'
+ for name, t in trends.items():
+ direction = t.get("direction", "?")
+ cls = "status-pass" if direction == "improving" else ("status-fail" if direction == "degrading" else "")
+ html += f'<tr><td>{t.get("label", name)}</td><td class="{cls}">{direction.upper()}</td>'
+ html += f'<td>{t.get("change_pct", 0):+.1f}%</td><td>{t.get("earliest_avg", "?")}</td><td>{t.get("latest_avg", "?")}</td></tr>'
+ html += '</tbody></table>'
+
+ # Failed audits
+ failed = mobile.get("failed_audits", [])
+ if failed:
+ html += f'<h3>Failed / Warning Audits ({len(failed)})</h3>'
+ html += '<table><thead><tr><th>Audit</th><th>Score</th><th>Details</th></tr></thead><tbody>'
+ for a in failed[:20]:
+ score_pct = f"{a['score']:.0%}" if a.get("score") is not None else "?"
+ html += f'<tr><td>{a.get("title", "")}</td><td class="status-fail">{score_pct}</td><td>{a.get("display", "")}</td></tr>'
+ html += '</tbody></table>'
+
+ # SEO audits
+ seo_audits = mobile.get("seo_audits", [])
+ if seo_audits:
+ seo_failed = [a for a in seo_audits if not a.get("pass")]
+ if seo_failed:
+ html += f'<h3>SEO Audit Issues ({len(seo_failed)})</h3>'
+ for a in seo_failed:
+ html += f'<div class="action-item critical"><h4>{a.get("title", "")}</h4></div>'
+ else:
+ html += f'<div class="success-box"><strong>SEO:</strong> All {len(seo_audits)} Lighthouse SEO checks passed.</div>'
+
+ # Accessibility issues
+ a11y = mobile.get("accessibility_audits", [])
+ if a11y:
+ html += f'<h3>Accessibility Issues ({len(a11y)})</h3>'
+ html += '<table><thead><tr><th>Issue</th><th>Score</th></tr></thead><tbody>'
+ for a in a11y:
+ html += f'<tr><td>{a.get("title", "")}</td><td class="status-fail">{a.get("score", 0):.0%}</td></tr>'
+ html += '</tbody></table>'
+
+ # Opportunities
+ opps = mobile.get("opportunities", [])
+ if opps:
+ html += f'<h3>Optimization Opportunities ({len(opps)})</h3>'
+ html += '<table><thead><tr><th>Opportunity</th><th>Estimated Savings</th></tr></thead><tbody>'
+ for o in opps:
+ html += f'<tr><td>{o.get("title", "")}</td><td>{o.get("savings_ms", 0)}ms</td></tr>'
+ html += '</tbody></table>'
+
+ html += '</div>'
+ return html
+
+
+def section_gsc_performance(gsc_data, charts):
+ """Build the GSC performance section."""
+ html = '<div class="section"><div class="section-header"><h2>Search Console Performance</h2></div>'
+
+ totals = gsc_data.get("totals", {})
+ dr = gsc_data.get("date_range", {})
+
+ if totals:
+ html += f'<p>Period: {dr.get("start", "?")} to {dr.get("end", "?")} | Property: {gsc_data.get("property", "?")}</p>'
+ clicks_val = f'{totals.get("clicks", 0):,}'
+ impr_val = f'{totals.get("impressions", 0):,}'
+ ctr_val = f'{totals.get("ctr", 0)}%'
+ rows_val = str(gsc_data.get("row_count", 0))
+ html += '<div class="two-col">'
+ html += f'<div class="col">{_metric_card(clicks_val, "Total Clicks", BRAND["primary"])}</div>'
+ html += f'<div class="col">{_metric_card(impr_val, "Total Impressions", BRAND["secondary"])}</div>'
+ html += '</div><div class="two-col">'
+ html += f'<div class="col">{_metric_card(ctr_val, "Average CTR", BRAND["accent"])}</div>'
+ html += f'<div class="col">{_metric_card(rows_val, "Queries Found")}</div>'
+ html += '</div>'
+
+ # Top queries chart
+ html += charts.get("top_queries", "")
+
+ # Top queries table
+ rows = gsc_data.get("rows", [])
+ if rows:
+ html += '<h3>Top Queries</h3>'
+ html += '<table><thead><tr><th>#</th><th>Query</th><th>Clicks</th><th>Impressions</th><th>CTR</th><th>Position</th></tr></thead><tbody>'
+ sorted_rows = sorted(rows, key=lambda r: r.get("clicks", 0), reverse=True)
+ for i, r in enumerate(sorted_rows[:25], 1):
+ query = r.get("query", r.get("keys", ["?"])[0])
+ html += f'<tr><td>{i}</td><td>{query}</td><td>{r.get("clicks", 0)}</td><td>{r.get("impressions", 0):,}</td>'
+ html += f'<td>{r.get("ctr", 0)}%</td><td>{r.get("position", 0)}</td></tr>'
+ html += '</tbody></table>'
+
+ # Quick wins
+ qw = gsc_data.get("quick_wins", [])
+ if qw:
+ html += f'<h3>Quick Wins ({len(qw)} opportunities)</h3>'
+ html += '<div class="highlight">These queries rank at position 4-10 with high impressions. A small ranking improvement could yield significant traffic gains.</div>'
+ html += '<table><thead><tr><th>Query</th><th>Position</th><th>Impressions</th><th>Clicks</th></tr></thead><tbody>'
+ for w in qw:
+ query = w.get("keys", ["?"])[0] if w.get("keys") else "?"
+ html += f'<tr><td>{query}</td><td>{w.get("position", 0)}</td><td>{w.get("impressions", 0):,}</td><td>{w.get("clicks", 0)}</td></tr>'
+ html += '</tbody></table>'
+
+ html += f'<p class="data-freshness">Search Analytics data has a 2-3 day lag. Data available for ~16 months.</p>'
+ html += '</div>'
+ return html
+
+
+def section_indexation(inspect_data, charts):
+ """Build the indexation status section."""
+ html = '<div class="section"><div class="section-header"><h2>Indexation Status</h2></div>'
+
+ summary = inspect_data.get("summary", {})
+ total = inspect_data.get("total", 0)
+
+ if summary:
+ html += charts.get("index_status", "")
+ html += f'<p>Total URLs inspected: {total}</p>'
+ html += '<div class="two-col">'
+ html += f'<div class="col">{_metric_card(summary.get("pass", 0), "Indexed", BRAND["success"])}</div>'
+ html += f'<div class="col">{_metric_card(summary.get("fail", 0), "Not Indexed", BRAND["danger"])}</div>'
+ html += '</div>'
+
+ results = inspect_data.get("results", [])
+ if results:
+ html += '<h3>Per-URL Results</h3>'
+ html += '<table><thead><tr><th>URL</th><th>Verdict</th><th>Coverage</th><th>Last Crawl</th></tr></thead><tbody>'
+ for r in results:
+ verdict = r.get("verdict", "?")
+ cls = "status-pass" if verdict == "PASS" else ("status-fail" if verdict == "FAIL" else "")
+ idx = r.get("index_status", {})
+ cov = idx.get("coverage_state", r.get("error", "N/A"))
+ crawl = idx.get("last_crawl_time", "N/A")
+ if crawl and crawl != "N/A":
+ crawl = crawl[:10]
+ html += f'<tr><td style="word-break:break-all;font-size:8pt;">{r.get("url", "?")}</td>'
+ html += f'<td class="{cls}">{verdict}</td><td>{cov}</td><td>{crawl}</td></tr>'
+ html += '</tbody></table>'
+
+ html += f'<p class="data-freshness">URL Inspection API: 2,000 inspections/day per site.</p>'
+ html += '</div>'
+ return html
+
+
+# ─── Report Assemblers ───────────────────────────────────────────────────────
+
+def generate_report(report_type, data, domain, output_dir, output_format="pdf"):
+ """
+ Generate a complete report.
+
+ Args:
+ report_type: 'cwv-audit', 'gsc-performance', 'indexation', or 'full'.
+ data: Dictionary with all input data.
+ domain: Domain name for the report header.
+ output_dir: Directory for output files.
+ output_format: 'pdf', 'html', or 'both'.
+
+ Returns:
+ Dictionary with output paths.
+ """
+ output_dir = Path(output_dir)
+ charts_dir = output_dir / "charts"
+ charts_dir.mkdir(parents=True, exist_ok=True)
+
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
+ result = {"report_type": report_type, "domain": domain, "files": [], "error": None}
+
+ # Generate charts based on report type
+ chart_paths = {}
+
+ if report_type in ("cwv-audit", "full"):
+ psi = data.get("psi", data)
+ mobile = psi.get("psi", {}).get("mobile", psi) if isinstance(psi, dict) else {}
+ chart_paths["gauges"] = _img(chart_lighthouse_gauges(mobile, charts_dir))
+ crux = data.get("crux", {})
+ chart_paths["distributions"] = _img(chart_cwv_distributions({"crux": crux} if crux else data, charts_dir))
+ history = data.get("crux_history", {})
+ if history and not history.get("error"):
+ chart_paths["timeline"] = _img(chart_cwv_timeline(history, charts_dir))
+
+ if report_type in ("gsc-performance", "full"):
+ gsc = data.get("gsc", data)
+ chart_paths["top_queries"] = _img(chart_top_queries(gsc, charts_dir))
+
+ if report_type in ("indexation", "full"):
+ inspect = data.get("inspection", data)
+ chart_paths["index_status"] = _img(chart_index_status(inspect, charts_dir))
+
+ # Build HTML sections
+ sections = []
+
+ # Title page
+ if report_type == "cwv-audit":
+ mobile = data.get("psi", data).get("psi", {}).get("mobile", data) if isinstance(data, dict) else {}
+ perf_score = mobile.get("lighthouse_scores", {}).get("performance")
+ sections.append(section_title_page(domain, "Core Web Vitals Audit", "Performance & User Experience Analysis",
+ score=perf_score, meta_items=[timestamp, "PSI + CrUX"]))
+ sections.append(section_cwv_audit(data, data.get("crux", {}), chart_paths, data.get("crux_history")))
+
+ elif report_type == "gsc-performance":
+ gsc = data.get("gsc", data)
+ clicks = gsc.get("totals", {}).get("clicks", 0)
+ sections.append(section_title_page(domain, "Search Console Performance", "Google Search Analytics Report",
+ score=clicks, meta_items=[timestamp, "Google Search Console API"]))
+ sections.append(section_gsc_performance(gsc, chart_paths))
+
+ elif report_type == "indexation":
+ inspect = data.get("inspection", data)
+ total = inspect.get("total", 0)
+ sections.append(section_title_page(domain, "Indexation Status Report", "URL Index Coverage Analysis",
+ score=total, meta_items=[timestamp, "URL Inspection API"]))
+ sections.append(section_indexation(inspect, chart_paths))
+
+ elif report_type == "full":
+ sections.append(section_title_page(domain, "Google SEO Intelligence Report", "Comprehensive Analysis",
+ meta_items=[timestamp, "All Google APIs"]))
+ if data.get("psi") or data.get("crux"):
+ sections.append(section_cwv_audit(data.get("psi", {}), data.get("crux", {}), chart_paths, data.get("crux_history")))
+ if data.get("gsc"):
+ sections.append(section_gsc_performance(data["gsc"], chart_paths))
+ if data.get("inspection"):
+ sections.append(section_indexation(data["inspection"], chart_paths))
+
+ # Assemble HTML
+ css = _base_css(domain)
+ body = "\n".join(sections)
+ html_content = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><style>{css}</style></head><body>{body}</body></html>"""
+
+ # Output
+ safe_domain = domain.replace(":", "_").replace("/", "_")
+ base_name = f"Google-SEO-Report-{safe_domain}-{report_type}"
+
+ if output_format in ("html", "both"):
+ html_path = output_dir / f"{base_name}.html"
+ with open(html_path, "w") as f:
+ f.write(html_content)
+ result["files"].append(str(html_path))
+
+ if output_format in ("pdf", "both"):
+ pdf_path = output_dir / f"{base_name}.pdf"
+ try:
+ HTML(string=html_content).write_pdf(str(pdf_path))
+ result["files"].append(str(pdf_path))
+ except Exception as e:
+ result["error"] = f"PDF generation failed: {e}"
+
+ return result
+
+
+# ─── CLI ─────────────────────────────────────────────────────────────────────
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google SEO Report Generator - Professional PDF/HTML reports"
+ )
+ parser.add_argument(
+ "--type", "-t",
+ choices=["cwv-audit", "gsc-performance", "indexation", "full"],
+ required=True,
+ help="Report type",
+ )
+ parser.add_argument("--data", "-d", help="Path to JSON data file (or pipe via stdin)")
+ parser.add_argument("--domain", required=True, help="Domain name for the report header")
+ parser.add_argument("--output-dir", "-o", default=".", help="Output directory (default: current)")
+ parser.add_argument(
+ "--format", "-f",
+ choices=["pdf", "html", "both"],
+ default="pdf",
+ help="Output format (default: pdf)",
+ )
+ parser.add_argument("--json", "-j", action="store_true", help="Output metadata as JSON")
+
+ args = parser.parse_args()
+
+ # Load data
+ if args.data:
+ try:
+ with open(args.data, "r") as f:
+ data = json.load(f)
+ except (json.JSONDecodeError, IOError) as e:
+ print(f"Error reading data file: {e}", file=sys.stderr)
+ sys.exit(1)
+ elif not sys.stdin.isatty():
+ try:
+ data = json.load(sys.stdin)
+ except json.JSONDecodeError as e:
+ print(f"Error parsing stdin JSON: {e}", file=sys.stderr)
+ sys.exit(1)
+ else:
+ print("Error: Provide --data file or pipe JSON via stdin.", file=sys.stderr)
+ sys.exit(1)
+
+ result = generate_report(
+ report_type=args.type,
+ data=data,
+ domain=args.domain,
+ output_dir=args.output_dir,
+ output_format=args.format,
+ )
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ for f in result.get("files", []):
+ print(f"Generated: {f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/gsc_inspect.py b/skills/blog-google/scripts/gsc_inspect.py
new file mode 100644
index 0000000..8551870
--- /dev/null
+++ b/skills/blog-google/scripts/gsc_inspect.py
@@ -0,0 +1,340 @@
+#!/usr/bin/env python3
+"""
+Google Search Console URL Inspection API helper.
+
+Inspects URLs for indexing status, canonical selection, crawl info,
+mobile usability, and rich results. Supports single URL and batch mode.
+
+Usage:
+ python gsc_inspect.py https://example.com/page --site-url sc-domain:example.com
+ python gsc_inspect.py --batch urls.txt --site-url sc-domain:example.com
+ python gsc_inspect.py https://example.com/page --json
+"""
+
+import argparse
+import json
+import sys
+import time
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials, load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials, load_config
+
+GSC_SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
+
+# Daily limit per site
+DAILY_LIMIT = 2000
+QPM_LIMIT = 600
+
+
+def _build_inspection_service():
+ """Build the Search Console v1 service for URL Inspection."""
+ credentials = get_oauth_credentials(GSC_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return build("searchconsole", "v1", credentials=credentials)
+ except Exception as e:
+ print(f"Error building service: {e}", file=sys.stderr)
+ return None
+
+
+def inspect_url(
+ inspection_url: str,
+ site_url: str,
+ language_code: str = "en",
+) -> dict:
+ """
+ Inspect a single URL via the GSC URL Inspection API.
+
+ Args:
+ inspection_url: The URL to inspect.
+ site_url: The GSC property (e.g., 'sc-domain:example.com').
+ language_code: Language for localized messages (default: 'en').
+
+ Returns:
+ Dictionary with inspection results including index status,
+ crawl info, canonical, mobile usability, and rich results.
+ """
+ result = {
+ "url": inspection_url,
+ "property": site_url,
+ "index_status": None,
+ "crawl_info": None,
+ "canonical": None,
+ "mobile_usability": None,
+ "rich_results": None,
+ "verdict": None,
+ "error": None,
+ }
+
+ service = _build_inspection_service()
+ if not service:
+ result["error"] = "Could not build GSC service. Check service account credentials."
+ return result
+
+ body = {
+ "inspectionUrl": inspection_url,
+ "siteUrl": site_url,
+ "languageCode": language_code,
+ }
+
+ try:
+ response = service.urlInspection().index().inspect(body=body).execute()
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ f"Permission denied. Add the service account as an Owner "
+ f"in GSC property '{site_url}'."
+ )
+ elif "429" in error_str:
+ result["error"] = (
+ f"Rate limit exceeded. URL Inspection: {QPM_LIMIT} QPM / {DAILY_LIMIT} QPD per site."
+ )
+ elif "400" in error_str:
+ result["error"] = (
+ f"Invalid request. Ensure the URL '{inspection_url}' belongs to "
+ f"property '{site_url}'."
+ )
+ else:
+ result["error"] = f"URL Inspection API error: {e}"
+ return result
+
+ ir = response.get("inspectionResult", {})
+
+ # Index status
+ idx = ir.get("indexStatusResult", {})
+ result["verdict"] = idx.get("verdict", "VERDICT_UNSPECIFIED")
+ result["index_status"] = {
+ "verdict": idx.get("verdict"),
+ "coverage_state": idx.get("coverageState"),
+ "robots_txt_state": idx.get("robotsTxtState"),
+ "indexing_state": idx.get("indexingState"),
+ "page_fetch_state": idx.get("pageFetchState"),
+ "last_crawl_time": idx.get("lastCrawlTime"),
+ "crawled_as": idx.get("crawledAs"),
+ "referring_urls": idx.get("referringUrls", []),
+ }
+
+ # Canonical
+ result["canonical"] = {
+ "google_canonical": idx.get("googleCanonical"),
+ "user_canonical": idx.get("userCanonical"),
+ "match": idx.get("googleCanonical") == idx.get("userCanonical")
+ if idx.get("googleCanonical") and idx.get("userCanonical") else None,
+ }
+
+ # Mobile usability (deprecated April 2023 but may still return data)
+ mu = ir.get("mobileUsabilityResult", {})
+ if mu:
+ result["mobile_usability"] = {
+ "verdict": mu.get("verdict"),
+ "issues": [
+ {"type": issue.get("issueType"), "message": issue.get("message")}
+ for issue in mu.get("issues", [])
+ ],
+ }
+
+ # Rich results
+ rr = ir.get("richResultsResult", {})
+ if rr:
+ result["rich_results"] = {
+ "verdict": rr.get("verdict"),
+ "detected_items": [
+ {
+ "type": item.get("richResultType"),
+ "items": [
+ {"name": i.get("name"), "issues": i.get("issues", [])}
+ for i in item.get("items", [])
+ ],
+ }
+ for item in rr.get("detectedItems", [])
+ ],
+ }
+
+ return result
+
+
+def batch_inspect(
+ urls: list,
+ site_url: str,
+ delay: float = 1.0,
+ language_code: str = "en",
+) -> dict:
+ """
+ Batch inspect multiple URLs with rate limiting.
+
+ Args:
+ urls: List of URLs to inspect.
+ site_url: GSC property.
+ delay: Seconds between requests (default: 1.0 for safety).
+ language_code: Language code.
+
+ Returns:
+ Dictionary with results list and summary.
+ """
+ result = {
+ "property": site_url,
+ "total": len(urls),
+ "results": [],
+ "summary": {
+ "pass": 0,
+ "fail": 0,
+ "neutral": 0,
+ "error": 0,
+ },
+ "error": None,
+ }
+
+ if len(urls) > DAILY_LIMIT:
+ result["error"] = (
+ f"Batch size ({len(urls)}) exceeds daily limit ({DAILY_LIMIT}). "
+ f"Only the first {DAILY_LIMIT} URLs will be processed."
+ )
+ urls = urls[:DAILY_LIMIT]
+
+ for i, url in enumerate(urls):
+ url = url.strip()
+ if not url:
+ continue
+
+ print(f"Inspecting [{i + 1}/{len(urls)}]: {url}", file=sys.stderr)
+
+ inspection = inspect_url(url, site_url, language_code)
+ result["results"].append(inspection)
+
+ verdict = inspection.get("verdict", "")
+ if inspection.get("error"):
+ result["summary"]["error"] += 1
+ elif verdict == "PASS":
+ result["summary"]["pass"] += 1
+ elif verdict == "FAIL":
+ result["summary"]["fail"] += 1
+ else:
+ result["summary"]["neutral"] += 1
+
+ # Rate limiting
+ if i < len(urls) - 1:
+ time.sleep(delay)
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Search Console URL Inspection API helper"
+ )
+ parser.add_argument("url", nargs="?", help="URL to inspect")
+ parser.add_argument(
+ "--site-url", "-s",
+ help="GSC property (e.g., sc-domain:example.com). Uses default from config if not specified.",
+ )
+ parser.add_argument(
+ "--batch", "-b",
+ help="File with URLs to inspect (one per line)",
+ )
+ parser.add_argument(
+ "--delay",
+ type=float,
+ default=1.0,
+ help="Delay between batch requests in seconds (default: 1.0)",
+ )
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ # Resolve site URL
+ site_url = args.site_url
+ if not site_url:
+ config = load_config()
+ site_url = config.get("default_property")
+ if not site_url:
+ print("Error: No site URL specified. Use --site-url or set default_property in config.", file=sys.stderr)
+ sys.exit(1)
+
+ if args.batch:
+ # Batch mode
+ try:
+ with open(args.batch, "r") as f:
+ urls = [line.strip() for line in f if line.strip()]
+ except IOError as e:
+ print(f"Error reading batch file: {e}", file=sys.stderr)
+ sys.exit(1)
+
+ result = batch_inspect(urls, site_url, delay=args.delay)
+ elif args.url:
+ result = inspect_url(args.url, site_url)
+ else:
+ parser.print_help()
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if args.batch:
+ summary = result.get("summary", {})
+ print(f"=== URL Inspection Batch Results ===")
+ print(f"Property: {site_url}")
+ print(f"Total: {result.get('total', 0)} | Pass: {summary.get('pass', 0)} | Fail: {summary.get('fail', 0)} | Errors: {summary.get('error', 0)}")
+ print()
+ for r in result.get("results", []):
+ verdict = r.get("verdict", "?")
+ status = {"PASS": "OK", "FAIL": "FAIL", "NEUTRAL": "--"}.get(verdict, "ERR")
+ print(f" [{status}] {r.get('url')}")
+ if r.get("error"):
+ print(f" Error: {r['error']}")
+ elif verdict == "FAIL":
+ idx = r.get("index_status", {})
+ print(f" Coverage: {idx.get('coverage_state')} | Fetch: {idx.get('page_fetch_state')}")
+ else:
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ sys.exit(1)
+
+ verdict = result.get("verdict", "?")
+ print(f"=== URL Inspection: {result.get('url')} ===")
+ print(f"Verdict: {verdict}")
+
+ idx = result.get("index_status", {})
+ if idx:
+ print(f"\nIndex Status:")
+ print(f" Coverage: {idx.get('coverage_state')}")
+ print(f" Robots.txt: {idx.get('robots_txt_state')}")
+ print(f" Indexing: {idx.get('indexing_state')}")
+ print(f" Page Fetch: {idx.get('page_fetch_state')}")
+ print(f" Last Crawl: {idx.get('last_crawl_time', 'N/A')}")
+ print(f" Crawled As: {idx.get('crawled_as')}")
+
+ canon = result.get("canonical", {})
+ if canon:
+ print(f"\nCanonical:")
+ print(f" Google: {canon.get('google_canonical', 'N/A')}")
+ print(f" User: {canon.get('user_canonical', 'N/A')}")
+ match = canon.get("match")
+ if match is not None:
+ print(f" Match: {'Yes' if match else 'MISMATCH'}")
+
+ rr = result.get("rich_results")
+ if rr and rr.get("detected_items"):
+ print(f"\nRich Results: {rr.get('verdict')}")
+ for item in rr.get("detected_items", []):
+ print(f" Type: {item.get('type')}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/gsc_query.py b/skills/blog-google/scripts/gsc_query.py
new file mode 100644
index 0000000..7385f2f
--- /dev/null
+++ b/skills/blog-google/scripts/gsc_query.py
@@ -0,0 +1,378 @@
+#!/usr/bin/env python3
+"""
+Google Search Console Search Analytics query helper.
+
+Queries the GSC Search Analytics API for clicks, impressions, CTR, and position
+data. Supports filtering by dimensions, auto-pagination, and quick-win detection.
+
+Usage:
+ python gsc_query.py --property sc-domain:example.com
+ python gsc_query.py --property sc-domain:example.com --days 90 --dimensions query
+ python gsc_query.py sitemaps --property sc-domain:example.com
+ python gsc_query.py sites
+"""
+
+import argparse
+import json
+import sys
+from datetime import datetime, timedelta
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials, load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials, load_config
+
+GSC_SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
+
+
+def _build_gsc_service():
+ """Build the Search Console API service."""
+ credentials = get_oauth_credentials(GSC_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return build("searchconsole", "v1", credentials=credentials)
+ except Exception as e:
+ print(f"Error building GSC service: {e}", file=sys.stderr)
+ return None
+
+
+def query_search_analytics(
+ site_url: str,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ dimensions: Optional[list] = None,
+ search_type: str = "web",
+ row_limit: int = 1000,
+ filters: Optional[list] = None,
+ data_state: str = "final",
+) -> dict:
+ """
+ Query GSC Search Analytics API.
+
+ Args:
+ site_url: GSC property (e.g., 'sc-domain:example.com' or 'https://example.com/').
+ start_date: Start date (YYYY-MM-DD). Default: 28 days ago.
+ end_date: End date (YYYY-MM-DD). Default: 3 days ago (data lag).
+ dimensions: List of dimensions: query, page, country, device, date, searchAppearance.
+ search_type: web, image, video, news, discover, googleNews.
+ row_limit: Max rows per request (1-25000). Auto-paginates if more.
+ filters: List of filter dicts with dimension, operator, expression.
+ data_state: 'final' or 'all' (includes fresh/unfinalized data).
+
+ Returns:
+ Dictionary with rows, totals, and quick_wins.
+ """
+ result = {
+ "property": site_url,
+ "rows": [],
+ "totals": {"clicks": 0, "impressions": 0, "ctr": 0, "position": 0},
+ "quick_wins": [],
+ "row_count": 0,
+ "error": None,
+ }
+
+ service = _build_gsc_service()
+ if not service:
+ result["error"] = "Could not build GSC service. Check service account credentials."
+ return result
+
+ if not start_date:
+ start_date = (datetime.now() - timedelta(days=28)).strftime("%Y-%m-%d")
+ if not end_date:
+ end_date = (datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")
+ if dimensions is None:
+ dimensions = ["query", "page"]
+
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ body = {
+ "startDate": start_date,
+ "endDate": end_date,
+ "dimensions": dimensions,
+ "type": search_type,
+ "rowLimit": min(row_limit, 25000),
+ "dataState": data_state,
+ }
+
+ if filters:
+ body["dimensionFilterGroups"] = [{"filters": filters}]
+
+ # Auto-paginate
+ all_rows = []
+ start_row = 0
+ page_size = min(row_limit, 25000)
+
+ try:
+ while True:
+ body["startRow"] = start_row
+ body["rowLimit"] = page_size
+
+ response = service.searchanalytics().query(
+ siteUrl=site_url, body=body
+ ).execute()
+
+ rows = response.get("rows", [])
+ all_rows.extend(rows)
+
+ if len(rows) < page_size:
+ break
+
+ start_row += page_size
+
+ # Safety: cap at 100,000 rows
+ if start_row >= 100000:
+ break
+
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ f"Permission denied for property '{site_url}'. "
+ "Ensure the service account email is added as a user in "
+ "Google Search Console > Settings > Users and permissions."
+ )
+ elif "404" in error_str:
+ result["error"] = (
+ f"Property '{site_url}' not found. "
+ "Use 'sc-domain:example.com' for domain properties or "
+ "'https://example.com/' for URL-prefix properties."
+ )
+ else:
+ result["error"] = f"GSC API error: {e}"
+ return result
+
+ # Process rows
+ total_clicks = 0
+ total_impressions = 0
+
+ for row in all_rows:
+ keys = row.get("keys", [])
+ clicks = row.get("clicks", 0)
+ impressions = row.get("impressions", 0)
+ ctr = row.get("ctr", 0)
+ position = row.get("position", 0)
+
+ processed = {
+ "keys": keys,
+ "clicks": clicks,
+ "impressions": impressions,
+ "ctr": round(ctr * 100, 2),
+ "position": round(position, 1),
+ }
+
+ # Label keys by dimension name
+ for i, dim in enumerate(dimensions):
+ if i < len(keys):
+ processed[dim] = keys[i]
+
+ result["rows"].append(processed)
+ total_clicks += clicks
+ total_impressions += impressions
+
+ result["row_count"] = len(all_rows)
+ result["totals"]["clicks"] = total_clicks
+ result["totals"]["impressions"] = total_impressions
+ if total_impressions > 0:
+ result["totals"]["ctr"] = round((total_clicks / total_impressions) * 100, 2)
+
+ # Quick wins: position 4-10 with high impressions
+ if "query" in dimensions:
+ sorted_by_impressions = sorted(all_rows, key=lambda r: r.get("impressions", 0), reverse=True)
+ for row in sorted_by_impressions[:200]:
+ pos = row.get("position", 0)
+ if 4 <= pos <= 10 and row.get("impressions", 0) > 50:
+ result["quick_wins"].append({
+ "keys": row.get("keys", []),
+ "position": round(pos, 1),
+ "impressions": row.get("impressions", 0),
+ "clicks": row.get("clicks", 0),
+ "ctr": round(row.get("ctr", 0) * 100, 2),
+ "opportunity": "Position 4-10 with high impressions -- small ranking improvement yields significant traffic gain",
+ })
+
+ result["quick_wins"] = result["quick_wins"][:20]
+
+ return result
+
+
+def list_sitemaps(site_url: str) -> dict:
+ """
+ List sitemaps for a GSC property.
+
+ Args:
+ site_url: GSC property URL.
+
+ Returns:
+ Dictionary with sitemaps list.
+ """
+ result = {"property": site_url, "sitemaps": [], "error": None}
+
+ service = _build_gsc_service()
+ if not service:
+ result["error"] = "Could not build GSC service."
+ return result
+
+ try:
+ response = service.sitemaps().list(siteUrl=site_url).execute()
+ for sm in response.get("sitemap", []):
+ result["sitemaps"].append({
+ "path": sm.get("path"),
+ "last_submitted": sm.get("lastSubmitted"),
+ "is_pending": sm.get("isPending"),
+ "is_index": sm.get("isSitemapsIndex"),
+ "type": sm.get("type"),
+ "warnings": sm.get("warnings", 0),
+ "errors": sm.get("errors", 0),
+ "contents": sm.get("contents", []),
+ })
+ except Exception as e:
+ result["error"] = f"Error listing sitemaps: {e}"
+
+ return result
+
+
+def list_sites() -> dict:
+ """
+ List all verified GSC properties.
+
+ Returns:
+ Dictionary with sites list.
+ """
+ result = {"sites": [], "error": None}
+
+ service = _build_gsc_service()
+ if not service:
+ result["error"] = "Could not build GSC service."
+ return result
+
+ try:
+ response = service.sites().list().execute()
+ for site in response.get("siteEntry", []):
+ result["sites"].append({
+ "url": site.get("siteUrl"),
+ "permission": site.get("permissionLevel"),
+ })
+ except Exception as e:
+ result["error"] = f"Error listing sites: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Search Console Search Analytics query helper"
+ )
+ parser.add_argument(
+ "command",
+ nargs="?",
+ default="query",
+ choices=["query", "sitemaps", "sites"],
+ help="Command: query (default), sitemaps, sites",
+ )
+ parser.add_argument(
+ "--property", "-p",
+ help="GSC property (e.g., sc-domain:example.com). Uses default from config if not specified.",
+ )
+ parser.add_argument("--days", "-d", type=int, default=28, help="Number of days (default: 28)")
+ parser.add_argument("--start-date", help="Start date (YYYY-MM-DD)")
+ parser.add_argument("--end-date", help="End date (YYYY-MM-DD)")
+ parser.add_argument(
+ "--dimensions",
+ default="query,page",
+ help="Comma-separated dimensions (default: query,page)",
+ )
+ parser.add_argument("--type", default="web", help="Search type (default: web)")
+ parser.add_argument("--limit", type=int, default=1000, help="Row limit (default: 1000)")
+ parser.add_argument(
+ "--device",
+ choices=["desktop", "mobile", "tablet"],
+ help="Filter by device type",
+ )
+ parser.add_argument("--country", help="Filter by country (ISO 3166-1 alpha-3, e.g., USA)")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ # Resolve property
+ prop = args.property
+ if not prop:
+ config = load_config()
+ prop = config.get("default_property")
+ if not prop and args.command != "sites":
+ print("Error: No property specified. Use --property or set default_property in config.", file=sys.stderr)
+ sys.exit(1)
+
+ if args.command == "sites":
+ result = list_sites()
+ elif args.command == "sitemaps":
+ result = list_sitemaps(prop)
+ else:
+ start = args.start_date or (datetime.now() - timedelta(days=args.days)).strftime("%Y-%m-%d")
+ end = args.end_date or (datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")
+ dims = [d.strip() for d in args.dimensions.split(",")]
+ filters = []
+ if args.device:
+ filters.append({
+ "dimension": "device",
+ "operator": "equals",
+ "expression": args.device.upper(),
+ })
+ if args.country:
+ filters.append({
+ "dimension": "country",
+ "operator": "equals",
+ "expression": args.country.upper(),
+ })
+ result = query_search_analytics(
+ prop, start_date=start, end_date=end,
+ dimensions=dims, search_type=args.type, row_limit=args.limit,
+ filters=filters if filters else None,
+ )
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if args.command == "sites":
+ print("=== Verified GSC Properties ===")
+ for site in result.get("sites", []):
+ print(f" {site['url']} ({site['permission']})")
+ elif args.command == "sitemaps":
+ print(f"=== Sitemaps for {prop} ===")
+ for sm in result.get("sitemaps", []):
+ status = "pending" if sm.get("is_pending") else "processed"
+ print(f" {sm['path']} [{status}] errors={sm.get('errors', 0)} warnings={sm.get('warnings', 0)}")
+ else:
+ totals = result.get("totals", {})
+ print(f"=== Search Analytics: {prop} ===")
+ print(f"Period: {result.get('date_range', {}).get('start')} to {result.get('date_range', {}).get('end')}")
+ print(f"Clicks: {totals.get('clicks', 0):,} | Impressions: {totals.get('impressions', 0):,} | CTR: {totals.get('ctr', 0)}% | Rows: {result.get('row_count', 0)}")
+
+ qw = result.get("quick_wins", [])
+ if qw:
+ print(f"\nQuick Wins ({len(qw)} found):")
+ for w in qw[:10]:
+ keys = " | ".join(w.get("keys", []))
+ print(f" Pos {w['position']} | {w['impressions']:,} imp | {w['clicks']} clicks | {keys}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/indexing_notify.py b/skills/blog-google/scripts/indexing_notify.py
new file mode 100644
index 0000000..9acff83
--- /dev/null
+++ b/skills/blog-google/scripts/indexing_notify.py
@@ -0,0 +1,313 @@
+#!/usr/bin/env python3
+"""
+Google Indexing API v3 - notify Google of URL updates and removals.
+
+Publishes URL_UPDATED or URL_DELETED notifications. Supports single URL
+and batch mode (up to 200 URLs/day). Includes quota tracking.
+
+IMPORTANT: The Indexing API is officially restricted to pages with
+JobPosting or BroadcastEvent/VideoObject structured data. Google may
+process other page types but provides no guarantees.
+
+Usage:
+ python indexing_notify.py https://example.com/jobs/123
+ python indexing_notify.py https://example.com/jobs/123 --action URL_DELETED
+ python indexing_notify.py --batch urls.txt
+ python indexing_notify.py --status https://example.com/jobs/123
+"""
+
+import argparse
+import json
+import sys
+import time
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+ from googleapiclient.http import BatchHttpRequest
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials
+
+INDEXING_SCOPES = ["https://www.googleapis.com/auth/indexing"]
+DAILY_QUOTA = 200
+
+SCOPE_WARNING = (
+ "NOTE: The Indexing API is officially for JobPosting and "
+ "BroadcastEvent/VideoObject pages only. Google may process other "
+ "page types but provides no guarantees."
+)
+
+
+def _build_indexing_service():
+ """Build the Indexing API v3 service."""
+ credentials = get_oauth_credentials(INDEXING_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return build("indexing", "v3", credentials=credentials)
+ except Exception as e:
+ print(f"Error building Indexing service: {e}", file=sys.stderr)
+ return None
+
+
+def notify_url(
+ url: str,
+ action: str = "URL_UPDATED",
+) -> dict:
+ """
+ Publish a single URL notification to the Indexing API.
+
+ Args:
+ url: The URL to notify about.
+ action: 'URL_UPDATED' or 'URL_DELETED'.
+
+ Returns:
+ Dictionary with notification result.
+ """
+ result = {
+ "url": url,
+ "action": action,
+ "notify_time": None,
+ "error": None,
+ }
+
+ service = _build_indexing_service()
+ if not service:
+ result["error"] = (
+ "Could not build Indexing service. Ensure the service account has "
+ "'https://www.googleapis.com/auth/indexing' scope and is added as "
+ "Owner in Google Search Console for the target domain."
+ )
+ return result
+
+ body = {
+ "url": url,
+ "type": action,
+ }
+
+ try:
+ response = service.urlNotifications().publish(body=body).execute()
+ metadata = response.get("urlNotificationMetadata", {})
+ latest = metadata.get("latestUpdate", {}) or metadata.get("latestRemove", {})
+ result["notify_time"] = latest.get("notifyTime")
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ "Permission denied. The service account must be added as an "
+ "Owner in Google Search Console for this domain. "
+ "Also ensure the Indexing API is enabled in your GCP project."
+ )
+ elif "429" in error_str:
+ result["error"] = (
+ f"Quota exceeded. Daily limit: {DAILY_QUOTA} publish requests. "
+ "Apply for a quota increase at https://developers.google.com/search/apis/indexing-api/v3/quota-increase"
+ )
+ elif "400" in error_str:
+ result["error"] = f"Invalid URL or request: {e}"
+ else:
+ result["error"] = f"Indexing API error: {e}"
+
+ return result
+
+
+def get_notification_metadata(url: str) -> dict:
+ """
+ Get the latest notification metadata for a URL.
+
+ Args:
+ url: The URL to check.
+
+ Returns:
+ Dictionary with latest update and remove timestamps.
+ """
+ result = {
+ "url": url,
+ "latest_update": None,
+ "latest_remove": None,
+ "error": None,
+ }
+
+ service = _build_indexing_service()
+ if not service:
+ result["error"] = "Could not build Indexing service."
+ return result
+
+ try:
+ response = service.urlNotifications().getMetadata(url=url).execute()
+ update = response.get("latestUpdate", {})
+ remove = response.get("latestRemove", {})
+
+ if update:
+ result["latest_update"] = {
+ "url": update.get("url"),
+ "type": update.get("type"),
+ "notify_time": update.get("notifyTime"),
+ }
+ if remove:
+ result["latest_remove"] = {
+ "url": remove.get("url"),
+ "type": remove.get("type"),
+ "notify_time": remove.get("notifyTime"),
+ }
+ except Exception as e:
+ if "404" in str(e):
+ result["error"] = "No notification metadata found for this URL."
+ else:
+ result["error"] = f"Error fetching metadata: {e}"
+
+ return result
+
+
+def batch_notify(
+ urls: list,
+ action: str = "URL_UPDATED",
+ delay: float = 0.5,
+) -> dict:
+ """
+ Batch notify multiple URLs with quota awareness.
+
+ Args:
+ urls: List of URLs.
+ action: 'URL_UPDATED' or 'URL_DELETED'.
+ delay: Seconds between requests.
+
+ Returns:
+ Dictionary with results and quota usage.
+ """
+ result = {
+ "action": action,
+ "total": len(urls),
+ "results": [],
+ "summary": {"success": 0, "error": 0},
+ "quota_warning": None,
+ "error": None,
+ }
+
+ if len(urls) > DAILY_QUOTA:
+ result["quota_warning"] = (
+ f"Batch size ({len(urls)}) exceeds daily quota ({DAILY_QUOTA}). "
+ f"Only the first {DAILY_QUOTA} URLs will be submitted."
+ )
+ urls = urls[:DAILY_QUOTA]
+
+ if len(urls) > 50:
+ result["quota_warning"] = (
+ f"Submitting {len(urls)} URLs will use {len(urls)}/{DAILY_QUOTA} "
+ f"of your daily quota."
+ )
+
+ for i, url in enumerate(urls):
+ url = url.strip()
+ if not url:
+ continue
+
+ print(f"Notifying [{i + 1}/{len(urls)}]: {url}", file=sys.stderr)
+
+ notification = notify_url(url, action)
+ result["results"].append(notification)
+
+ if notification.get("error"):
+ result["summary"]["error"] += 1
+ # Stop on quota errors
+ if "429" in str(notification.get("error", "")):
+ result["error"] = "Stopped: daily quota exceeded."
+ break
+ else:
+ result["summary"]["success"] += 1
+
+ if i < len(urls) - 1:
+ time.sleep(delay)
+
+ remaining = DAILY_QUOTA - result["summary"]["success"]
+ result["estimated_remaining_quota"] = max(0, remaining)
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Indexing API v3 - URL notification helper"
+ )
+ parser.add_argument("url", nargs="?", help="URL to notify")
+ parser.add_argument(
+ "--action", "-a",
+ choices=["URL_UPDATED", "URL_DELETED"],
+ default="URL_UPDATED",
+ help="Notification type (default: URL_UPDATED)",
+ )
+ parser.add_argument("--batch", "-b", help="File with URLs (one per line)")
+ parser.add_argument("--status", help="Check notification status for a URL")
+ parser.add_argument(
+ "--delay",
+ type=float,
+ default=0.5,
+ help="Delay between batch requests in seconds (default: 0.5)",
+ )
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if args.status:
+ result = get_notification_metadata(args.status)
+ elif args.batch:
+ print(SCOPE_WARNING, file=sys.stderr)
+ try:
+ with open(args.batch, "r") as f:
+ urls = [line.strip() for line in f if line.strip()]
+ except IOError as e:
+ print(f"Error reading batch file: {e}", file=sys.stderr)
+ sys.exit(1)
+ result = batch_notify(urls, args.action, delay=args.delay)
+ elif args.url:
+ print(SCOPE_WARNING, file=sys.stderr)
+ result = notify_url(args.url, args.action)
+ else:
+ parser.print_help()
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+
+ if args.status:
+ print(f"=== Notification Status: {args.status} ===")
+ update = result.get("latest_update")
+ remove = result.get("latest_remove")
+ if update:
+ print(f" Latest Update: {update.get('notify_time')} ({update.get('type')})")
+ if remove:
+ print(f" Latest Remove: {remove.get('notify_time')} ({remove.get('type')})")
+ if not update and not remove and not result.get("error"):
+ print(" No notifications found.")
+ elif args.batch:
+ summary = result.get("summary", {})
+ print(f"=== Batch Indexing Notification ===")
+ print(f"Action: {args.action}")
+ print(f"Total: {result.get('total', 0)} | Success: {summary.get('success', 0)} | Errors: {summary.get('error', 0)}")
+ print(f"Estimated remaining daily quota: {result.get('estimated_remaining_quota', '?')}")
+ if result.get("quota_warning"):
+ print(f"Warning: {result['quota_warning']}")
+ else:
+ if result.get("notify_time"):
+ print(f"Notified: {result['url']} ({result['action']}) at {result['notify_time']}")
+ elif not result.get("error"):
+ print(f"Notification sent for: {result['url']} ({result['action']})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/keyword_planner.py b/skills/blog-google/scripts/keyword_planner.py
new file mode 100644
index 0000000..fb25c5f
--- /dev/null
+++ b/skills/blog-google/scripts/keyword_planner.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""
+Google Ads API - Keyword Planner for SEO keyword research.
+
+Gold-standard source for keyword search volume, CPC, and competition data.
+Requires a Google Ads Manager account with a developer token.
+
+Usage:
+ python keyword_planner.py ideas "seo tools" --json
+ python keyword_planner.py volume "seo tools,seo audit,seo checker" --json
+ python keyword_planner.py forecast "seo tools" --json
+
+Prerequisites:
+ - Google Ads Manager account (can be free)
+ - Developer Token (apply at Google Ads API Center)
+ - OAuth credentials or service account
+ - google-ads Python library: pip install google-ads
+ - Config: ~/.config/claude-seo/google-api.json with:
+ {
+ "ads_developer_token": "YOUR_DEV_TOKEN",
+ "ads_customer_id": "123-456-7890",
+ "ads_login_customer_id": "123-456-7890"
+ }
+
+Note: Accounts without active ad spend receive bucketed volume ranges
+(e.g., "1K-10K") instead of exact numbers.
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+
+try:
+ from google.ads.googleads.client import GoogleAdsClient
+ from google.ads.googleads.errors import GoogleAdsException
+ HAS_GOOGLE_ADS = True
+except ImportError:
+ HAS_GOOGLE_ADS = False
+
+try:
+ from google_auth import load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import load_config
+
+
+def _build_ads_client() -> Optional[object]:
+ """Build Google Ads client from config."""
+ if not HAS_GOOGLE_ADS:
+ print(
+ "Error: google-ads library required. Install with: pip install google-ads",
+ file=sys.stderr,
+ )
+ return None
+
+ config = load_config()
+ dev_token = config.get("ads_developer_token")
+ customer_id = config.get("ads_customer_id", "").replace("-", "")
+ login_customer_id = config.get("ads_login_customer_id", "").replace("-", "")
+ oauth_client_path = config.get("oauth_client_path")
+
+ if not dev_token:
+ print(
+ "Error: No Google Ads developer token configured. "
+ "Add 'ads_developer_token' to ~/.config/claude-seo/google-api.json. "
+ "Get a token at: https://ads.google.com/aw/apicenter",
+ file=sys.stderr,
+ )
+ return None
+
+ if not customer_id:
+ print(
+ "Error: No Google Ads customer ID configured. "
+ "Add 'ads_customer_id' (format: 123-456-7890) to config.",
+ file=sys.stderr,
+ )
+ return None
+
+ try:
+ # Build from dict configuration
+ ads_config = {
+ "developer_token": dev_token,
+ "use_proto_plus": True,
+ }
+ if login_customer_id:
+ ads_config["login_customer_id"] = login_customer_id
+
+ # Try to use OAuth token if available
+ token_path = os.path.expanduser("~/.config/claude-seo/oauth-token.json")
+ if os.path.exists(token_path):
+ with open(token_path) as f:
+ token_data = json.load(f)
+ if oauth_client_path:
+ with open(os.path.expanduser(oauth_client_path)) as f:
+ client_data = json.load(f)
+ client_info = client_data.get("web", client_data.get("installed", {}))
+ ads_config["client_id"] = client_info.get("client_id")
+ ads_config["client_secret"] = client_info.get("client_secret")
+ ads_config["refresh_token"] = token_data.get("refresh_token")
+
+ client = GoogleAdsClient.load_from_dict(ads_config)
+ return client, customer_id
+
+ except Exception as e:
+ print(f"Error building Google Ads client: {e}", file=sys.stderr)
+ return None
+
+
+def generate_keyword_ideas(
+ seed_keywords: list,
+ language_id: str = "1000",
+ location_id: str = "2840",
+ limit: int = 50,
+) -> dict:
+ """
+ Generate keyword ideas from seed keywords.
+
+ Args:
+ seed_keywords: List of seed keyword strings.
+ language_id: Language ID (1000 = English).
+ location_id: Location ID (2840 = United States).
+ limit: Max results.
+
+ Returns:
+ Dictionary with keyword ideas and metrics.
+ """
+ result = {
+ "seed_keywords": seed_keywords,
+ "ideas": [],
+ "error": None,
+ }
+
+ client_data = _build_ads_client()
+ if not client_data:
+ result["error"] = "Could not build Google Ads client. Check config."
+ return result
+
+ client, customer_id = client_data
+
+ try:
+ kp_service = client.get_service("KeywordPlanIdeaService")
+ request = client.get_type("GenerateKeywordIdeasRequest")
+ request.customer_id = customer_id
+ request.language = f"languageConstants/{language_id}"
+ request.geo_target_constants.append(f"geoTargetConstants/{location_id}")
+ request.keyword_plan_network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH
+ request.keyword_seed.keywords.extend(seed_keywords)
+
+ response = kp_service.generate_keyword_ideas(request=request)
+
+ for idea in response.results:
+ metrics = idea.keyword_idea_metrics
+ monthly_volumes = []
+ for mv in metrics.monthly_search_volumes:
+ monthly_volumes.append({
+ "year": mv.year,
+ "month": mv.month,
+ "volume": mv.monthly_searches,
+ })
+
+ result["ideas"].append({
+ "keyword": idea.text,
+ "avg_monthly_searches": metrics.avg_monthly_searches,
+ "competition": metrics.competition.name if metrics.competition else "UNSPECIFIED",
+ "competition_index": metrics.competition_index,
+ "low_top_of_page_bid": metrics.low_top_of_page_bid_micros / 1_000_000 if metrics.low_top_of_page_bid_micros else None,
+ "high_top_of_page_bid": metrics.high_top_of_page_bid_micros / 1_000_000 if metrics.high_top_of_page_bid_micros else None,
+ "monthly_volumes": monthly_volumes[-12:] if monthly_volumes else [],
+ })
+
+ if len(result["ideas"]) >= limit:
+ break
+
+ # Sort by volume descending
+ result["ideas"].sort(key=lambda k: k.get("avg_monthly_searches", 0) or 0, reverse=True)
+
+ except GoogleAdsException as e:
+ errors = [err.message for err in e.failure.errors]
+ result["error"] = f"Google Ads API error: {'; '.join(errors)}"
+ except Exception as e:
+ result["error"] = f"Keyword Planner error: {e}"
+
+ return result
+
+
+def get_keyword_volumes(
+ keywords: list,
+ language_id: str = "1000",
+ location_id: str = "2840",
+) -> dict:
+ """
+ Get search volume for specific keywords.
+
+ Args:
+ keywords: List of keywords to check.
+ language_id: Language ID.
+ location_id: Location ID.
+
+ Returns:
+ Dictionary with keyword metrics.
+ """
+ result = {
+ "keywords": [],
+ "error": None,
+ }
+
+ client_data = _build_ads_client()
+ if not client_data:
+ result["error"] = "Could not build Google Ads client."
+ return result
+
+ client, customer_id = client_data
+
+ try:
+ kp_service = client.get_service("KeywordPlanIdeaService")
+ request = client.get_type("GenerateKeywordHistoricalMetricsRequest")
+ request.customer_id = customer_id
+ request.keywords.extend(keywords)
+ request.language = f"languageConstants/{language_id}"
+ request.geo_target_constants.append(f"geoTargetConstants/{location_id}")
+ request.keyword_plan_network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH
+
+ response = kp_service.generate_keyword_historical_metrics(request=request)
+
+ for kw_result in response.results:
+ metrics = kw_result.keyword_metrics
+ result["keywords"].append({
+ "keyword": kw_result.text,
+ "avg_monthly_searches": metrics.avg_monthly_searches,
+ "competition": metrics.competition.name if metrics.competition else "UNSPECIFIED",
+ "competition_index": metrics.competition_index,
+ "low_top_of_page_bid": metrics.low_top_of_page_bid_micros / 1_000_000 if metrics.low_top_of_page_bid_micros else None,
+ "high_top_of_page_bid": metrics.high_top_of_page_bid_micros / 1_000_000 if metrics.high_top_of_page_bid_micros else None,
+ })
+
+ except GoogleAdsException as e:
+ errors = [err.message for err in e.failure.errors]
+ result["error"] = f"Google Ads API error: {'; '.join(errors)}"
+ except Exception as e:
+ result["error"] = f"Keyword volume error: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Ads Keyword Planner - SEO keyword research"
+ )
+ parser.add_argument(
+ "command",
+ choices=["ideas", "volume"],
+ help="Command: ideas (keyword suggestions), volume (search volume lookup)",
+ )
+ parser.add_argument("keywords", help="Seed keyword(s), comma-separated for volume")
+ parser.add_argument("--limit", type=int, default=50, help="Max results for ideas (default: 50)")
+ parser.add_argument("--language", default="1000", help="Language ID (default: 1000 = English)")
+ parser.add_argument("--location", default="2840", help="Location ID (default: 2840 = US)")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if args.command == "ideas":
+ seeds = [k.strip() for k in args.keywords.split(",")]
+ result = generate_keyword_ideas(seeds, language_id=args.language, location_id=args.location, limit=args.limit)
+ elif args.command == "volume":
+ kws = [k.strip() for k in args.keywords.split(",")]
+ result = get_keyword_volumes(kws, language_id=args.language, location_id=args.location)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ if args.command == "ideas":
+ print(f"=== Keyword Ideas ===")
+ for i, idea in enumerate(result.get("ideas", [])[:20], 1):
+ vol = idea.get("avg_monthly_searches", "?")
+ comp = idea.get("competition", "?")
+ bid_low = idea.get("low_top_of_page_bid")
+ bid_high = idea.get("high_top_of_page_bid")
+ bid_str = f"${bid_low:.2f}-${bid_high:.2f}" if bid_low and bid_high else "N/A"
+ print(f" {i:2d}. {idea['keyword']:40s} | Vol: {vol:>8} | Comp: {comp:8s} | CPC: {bid_str}")
+ elif args.command == "volume":
+ print(f"=== Keyword Volumes ===")
+ for kw in result.get("keywords", []):
+ vol = kw.get("avg_monthly_searches", "?")
+ comp = kw.get("competition", "?")
+ print(f" {kw['keyword']:40s} | Vol: {vol:>8} | Comp: {comp}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/nlp_analyze.py b/skills/blog-google/scripts/nlp_analyze.py
new file mode 100644
index 0000000..c635035
--- /dev/null
+++ b/skills/blog-google/scripts/nlp_analyze.py
@@ -0,0 +1,306 @@
+#!/usr/bin/env python3
+"""
+Google Cloud Natural Language API - Entity, sentiment, and content analysis.
+
+Enhances E-E-A-T scoring with NLP entity coverage, sentiment analysis,
+and Google's own content classification taxonomy.
+
+Usage:
+ python nlp_analyze.py --text "Your content here" --json
+ python nlp_analyze.py --url https://example.com --json
+ python nlp_analyze.py --text "Your content" --features entities,sentiment,classify
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+
+try:
+ import requests
+except ImportError:
+ print("Error: requests library required. Install with: pip install requests", file=sys.stderr)
+ sys.exit(1)
+
+try:
+ from google_auth import get_api_key
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key
+
+NLP_ENDPOINT = "https://language.googleapis.com/v2/documents:annotateText"
+
+# Free tier: 5,000 units/month per feature
+# Paid: $0.001 per 1,000-character unit for entity/sentiment
+FEATURES = {
+ "entities": "extractEntities",
+ "sentiment": "extractDocumentSentiment",
+ "classify": "classifyText",
+ "categories": "classifyText",
+ "moderate": "moderateText",
+}
+
+
+def analyze_text(
+ text: str,
+ features: Optional[list] = None,
+ api_key: Optional[str] = None,
+ language: str = "en",
+) -> dict:
+ """
+ Analyze text using Google Cloud Natural Language API.
+
+ Args:
+ text: Text content to analyze (max 1M characters).
+ features: List of features: entities, sentiment, classify, moderate.
+ api_key: Google API key.
+ language: Language code (default: en).
+
+ Returns:
+ Dictionary with entities, sentiment, categories, and moderation results.
+ """
+ result = {
+ "text_length": len(text),
+ "language": language,
+ "entities": [],
+ "sentiment": None,
+ "categories": [],
+ "moderation": [],
+ "error": None,
+ }
+
+ key = api_key or get_api_key()
+ if not key:
+ result["error"] = "No API key. Set GOOGLE_API_KEY or add 'api_key' to config."
+ return result
+
+ if features is None:
+ features = ["entities", "sentiment", "classify"]
+
+ # Build request
+ feature_map = {}
+ for f in features:
+ api_feature = FEATURES.get(f)
+ if api_feature:
+ feature_map[api_feature] = True
+
+ body = {
+ "document": {
+ "type": "PLAIN_TEXT",
+ "content": text[:100000], # API limit
+ "languageCode": language,
+ },
+ "features": feature_map,
+ "encodingType": "UTF8",
+ }
+
+ try:
+ resp = requests.post(
+ f"{NLP_ENDPOINT}?key={key}",
+ json=body,
+ timeout=30,
+ )
+
+ if resp.status_code == 403:
+ result["error"] = (
+ "Cloud Natural Language API access denied. Enable it in "
+ "GCP Console: APIs & Services > Library > Cloud Natural Language API. "
+ "Billing must be enabled on the project."
+ )
+ return result
+
+ if resp.status_code == 429:
+ result["error"] = "NLP API quota exceeded. Free tier: 5,000 units/month."
+ return result
+
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"NLP API request failed: {e}"
+ return result
+
+ # Entities
+ for entity in data.get("entities", []):
+ mentions = entity.get("mentions", [])
+ result["entities"].append({
+ "name": entity.get("name", ""),
+ "type": entity.get("type", "UNKNOWN"),
+ "salience": round(entity.get("salience", 0), 4),
+ "sentiment_score": entity.get("sentiment", {}).get("score"),
+ "sentiment_magnitude": entity.get("sentiment", {}).get("magnitude"),
+ "mention_count": len(mentions),
+ "metadata": entity.get("metadata", {}),
+ })
+
+ # Sort by salience (most important first)
+ result["entities"].sort(key=lambda e: e["salience"], reverse=True)
+
+ # Document sentiment
+ doc_sentiment = data.get("documentSentiment", {})
+ if doc_sentiment:
+ score = doc_sentiment.get("score", 0)
+ magnitude = doc_sentiment.get("magnitude", 0)
+ if score > 0.25:
+ tone = "positive"
+ elif score < -0.25:
+ tone = "negative"
+ else:
+ tone = "neutral"
+
+ result["sentiment"] = {
+ "score": round(score, 3),
+ "magnitude": round(magnitude, 3),
+ "tone": tone,
+ "interpretation": (
+ f"{'Positive' if score > 0 else 'Negative' if score < 0 else 'Neutral'} "
+ f"(score: {score:.2f}) with "
+ f"{'high' if magnitude > 2 else 'moderate' if magnitude > 0.5 else 'low'} "
+ f"emotional content (magnitude: {magnitude:.2f})"
+ ),
+ }
+
+ # Sentence-level sentiment
+ sentences = data.get("sentences", [])
+ if sentences:
+ result["sentiment"]["sentence_count"] = len(sentences)
+ sent_scores = [s.get("sentiment", {}).get("score", 0) for s in sentences]
+ result["sentiment"]["most_positive"] = max(sent_scores) if sent_scores else 0
+ result["sentiment"]["most_negative"] = min(sent_scores) if sent_scores else 0
+
+ # Categories (content classification)
+ for cat in data.get("categories", []):
+ result["categories"].append({
+ "name": cat.get("name", ""),
+ "confidence": round(cat.get("confidence", 0), 4),
+ })
+
+ # Moderation categories
+ for mod in data.get("moderationCategories", []):
+ if mod.get("confidence", 0) > 0.5:
+ result["moderation"].append({
+ "name": mod.get("name", ""),
+ "confidence": round(mod.get("confidence", 0), 4),
+ })
+
+ return result
+
+
+def analyze_url(
+ url: str,
+ features: Optional[list] = None,
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Fetch a URL's text content and analyze it.
+
+ Args:
+ url: URL to fetch and analyze.
+ features: NLP features to extract.
+ api_key: API key override.
+
+ Returns:
+ Dictionary with NLP analysis results.
+ """
+ # Fetch the page text
+ try:
+ resp = requests.get(url, timeout=30, headers={
+ "User-Agent": "Mozilla/5.0 (compatible; ClaudeSEO/1.7 NLP Analyzer)"
+ })
+ resp.raise_for_status()
+ html = resp.text
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Could not fetch URL: {e}"}
+
+ # Extract text from HTML (simple approach)
+ try:
+ from bs4 import BeautifulSoup
+ soup = BeautifulSoup(html, "html.parser")
+ # Remove script and style
+ for tag in soup(["script", "style", "nav", "footer", "header"]):
+ tag.decompose()
+ text = soup.get_text(separator=" ", strip=True)
+ except ImportError:
+ # Fallback: regex-based text extraction
+ import re
+ text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
+ text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
+ text = re.sub(r"<[^>]+>", " ", text)
+ text = re.sub(r"\s+", " ", text).strip()
+
+ if not text or len(text) < 50:
+ return {"error": "Extracted text too short for meaningful NLP analysis."}
+
+ result = analyze_text(text, features=features, api_key=api_key)
+ result["source_url"] = url
+ result["extracted_text_length"] = len(text)
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Cloud Natural Language API - Entity/sentiment/classification for SEO"
+ )
+ parser.add_argument("--text", "-t", help="Text to analyze")
+ parser.add_argument("--url", "-u", help="URL to fetch and analyze")
+ parser.add_argument(
+ "--features", "-f",
+ default="entities,sentiment,classify",
+ help="Comma-separated features: entities, sentiment, classify, moderate (default: entities,sentiment,classify)",
+ )
+ parser.add_argument("--api-key", help="API key override")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if not args.text and not args.url:
+ print("Error: Provide --text or --url to analyze.", file=sys.stderr)
+ sys.exit(1)
+
+ features = [f.strip() for f in args.features.split(",")]
+
+ if args.url:
+ result = analyze_url(args.url, features=features, api_key=args.api_key)
+ else:
+ result = analyze_text(args.text, features=features, api_key=args.api_key)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if result.get("source_url"):
+ print(f"=== NLP Analysis: {result['source_url']} ===")
+ print(f"Text extracted: {result.get('extracted_text_length', 0):,} chars")
+ else:
+ print(f"=== NLP Analysis ({result.get('text_length', 0):,} chars) ===")
+
+ sent = result.get("sentiment")
+ if sent:
+ print(f"\nSentiment: {sent['tone'].upper()} (score: {sent['score']}, magnitude: {sent['magnitude']})")
+ print(f" {sent['interpretation']}")
+
+ entities = result.get("entities", [])
+ if entities:
+ print(f"\nTop Entities ({len(entities)} total):")
+ for e in entities[:15]:
+ print(f" [{e['type']:12s}] {e['name']} (salience: {e['salience']:.3f})")
+
+ categories = result.get("categories", [])
+ if categories:
+ print(f"\nContent Categories:")
+ for c in categories:
+ print(f" {c['name']} ({c['confidence']:.1%})")
+
+ moderation = result.get("moderation", [])
+ if moderation:
+ print(f"\nModeration Flags:")
+ for m in moderation:
+ print(f" {m['name']} ({m['confidence']:.1%})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/pagespeed_check.py b/skills/blog-google/scripts/pagespeed_check.py
new file mode 100644
index 0000000..bf1a43c
--- /dev/null
+++ b/skills/blog-google/scripts/pagespeed_check.py
@@ -0,0 +1,641 @@
+#!/usr/bin/env python3
+"""
+PageSpeed Insights v5 + CrUX API combined checker.
+
+Runs Lighthouse lab analysis via PSI and fetches real Chrome UX field data
+via the CrUX API. Merges both perspectives into a single report.
+
+Usage:
+ python pagespeed_check.py https://example.com
+ python pagespeed_check.py https://example.com --strategy mobile
+ python pagespeed_check.py https://example.com --crux-only
+ python pagespeed_check.py https://example.com --psi-only --json
+"""
+
+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)
+
+# Import credential helper (same directory)
+try:
+ from google_auth import get_api_key, load_config
+except ImportError:
+ # Fallback: try relative import from scripts/
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key, load_config
+
+PSI_ENDPOINT = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
+CRUX_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryRecord"
+
+# Core Web Vitals thresholds (March 2026)
+CWV_THRESHOLDS = {
+ "largest_contentful_paint": {"good": 2500, "poor": 4000, "unit": "ms", "label": "LCP"},
+ "interaction_to_next_paint": {"good": 200, "poor": 500, "unit": "ms", "label": "INP"},
+ "cumulative_layout_shift": {"good": 0.1, "poor": 0.25, "unit": "", "label": "CLS"},
+ "first_contentful_paint": {"good": 1800, "poor": 3000, "unit": "ms", "label": "FCP"},
+ "experimental_time_to_first_byte": {"good": 800, "poor": 1800, "unit": "ms", "label": "TTFB"},
+}
+
+PSI_METRIC_MAP = {
+ "LARGEST_CONTENTFUL_PAINT_MS": "largest_contentful_paint",
+ "INTERACTION_TO_NEXT_PAINT": "interaction_to_next_paint",
+ "CUMULATIVE_LAYOUT_SHIFT_SCORE": "cumulative_layout_shift",
+ "FIRST_CONTENTFUL_PAINT_MS": "first_contentful_paint",
+ "EXPERIMENTAL_TIME_TO_FIRST_BYTE": "experimental_time_to_first_byte",
+}
+
+
+def rate_metric(metric_name: str, value: float) -> str:
+ """Rate a CWV metric as good/needs-improvement/poor."""
+ thresholds = CWV_THRESHOLDS.get(metric_name)
+ if not thresholds:
+ return "unknown"
+ if value <= thresholds["good"]:
+ return "good"
+ elif value <= thresholds["poor"]:
+ return "needs-improvement"
+ else:
+ return "poor"
+
+
+def run_pagespeed(
+ url: str,
+ strategy: str = "mobile",
+ api_key: Optional[str] = None,
+ categories: Optional[list] = None,
+) -> dict:
+ """
+ Run PageSpeed Insights v5 analysis.
+
+ Args:
+ url: URL to analyze.
+ strategy: 'mobile' or 'desktop'.
+ api_key: Google API key (optional but recommended for quota).
+ categories: List of categories: PERFORMANCE, ACCESSIBILITY, BEST_PRACTICES, SEO.
+
+ Returns:
+ Dictionary with lighthouse scores, lab metrics, field data (if available),
+ and opportunities. Error in 'error' field on failure.
+ """
+ result = {
+ "url": url,
+ "strategy": strategy,
+ "lighthouse_scores": {},
+ "lab_metrics": {},
+ "field_metrics": {},
+ "opportunities": [],
+ "diagnostics": [],
+ "failed_audits": [],
+ "passed_audits_count": 0,
+ "seo_audits": [],
+ "accessibility_audits": [],
+ "analysis_timestamp": None,
+ "error": None,
+ }
+
+ if categories is None:
+ categories = ["PERFORMANCE", "ACCESSIBILITY", "BEST_PRACTICES", "SEO"]
+
+ params = {
+ "url": url,
+ "strategy": strategy.upper(),
+ }
+ for cat in categories:
+ params.setdefault("category", [])
+ if isinstance(params["category"], list):
+ params["category"].append(cat)
+
+ if api_key:
+ params["key"] = api_key
+
+ try:
+ resp = requests.get(PSI_ENDPOINT, params=params, timeout=120)
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.Timeout:
+ result["error"] = "PageSpeed Insights request timed out (120s). The target page may be very slow."
+ return result
+ except requests.exceptions.HTTPError as e:
+ if resp.status_code == 429:
+ result["error"] = "PSI rate limit exceeded (240 QPM / 25,000 QPD). Wait and retry."
+ elif resp.status_code == 400:
+ result["error"] = f"Invalid URL or parameters: {resp.text}"
+ else:
+ result["error"] = f"PSI API error {resp.status_code}: {e}"
+ return result
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"Request failed: {e}"
+ return result
+
+ result["analysis_timestamp"] = data.get("analysisUTCTimestamp")
+
+ # Lighthouse scores
+ lr = data.get("lighthouseResult", {})
+ for cat_key, cat_data in lr.get("categories", {}).items():
+ result["lighthouse_scores"][cat_key] = round(cat_data.get("score", 0) * 100)
+
+ # Lab metrics from Lighthouse audits
+ audits = lr.get("audits", {})
+ lab_audit_ids = [
+ "first-contentful-paint", "largest-contentful-paint",
+ "total-blocking-time", "cumulative-layout-shift",
+ "speed-index", "interactive",
+ ]
+ for audit_id in lab_audit_ids:
+ audit = audits.get(audit_id, {})
+ if audit.get("numericValue") is not None:
+ result["lab_metrics"][audit_id] = {
+ "value": audit["numericValue"],
+ "display": audit.get("displayValue", ""),
+ "score": audit.get("score"),
+ }
+
+ # Field data from PSI (loading experience)
+ for exp_key in ["loadingExperience", "originLoadingExperience"]:
+ exp = data.get(exp_key, {})
+ metrics = exp.get("metrics", {})
+ if metrics:
+ field_source = "url" if exp_key == "loadingExperience" else "origin"
+ for psi_name, crux_name in PSI_METRIC_MAP.items():
+ metric_data = metrics.get(psi_name, {})
+ if metric_data:
+ p75 = metric_data.get("percentile")
+ category = metric_data.get("category", "NONE")
+ if p75 is not None:
+ # CLS from PSI is already numeric
+ if crux_name == "cumulative_layout_shift":
+ p75_val = p75 / 100 if p75 > 1 else p75
+ else:
+ p75_val = p75
+ result["field_metrics"][f"{field_source}_{crux_name}"] = {
+ "p75": p75_val,
+ "rating": category.lower().replace("_", "-"),
+ "source": f"PSI {field_source}-level",
+ }
+
+ # Opportunities
+ for audit_id, audit in audits.items():
+ if audit.get("details", {}).get("type") == "opportunity":
+ savings = audit.get("details", {}).get("overallSavingsMs")
+ if savings and savings > 0:
+ result["opportunities"].append({
+ "id": audit_id,
+ "title": audit.get("title", audit_id),
+ "savings_ms": savings,
+ "description": audit.get("description", ""),
+ })
+
+ result["opportunities"].sort(key=lambda x: x["savings_ms"], reverse=True)
+
+ # Diagnostics (performance bottlenecks)
+ diagnostic_ids = [
+ "dom-size", "render-blocking-resources", "uses-long-cache-ttl",
+ "total-byte-weight", "mainthread-work-breakdown", "bootup-time",
+ "font-display", "third-party-summary", "largest-contentful-paint-element",
+ "layout-shifts", "long-tasks", "duplicated-javascript",
+ "legacy-javascript", "unused-javascript", "unused-css-rules",
+ ]
+ for diag_id in diagnostic_ids:
+ audit = audits.get(diag_id, {})
+ if audit:
+ score = audit.get("score")
+ result["diagnostics"].append({
+ "id": diag_id,
+ "title": audit.get("title", diag_id),
+ "display": audit.get("displayValue", ""),
+ "score": score,
+ "description": audit.get("description", ""),
+ })
+
+ # Failed and warning audits (score < 0.9, excluding opportunities already captured)
+ opportunity_ids = {o["id"] for o in result["opportunities"]}
+ passed_count = 0
+ for audit_id, audit in audits.items():
+ score = audit.get("score")
+ if score is None:
+ continue
+ if score >= 0.9:
+ passed_count += 1
+ continue
+ if audit_id in opportunity_ids:
+ continue
+ result["failed_audits"].append({
+ "id": audit_id,
+ "title": audit.get("title", audit_id),
+ "score": score,
+ "display": audit.get("displayValue", ""),
+ "description": audit.get("description", ""),
+ })
+ result["passed_audits_count"] = passed_count
+ result["failed_audits"].sort(key=lambda x: x.get("score", 1))
+
+ # SEO audits from the SEO category
+ seo_cat = lr.get("categories", {}).get("seo", {})
+ for ref in seo_cat.get("auditRefs", []):
+ audit = audits.get(ref.get("id"), {})
+ if audit and audit.get("score") is not None:
+ result["seo_audits"].append({
+ "id": ref["id"],
+ "title": audit.get("title", ref["id"]),
+ "score": audit["score"],
+ "pass": audit["score"] >= 0.9,
+ })
+
+ # Accessibility audits from the accessibility category
+ a11y_cat = lr.get("categories", {}).get("accessibility", {})
+ for ref in a11y_cat.get("auditRefs", []):
+ audit = audits.get(ref.get("id"), {})
+ if audit and audit.get("score") is not None and audit["score"] < 0.9:
+ result["accessibility_audits"].append({
+ "id": ref["id"],
+ "title": audit.get("title", ref["id"]),
+ "score": audit["score"],
+ "display": audit.get("displayValue", ""),
+ })
+
+ # Audit details: extract top items from audits with details.items[]
+ # This captures WHICH specific resources are problems (e.g., "hero.jpg is 2MB")
+ for audit_id, audit in audits.items():
+ details = audit.get("details", {})
+ items = details.get("items", [])
+ headings = details.get("headings", [])
+ if items and headings:
+ heading_keys = [h.get("key", "") for h in headings if h.get("key")]
+ extracted_items = []
+ for item in items[:5]:
+ row = {}
+ for key in heading_keys:
+ val = item.get(key)
+ if isinstance(val, dict):
+ row[key] = val.get("url") or val.get("text") or str(val)[:200]
+ elif val is not None:
+ row[key] = val
+ if row:
+ extracted_items.append(row)
+ if extracted_items:
+ result["audit_details"][audit_id] = {
+ "title": audit.get("title", audit_id),
+ "headings": heading_keys,
+ "items": extracted_items,
+ "total_items": len(items),
+ }
+
+ return result
+
+
+def query_crux(
+ url_or_origin: str,
+ api_key: str,
+ form_factor: Optional[str] = None,
+) -> dict:
+ """
+ Query the CrUX API for field data (28-day rolling average).
+
+ Args:
+ url_or_origin: Full URL or origin (e.g., https://example.com).
+ api_key: Google API key.
+ form_factor: DESKTOP, PHONE, or TABLET. None for all form factors.
+
+ Returns:
+ Dictionary with p75 metrics, distributions, collection period, and rating.
+ Error in 'error' field on failure.
+ """
+ result = {
+ "target": url_or_origin,
+ "metrics": {},
+ "collection_period": None,
+ "form_factor": form_factor or "ALL",
+ "error": None,
+ }
+
+ parsed = urlparse(url_or_origin)
+ # Determine if this is a URL or an 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(
+ f"{CRUX_ENDPOINT}?key={api_key}",
+ json=body,
+ timeout=30,
+ )
+
+ if resp.status_code == 404:
+ target_type = "origin" if is_origin else "URL"
+ result["error"] = (
+ f"No CrUX data for this {target_type}. "
+ "The site likely has insufficient Chrome traffic volume for eligibility."
+ )
+ return result
+
+ if resp.status_code == 429:
+ result["error"] = "CrUX API rate limit exceeded (150 QPM shared with History API). Wait and retry."
+ return result
+
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"CrUX API request failed: {e}"
+ return result
+
+ record = data.get("record", {})
+
+ # Collection period
+ cp = record.get("collectionPeriod", {})
+ if cp:
+ first = cp.get("firstDate", {})
+ last = cp.get("lastDate", {})
+ result["collection_period"] = {
+ "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
+ for metric_name, metric_data in record.get("metrics", {}).items():
+ p75s = metric_data.get("percentiles", {})
+ p75 = p75s.get("p75")
+ if p75 is None:
+ continue
+
+ # CLS is string-encoded in CrUX -- parse carefully
+ if metric_name == "cumulative_layout_shift":
+ try:
+ p75_val = float(str(p75))
+ except (ValueError, TypeError):
+ p75_val = 0.0
+ else:
+ try:
+ p75_val = int(p75)
+ except (ValueError, TypeError):
+ try:
+ p75_val = float(p75)
+ except (ValueError, TypeError):
+ continue
+
+ rating = rate_metric(metric_name, p75_val)
+ thresholds = CWV_THRESHOLDS.get(metric_name, {})
+
+ result["metrics"][metric_name] = {
+ "p75": p75_val,
+ "rating": rating,
+ "label": thresholds.get("label", metric_name),
+ "unit": thresholds.get("unit", ""),
+ "good_threshold": thresholds.get("good"),
+ "poor_threshold": thresholds.get("poor"),
+ }
+
+ # Distributions
+ histogram = metric_data.get("histogram", [])
+ if histogram:
+ densities = [bin_data.get("density", 0) for bin_data in histogram]
+ if len(densities) >= 3:
+ result["metrics"][metric_name]["distribution"] = {
+ "good": round(densities[0] * 100, 1),
+ "needs_improvement": round(densities[1] * 100, 1),
+ "poor": round(densities[2] * 100, 1),
+ }
+
+ return result
+
+
+def combined_check(
+ url: str,
+ api_key: Optional[str] = None,
+ strategy: str = "both",
+) -> dict:
+ """
+ Run combined PSI + CrUX check.
+
+ Args:
+ url: URL to analyze.
+ api_key: Google API key.
+ strategy: 'mobile', 'desktop', or 'both'.
+
+ Returns:
+ Dictionary with PSI results (per strategy) and CrUX field data.
+ """
+ result = {
+ "url": url,
+ "psi": {},
+ "crux": None,
+ "error": None,
+ }
+
+ strategies = ["mobile", "desktop"] if strategy == "both" else [strategy]
+
+ for strat in strategies:
+ psi_result = run_pagespeed(url, strategy=strat, api_key=api_key)
+ result["psi"][strat] = psi_result
+ if psi_result.get("error"):
+ result["error"] = psi_result["error"]
+
+ # CrUX (separate call for accurate field data)
+ if api_key:
+ crux_result = query_crux(url, api_key)
+ result["crux"] = crux_result
+ # Also try origin-level if URL-level has no data
+ if crux_result.get("error") and "insufficient" in crux_result.get("error", ""):
+ parsed = urlparse(url)
+ origin = f"{parsed.scheme}://{parsed.netloc}"
+ origin_result = query_crux(origin, api_key)
+ if not origin_result.get("error"):
+ result["crux"] = origin_result
+ result["crux"]["note"] = "URL-level data unavailable; showing origin-level data"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="PageSpeed Insights v5 + CrUX API combined checker"
+ )
+ parser.add_argument("url", help="URL to analyze")
+ parser.add_argument(
+ "--strategy", "-s",
+ choices=["mobile", "desktop", "both"],
+ default="both",
+ help="Analysis strategy (default: both)",
+ )
+ parser.add_argument(
+ "--api-key",
+ help="Google API key (overrides config/env)",
+ )
+ parser.add_argument(
+ "--crux-only",
+ action="store_true",
+ help="Only fetch CrUX field data (skip PSI Lighthouse)",
+ )
+ parser.add_argument(
+ "--psi-only",
+ action="store_true",
+ help="Only run PSI Lighthouse (skip CrUX API)",
+ )
+ parser.add_argument(
+ "--form-factor",
+ choices=["PHONE", "DESKTOP", "TABLET"],
+ help="CrUX form factor filter",
+ )
+ 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 args.crux_only:
+ if not api_key:
+ print("Error: CrUX API requires an API key. Use --api-key or configure GOOGLE_API_KEY.", file=sys.stderr)
+ sys.exit(1)
+ result = query_crux(args.url, api_key, form_factor=args.form_factor)
+ elif args.psi_only:
+ strategies = ["mobile", "desktop"] if args.strategy == "both" else [args.strategy]
+ result = {"psi": {}}
+ for strat in strategies:
+ result["psi"][strat] = run_pagespeed(args.url, strategy=strat, api_key=api_key)
+ else:
+ result = combined_check(args.url, api_key=api_key, strategy=args.strategy)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ # Pretty print summary
+ if args.crux_only:
+ _print_crux_summary(result)
+ elif args.psi_only:
+ for strat, psi in result.get("psi", {}).items():
+ _print_psi_summary(psi)
+ else:
+ for strat, psi in result.get("psi", {}).items():
+ _print_psi_summary(psi)
+ if result.get("crux"):
+ print()
+ _print_crux_summary(result["crux"])
+
+ # Exit with error code if any errors occurred
+ if isinstance(result, dict) and result.get("error"):
+ sys.exit(1)
+
+
+def _print_psi_summary(psi: dict):
+ """Print PSI results in human-readable format."""
+ if psi.get("error"):
+ print(f"PSI Error ({psi.get('strategy', '?')}): {psi['error']}")
+ return
+
+ print(f"\n=== PageSpeed Insights ({psi.get('strategy', 'unknown')}) ===")
+ print(f"URL: {psi.get('url')}")
+ print(f"Timestamp: {psi.get('analysis_timestamp', 'N/A')}")
+
+ scores = psi.get("lighthouse_scores", {})
+ if scores:
+ print("\nLighthouse Scores:")
+ for cat, score in scores.items():
+ print(f" {cat}: {score}/100")
+
+ lab = psi.get("lab_metrics", {})
+ if lab:
+ print("\nLab Metrics:")
+ for metric_id, data in lab.items():
+ print(f" {metric_id}: {data.get('display', data.get('value'))}")
+
+ opps = psi.get("opportunities", [])
+ if opps:
+ print("\nTop Opportunities:")
+ for opp in opps[:5]:
+ print(f" - {opp['title']} (save ~{opp['savings_ms']}ms)")
+
+ failed = psi.get("failed_audits", [])
+ if failed:
+ print(f"\nFailed/Warning Audits ({len(failed)}):")
+ for a in failed[:10]:
+ score_pct = f"{a['score']:.0%}" if a['score'] is not None else "?"
+ print(f" [{score_pct}] {a['title']} {a.get('display', '')}")
+
+ diags = psi.get("diagnostics", [])
+ notable_diags = [d for d in diags if d.get("score") is not None and d["score"] < 0.9]
+ if notable_diags:
+ print(f"\nDiagnostics (needs attention):")
+ for d in notable_diags[:5]:
+ score_pct = f"{d['score']:.0%}" if d['score'] is not None else "info"
+ print(f" [{score_pct}] {d['title']}: {d.get('display', '')}")
+
+ seo = psi.get("seo_audits", [])
+ seo_failed = [a for a in seo if not a.get("pass")]
+ if seo_failed:
+ print(f"\nSEO Issues ({len(seo_failed)}):")
+ for a in seo_failed:
+ print(f" [FAIL] {a['title']}")
+ elif seo:
+ print(f"\nSEO: All {len(seo)} checks passed")
+
+ a11y = psi.get("accessibility_audits", [])
+ if a11y:
+ print(f"\nAccessibility Issues ({len(a11y)}):")
+ for a in a11y[:5]:
+ print(f" [{a['score']:.0%}] {a['title']}")
+
+ passed = psi.get("passed_audits_count", 0)
+ if passed:
+ print(f"\nPassed: {passed} audits")
+
+
+def _print_crux_summary(crux: dict):
+ """Print CrUX results in human-readable format."""
+ if crux.get("error"):
+ print(f"CrUX Error: {crux['error']}")
+ return
+
+ print(f"=== CrUX Field Data ({crux.get('form_factor', 'ALL')}) ===")
+ print(f"Target: {crux.get('target')}")
+
+ if crux.get("note"):
+ print(f"Note: {crux['note']}")
+
+ cp = crux.get("collection_period", {})
+ if cp:
+ print(f"Period: {cp.get('first')} to {cp.get('last')}")
+
+ metrics = crux.get("metrics", {})
+ if metrics:
+ print("\nCore Web Vitals (p75):")
+ for name, data in metrics.items():
+ label = data.get("label", name)
+ p75 = data.get("p75")
+ unit = data.get("unit", "")
+ rating = data.get("rating", "?")
+ good = data.get("good_threshold")
+
+ rating_icon = {"good": "GOOD", "needs-improvement": "NEEDS IMPROVEMENT", "poor": "POOR"}.get(rating, "?")
+
+ if name == "cumulative_layout_shift":
+ print(f" {label}: {p75:.3f} [{rating_icon}] (threshold: <={good})")
+ else:
+ print(f" {label}: {p75}{unit} [{rating_icon}] (threshold: <={good}{unit})")
+
+ dist = data.get("distribution")
+ if dist:
+ print(f" Good: {dist['good']}% | NI: {dist['needs_improvement']}% | Poor: {dist['poor']}%")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/requirements.txt b/skills/blog-google/scripts/requirements.txt
new file mode 100644
index 0000000..4f33555
--- /dev/null
+++ b/skills/blog-google/scripts/requirements.txt
@@ -0,0 +1,18 @@
+# Blog Google Skill Dependencies
+# Installed in the skill's local .venv via run.py
+
+# Core Google API client
+google-api-python-client>=2.100.0,<3.0.0
+google-auth>=2.20.0,<3.0.0
+google-auth-oauthlib>=1.0.0,<2.0.0
+google-auth-httplib2>=0.2.0,<1.0.0
+
+# GA4 Data API
+google-analytics-data>=0.18.0,<1.0.0
+
+# HTTP requests (PSI, CrUX, NLP)
+requests>=2.32.4,<3.0.0
+
+# Report generation (optional - graceful fallback if unavailable)
+matplotlib>=3.8.0,<4.0.0
+weasyprint>=61.0,<70.0
diff --git a/skills/blog-google/scripts/run.py b/skills/blog-google/scripts/run.py
new file mode 100644
index 0000000..0bf961b
--- /dev/null
+++ b/skills/blog-google/scripts/run.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""
+Universal runner for Blog Google skill scripts
+Ensures all scripts run with the correct virtual environment
+"""
+
+import os
+import sys
+import subprocess
+from pathlib import Path
+
+
+def get_venv_python():
+ """Get the virtual environment Python executable"""
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+
+ if os.name == 'nt': # Windows
+ venv_python = venv_dir / "Scripts" / "python.exe"
+ else: # Unix/Linux/Mac
+ venv_python = venv_dir / "bin" / "python"
+
+ return venv_python
+
+
+def ensure_venv():
+ """Ensure virtual environment exists"""
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+ setup_script = skill_dir / "scripts" / "setup_environment.py"
+
+ # Check if venv exists
+ if not venv_dir.exists():
+ print("First-time setup: Creating virtual environment...")
+ print(" This may take a minute...")
+
+ # Run setup with system Python
+ result = subprocess.run([sys.executable, str(setup_script)])
+ if result.returncode != 0:
+ print("Failed to set up environment")
+ sys.exit(1)
+
+ print("Environment ready!")
+
+ return get_venv_python()
+
+
+def main():
+ """Main runner"""
+ if len(sys.argv) < 2:
+ print("Usage: python run.py <script_name> [args...]")
+ print("\nAvailable scripts:")
+ print(" google_auth.py - Credential management and auth setup")
+ print(" pagespeed_check.py - PageSpeed Insights + CrUX field data")
+ print(" crux_history.py - 25-week CWV trend history")
+ print(" youtube_search.py - YouTube video search and details")
+ print(" nlp_analyze.py - NLP entity extraction and sentiment")
+ print(" gsc_query.py - Search Console performance data")
+ print(" gsc_inspect.py - URL Inspection API")
+ print(" indexing_notify.py - Indexing API notifications")
+ print(" ga4_report.py - GA4 organic traffic reports")
+ print(" keyword_planner.py - Google Ads Keyword Planner")
+ print(" google_report.py - PDF/HTML performance reports")
+ sys.exit(1)
+
+ script_name = sys.argv[1]
+ script_args = sys.argv[2:]
+
+ # Handle both "scripts/script.py" and "script.py" formats
+ if script_name.startswith('scripts/'):
+ script_name = script_name[8:] # len('scripts/') = 8
+
+ # Ensure .py extension
+ if not script_name.endswith('.py'):
+ script_name += '.py'
+
+ # Get script path
+ skill_dir = Path(__file__).parent.parent
+ script_path = skill_dir / "scripts" / script_name
+
+ if not script_path.exists():
+ print(f"Script not found: {script_name}")
+ print(f" Skill directory: {skill_dir}")
+ print(f" Looked for: {script_path}")
+ sys.exit(1)
+
+ # Ensure venv exists and get Python executable
+ venv_python = ensure_venv()
+
+ # Build command
+ cmd = [str(venv_python), str(script_path)] + script_args
+
+ # Run the script
+ try:
+ result = subprocess.run(cmd)
+ sys.exit(result.returncode)
+ except KeyboardInterrupt:
+ print("\nInterrupted by user")
+ sys.exit(130)
+ except Exception as e:
+ print(f"Error: {e}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-google/scripts/setup_environment.py b/skills/blog-google/scripts/setup_environment.py
new file mode 100644
index 0000000..9ea5597
--- /dev/null
+++ b/skills/blog-google/scripts/setup_environment.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""
+Environment Setup for Blog Google Skill
+Manages virtual environment and dependencies automatically
+"""
+
+import os
+import sys
+import subprocess
+import venv
+from pathlib import Path
+
+
+class SkillEnvironment:
+ """Manages skill-specific virtual environment"""
+
+ def __init__(self):
+ self.skill_dir = Path(__file__).parent.parent
+ self.venv_dir = self.skill_dir / ".venv"
+ self.requirements_file = self.skill_dir / "scripts" / "requirements.txt"
+
+ if os.name == 'nt':
+ self.venv_python = self.venv_dir / "Scripts" / "python.exe"
+ self.venv_pip = self.venv_dir / "Scripts" / "pip.exe"
+ else:
+ self.venv_python = self.venv_dir / "bin" / "python"
+ self.venv_pip = self.venv_dir / "bin" / "pip"
+
+ def ensure_venv(self) -> bool:
+ """Ensure virtual environment exists and is set up"""
+ if self.is_in_skill_venv():
+ return True
+
+ if not self.venv_dir.exists():
+ print(f"Creating virtual environment in {self.venv_dir.name}/")
+ try:
+ venv.create(self.venv_dir, with_pip=True)
+ except Exception as e:
+ print(f"Failed to create venv: {e}")
+ return False
+
+ if self.requirements_file.exists():
+ print("Installing dependencies...")
+ try:
+ subprocess.run(
+ [str(self.venv_pip), "install", "--upgrade", "pip"],
+ check=True, capture_output=True, text=True,
+ )
+ subprocess.run(
+ [str(self.venv_pip), "install", "-r", str(self.requirements_file)],
+ check=True, capture_output=True, text=True,
+ )
+ print("Dependencies installed")
+ return True
+ except subprocess.CalledProcessError as e:
+ print(f"Failed to install dependencies: {e}")
+ return False
+ else:
+ print("No requirements.txt found, skipping dependency installation")
+ return True
+
+ def is_in_skill_venv(self) -> bool:
+ """Check if running in the skill's venv"""
+ if hasattr(sys, 'real_prefix') or (
+ hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
+ ):
+ return Path(sys.prefix) == self.venv_dir
+ return False
+
+ def get_python_executable(self) -> str:
+ """Get the correct Python executable"""
+ if self.venv_python.exists():
+ return str(self.venv_python)
+ return sys.executable
+
+
+def main():
+ """Main entry point for environment setup"""
+ import argparse
+
+ parser = argparse.ArgumentParser(description='Setup Blog Google skill environment')
+ parser.add_argument('--check', action='store_true', help='Check if environment is set up')
+ args = parser.parse_args()
+
+ env = SkillEnvironment()
+
+ if args.check:
+ if env.venv_dir.exists():
+ print(f"Virtual environment exists: {env.venv_dir}")
+ print(f" Python: {env.get_python_executable()}")
+ else:
+ print("No virtual environment found")
+ return
+
+ if env.ensure_venv():
+ print(f"\nEnvironment ready!")
+ print(f" Virtual env: {env.venv_dir}")
+ print(f" Python: {env.get_python_executable()}")
+ else:
+ print("\nEnvironment setup failed")
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main() or 0)
diff --git a/skills/blog-google/scripts/youtube_search.py b/skills/blog-google/scripts/youtube_search.py
new file mode 100644
index 0000000..11b8815
--- /dev/null
+++ b/skills/blog-google/scripts/youtube_search.py
@@ -0,0 +1,355 @@
+#!/usr/bin/env python3
+"""
+YouTube Data API v3 - Search, video details, and channel data for SEO.
+
+YouTube mentions have the strongest AI visibility correlation (0.737).
+This script provides authoritative YouTube data directly from Google.
+
+Usage:
+ python youtube_search.py search "claude code seo"
+ python youtube_search.py video dQw4w9WgXcQ --json
+ python youtube_search.py channel UCxxxxxx --json
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_api_key
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key
+
+# YouTube Data API v3 quota costs:
+# search.list = 100 units, videos.list = 1 unit, channels.list = 1 unit
+# Default quota: 10,000 units/day = ~100 searches or ~10,000 video lookups
+YOUTUBE_API_SERVICE = "youtube"
+YOUTUBE_API_VERSION = "v3"
+
+
+def _build_youtube_service(api_key: Optional[str] = None):
+ """Build the YouTube Data API v3 service."""
+ key = api_key or get_api_key()
+ if not key:
+ return None
+ try:
+ return build(YOUTUBE_API_SERVICE, YOUTUBE_API_VERSION, developerKey=key)
+ except Exception as e:
+ print(f"Error building YouTube service: {e}", file=sys.stderr)
+ return None
+
+
+def search_videos(
+ query: str,
+ max_results: int = 10,
+ order: str = "relevance",
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Search YouTube for videos matching a query.
+
+ Args:
+ query: Search query string.
+ max_results: Max results (1-50, default 10).
+ order: Sort order: relevance, date, rating, viewCount, title.
+ api_key: Optional API key override.
+
+ Returns:
+ Dictionary with videos list and metadata.
+ """
+ result = {"query": query, "videos": [], "total_results": 0, "error": None}
+
+ service = _build_youtube_service(api_key)
+ if not service:
+ result["error"] = "No API key. Set GOOGLE_API_KEY or add 'api_key' to config."
+ return result
+
+ try:
+ response = service.search().list(
+ q=query,
+ part="snippet",
+ type="video",
+ maxResults=min(max_results, 50),
+ order=order,
+ ).execute()
+
+ result["total_results"] = response.get("pageInfo", {}).get("totalResults", 0)
+
+ # Get video IDs for statistics
+ video_ids = []
+ snippets = {}
+ for item in response.get("items", []):
+ vid = item["id"].get("videoId")
+ if vid:
+ video_ids.append(vid)
+ snippets[vid] = item.get("snippet", {})
+
+ # Fetch statistics for all videos in one call (1 unit)
+ if video_ids:
+ stats_response = service.videos().list(
+ id=",".join(video_ids),
+ part="statistics,contentDetails",
+ ).execute()
+
+ stats_map = {}
+ for item in stats_response.get("items", []):
+ stats_map[item["id"]] = {
+ "views": int(item.get("statistics", {}).get("viewCount", 0)),
+ "likes": int(item.get("statistics", {}).get("likeCount", 0)),
+ "comments": int(item.get("statistics", {}).get("commentCount", 0)),
+ "duration": item.get("contentDetails", {}).get("duration", ""),
+ }
+
+ for vid in video_ids:
+ snip = snippets.get(vid, {})
+ stats = stats_map.get(vid, {})
+ result["videos"].append({
+ "video_id": vid,
+ "title": snip.get("title", ""),
+ "channel": snip.get("channelTitle", ""),
+ "channel_id": snip.get("channelId", ""),
+ "published": snip.get("publishedAt", ""),
+ "description": snip.get("description", "")[:300],
+ "thumbnail": snip.get("thumbnails", {}).get("high", {}).get("url", ""),
+ "views": stats.get("views", 0),
+ "likes": stats.get("likes", 0),
+ "comments": stats.get("comments", 0),
+ "duration": stats.get("duration", ""),
+ "url": f"https://www.youtube.com/watch?v={vid}",
+ })
+
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ "YouTube Data API access denied. Ensure the API is enabled "
+ "in your GCP project (APIs & Services > Library > YouTube Data API v3)."
+ )
+ elif "429" in error_str:
+ result["error"] = "YouTube API quota exceeded (10,000 units/day). Search costs 100 units."
+ else:
+ result["error"] = f"YouTube API error: {e}"
+
+ return result
+
+
+def get_video_details(
+ video_id: str,
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Get detailed information about a specific YouTube video.
+
+ Args:
+ video_id: YouTube video ID.
+ api_key: Optional API key override.
+
+ Returns:
+ Dictionary with video details, statistics, and top comments.
+ """
+ result = {"video_id": video_id, "details": None, "comments": [], "error": None}
+
+ service = _build_youtube_service(api_key)
+ if not service:
+ result["error"] = "No API key configured."
+ return result
+
+ try:
+ # Video details (1 unit)
+ response = service.videos().list(
+ id=video_id,
+ part="snippet,statistics,contentDetails,topicDetails",
+ ).execute()
+
+ items = response.get("items", [])
+ if not items:
+ result["error"] = f"Video not found: {video_id}"
+ return result
+
+ item = items[0]
+ snip = item.get("snippet", {})
+ stats = item.get("statistics", {})
+ content = item.get("contentDetails", {})
+ topics = item.get("topicDetails", {})
+
+ result["details"] = {
+ "title": snip.get("title", ""),
+ "channel": snip.get("channelTitle", ""),
+ "channel_id": snip.get("channelId", ""),
+ "published": snip.get("publishedAt", ""),
+ "description": snip.get("description", ""),
+ "tags": snip.get("tags", []),
+ "category_id": snip.get("categoryId", ""),
+ "duration": content.get("duration", ""),
+ "definition": content.get("definition", ""),
+ "caption": content.get("caption", "false"),
+ "views": int(stats.get("viewCount", 0)),
+ "likes": int(stats.get("likeCount", 0)),
+ "comments_count": int(stats.get("commentCount", 0)),
+ "favorites": int(stats.get("favoriteCount", 0)),
+ "topic_categories": topics.get("topicCategories", []),
+ "url": f"https://www.youtube.com/watch?v={video_id}",
+ }
+
+ # Top comments (1 unit)
+ try:
+ comments_response = service.commentThreads().list(
+ videoId=video_id,
+ part="snippet",
+ maxResults=10,
+ order="relevance",
+ textFormat="plainText",
+ ).execute()
+
+ for thread in comments_response.get("items", []):
+ comment = thread.get("snippet", {}).get("topLevelComment", {}).get("snippet", {})
+ result["comments"].append({
+ "author": comment.get("authorDisplayName", ""),
+ "text": comment.get("textDisplay", "")[:500],
+ "likes": comment.get("likeCount", 0),
+ "published": comment.get("publishedAt", ""),
+ })
+ except Exception:
+ pass # Comments may be disabled
+
+ except Exception as e:
+ result["error"] = f"YouTube API error: {e}"
+
+ return result
+
+
+def get_channel_info(
+ channel_id: str,
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Get channel information.
+
+ Args:
+ channel_id: YouTube channel ID.
+ api_key: Optional API key override.
+
+ Returns:
+ Dictionary with channel details.
+ """
+ result = {"channel_id": channel_id, "channel": None, "error": None}
+
+ service = _build_youtube_service(api_key)
+ if not service:
+ result["error"] = "No API key configured."
+ return result
+
+ try:
+ response = service.channels().list(
+ id=channel_id,
+ part="snippet,statistics,brandingSettings",
+ ).execute()
+
+ items = response.get("items", [])
+ if not items:
+ result["error"] = f"Channel not found: {channel_id}"
+ return result
+
+ item = items[0]
+ snip = item.get("snippet", {})
+ stats = item.get("statistics", {})
+
+ result["channel"] = {
+ "title": snip.get("title", ""),
+ "description": snip.get("description", "")[:500],
+ "custom_url": snip.get("customUrl", ""),
+ "published": snip.get("publishedAt", ""),
+ "country": snip.get("country", ""),
+ "subscribers": int(stats.get("subscriberCount", 0)),
+ "videos": int(stats.get("videoCount", 0)),
+ "views": int(stats.get("viewCount", 0)),
+ "thumbnail": snip.get("thumbnails", {}).get("high", {}).get("url", ""),
+ }
+
+ except Exception as e:
+ result["error"] = f"YouTube API error: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="YouTube Data API v3 - Search and video analysis for SEO"
+ )
+ parser.add_argument(
+ "command",
+ choices=["search", "video", "channel"],
+ help="Command: search, video (details), channel (info)",
+ )
+ parser.add_argument("query", help="Search query, video ID, or channel ID")
+ parser.add_argument("--limit", type=int, default=10, help="Max results for search (default: 10)")
+ parser.add_argument(
+ "--order",
+ choices=["relevance", "date", "rating", "viewCount", "title"],
+ default="relevance",
+ help="Sort order for search (default: relevance)",
+ )
+ parser.add_argument("--api-key", help="API key override")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if args.command == "search":
+ result = search_videos(args.query, max_results=args.limit, order=args.order, api_key=args.api_key)
+ elif args.command == "video":
+ result = get_video_details(args.query, api_key=args.api_key)
+ elif args.command == "channel":
+ result = get_channel_info(args.query, api_key=args.api_key)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if args.command == "search":
+ print(f"=== YouTube Search: {args.query} ===")
+ print(f"Results: {result.get('total_results', 0):,}")
+ for i, v in enumerate(result.get("videos", []), 1):
+ print(f"\n {i}. {v['title']}")
+ print(f" {v['channel']} | {v['views']:,} views | {v['likes']:,} likes | {v['duration']}")
+ print(f" {v['url']}")
+ elif args.command == "video":
+ d = result.get("details", {})
+ if d:
+ print(f"=== {d.get('title')} ===")
+ print(f"Channel: {d.get('channel')}")
+ print(f"Views: {d.get('views', 0):,} | Likes: {d.get('likes', 0):,} | Comments: {d.get('comments_count', 0):,}")
+ print(f"Published: {d.get('published', '')[:10]} | Duration: {d.get('duration')}")
+ tags = d.get("tags", [])
+ if tags:
+ print(f"Tags: {', '.join(tags[:10])}")
+ comments = result.get("comments", [])
+ if comments:
+ print(f"\nTop Comments ({len(comments)}):")
+ for c in comments[:5]:
+ print(f" [{c['likes']} likes] {c['author']}: {c['text'][:100]}")
+ elif args.command == "channel":
+ ch = result.get("channel", {})
+ if ch:
+ print(f"=== {ch.get('title')} ===")
+ print(f"Subscribers: {ch.get('subscribers', 0):,} | Videos: {ch.get('videos', 0):,} | Views: {ch.get('views', 0):,}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-image/SKILL.md b/skills/blog-image/SKILL.md
index 8424f75..066dc94 100644
--- a/skills/blog-image/SKILL.md
+++ b/skills/blog-image/SKILL.md
@@ -14,13 +14,6 @@ description: >
"image generate", "blog cover image", "inline image", "OG image".
user-invokable: true
argument-hint: "[generate|edit|setup] [description-or-path]"
-allowed-tools:
- - Read
- - Write
- - Edit
- - Bash
- - Glob
- - Grep
license: MIT
metadata:
author: AgriciDaniel
diff --git a/skills/blog-notebooklm/SKILL.md b/skills/blog-notebooklm/SKILL.md
index 98e5cf3..fe77cb4 100644
--- a/skills/blog-notebooklm/SKILL.md
+++ b/skills/blog-notebooklm/SKILL.md
@@ -11,11 +11,6 @@ description: >
"document query", "notebook library".
user-invokable: true
argument-hint: "[ask|discover|library|setup|status|cleanup] [question-or-url]"
-allowed-tools:
- - Read
- - Bash
- - Glob
- - Grep
license: MIT
metadata:
author: AgriciDaniel
diff --git a/skills/blog-outline/SKILL.md b/skills/blog-outline/SKILL.md
index daf4122..6558709 100644
--- a/skills/blog-outline/SKILL.md
+++ b/skills/blog-outline/SKILL.md
@@ -8,14 +8,6 @@ description: >
ready for /blog write to consume. Use when user says "outline", "blog outline",
"content outline", "structure blog", "plan sections", "article skeleton",
"heading structure", "SERP analysis", "competitive outline", "plan article".
-allowed-tools:
- - Read
- - Write
- - Bash
- - Grep
- - Glob
- - WebSearch
- - WebFetch
---
# Blog Outline Generator -- SERP-Informed Structure Planning
diff --git a/skills/blog-persona/SKILL.md b/skills/blog-persona/SKILL.md
index 139828e..0f1f8ea 100644
--- a/skills/blog-persona/SKILL.md
+++ b/skills/blog-persona/SKILL.md
@@ -9,12 +9,6 @@ description: >
"writing style", "brand voice", "create persona", "use persona".
user-invokable: true
argument-hint: "[create|list|use|show] [persona-name]"
-allowed-tools:
- - Read
- - Write
- - Glob
- - WebFetch
- - AskUserQuestion
---
# Blog Persona - Writing Voice Management
diff --git a/skills/blog-repurpose/SKILL.md b/skills/blog-repurpose/SKILL.md
index f8ee64e..b679156 100644
--- a/skills/blog-repurpose/SKILL.md
+++ b/skills/blog-repurpose/SKILL.md
@@ -6,11 +6,6 @@ description: >
discussion posts, email newsletter excerpts. Adapts tone for each platform.
Use when user says "repurpose", "blog repurpose", "share blog", "social media",
"twitter thread", "linkedin post", "youtube script", "reddit post".
-allowed-tools:
- - Read
- - Write
- - Grep
- - Glob
---
# Blog Repurpose -- Cross-Platform Content Adaptation
diff --git a/skills/blog-rewrite/SKILL.md b/skills/blog-rewrite/SKILL.md
index eae1c4a..d7cb895 100644
--- a/skills/blog-rewrite/SKILL.md
+++ b/skills/blog-rewrite/SKILL.md
@@ -9,16 +9,6 @@ description: >
and updates freshness signals. Works with any blog format (MDX, markdown, HTML).
Use when user says "rewrite blog", "optimize blog", "update blog",
"improve blog", "fix blog", "refresh blog post", "blog optimization".
-allowed-tools:
- - Read
- - Write
- - Edit
- - Bash
- - Grep
- - Glob
- - WebFetch
- - WebSearch
- - Task
---
# Blog Rewriter -- Optimize Existing Posts
@@ -65,7 +55,11 @@ and AI citation platforms. Preserves the author's voice while applying the
- **AI content percentage estimate** - Based on burstiness, phrase density, and
TTR, estimate what percentage of the content reads as AI-generated (0-100%).
Report as: "AI content estimate: ~X%"
-4. **Cannibalization check**:
+4. **Video embed check**:
+ - Count existing YouTube embeds in the post
+ - If 0 embeds, flag: "No video embeds -- YouTube has strongest AI visibility correlation (0.737)"
+ - If present, check: lazy loading? aria-labels? noscript fallback? VideoObject schema?
+5. **Cannibalization check**:
- Identify the post's primary keyword from title, H1, and first paragraph
- Search the blog directory for other posts targeting the same keyword:
- Grep headings and meta descriptions across all blog posts
@@ -74,11 +68,11 @@ and AI citation platforms. Preserves the author's voice while applying the
- Which posts compete for the same keyword
- Recommend: **merge** (combine into one stronger post) or **differentiate**
(shift one post to a related but distinct keyword)
-5. **Calculate current score** across 5 categories:
+6. **Calculate current score** across 5 categories:
- Score across 5 categories (Content Quality 30, SEO Optimization 25, E-E-A-T Signals 15, Technical Elements 15, AI Citation Readiness 15)
- Total: 0-100
-6. **Present audit summary** with specific findings, AI detection results, cannibalization status, and score
-7. **Enter plan mode** - Present section-by-section optimization plan
+7. **Present audit summary** with specific findings, AI detection results, video status, cannibalization status, and score
+8. **Enter plan mode** - Present section-by-section optimization plan
Wait for user approval before proceeding.
@@ -154,17 +148,24 @@ Every H2 section MUST open with a 40-60 word paragraph containing:
- If nanobanana-mcp configured: generate custom images for sections lacking good stock matches (invoke `blog-image` sub-skill via Task)
- Adapt embed format to detected platform (MDX vs markdown vs HTML)
-#### 4h. Add/Improve FAQ
+#### 4h. Add Video Embeds
+If the post lacks YouTube video embeds:
+- Search 2-3 relevant videos using quality criteria from `references/video-embeds.md`
+- Embed using platform-appropriate format (srcdoc lazy loading)
+- Place: 1 after introduction, 1-2 in mid-article sections
+- Include noscript fallback for AI crawlers
+
+#### 4i. Add/Improve FAQ
- If no FAQ exists, add one (3-5 questions)
- If FAQ exists, ensure answers are 40-60 words with statistics
- Add FAQ schema markup appropriate to platform
-#### 4i. Reduce Self-Promotion
+#### 4j. Reduce Self-Promotion
- Max 1 brand mention (author bio context only)
- Remove "At [Company], we..." patterns
- Convert promotional sections to educational content
-#### 4j. Citation Capsule Injection
+#### 4k. Citation Capsule Injection
For each H2 section, generate (or improve existing) a citation capsule:
- 40-60 word self-contained passage per H2
- Contains: one specific claim + one data point + source attribution
@@ -182,7 +183,7 @@ for AI systems to extract and cite in their responses.
Capsules map to the "AI Citation Readiness" category (15 points) in
`references/quality-scoring.md`.
-#### 4k. Anti-AI-Detection Patterns
+#### 4l. Anti-AI-Detection Patterns
Apply these transformations to reduce AI-detectable writing patterns:
- **Eliminate em dashes** - Replace every em dash (-) with a comma, hyphen (-),
colon, or period. Split sentences if needed. Em dashes are an AI writing tell.
@@ -206,7 +207,7 @@ Apply these transformations to reduce AI-detectable writing patterns:
experience: "in our experience", "we've found that", "from what we've seen",
"this tends to", "it depends on".
-#### 4l. Summary Box (Key Takeaways)
+#### 4m. Summary Box (Key Takeaways)
If the post lacks a summary box, add one immediately after the introduction:
```markdown
> **Key Takeaways**
@@ -223,7 +224,7 @@ If an existing TL;DR box is present, convert it to the bullet-point Key
Takeaways format. Verify it meets the 40-60 word requirement and contains
at least one statistic with source attribution.
-#### 4m. Information Gain Marker Injection
+#### 4n. Information Gain Marker Injection
Review the post for original value and tag it:
- `[ORIGINAL DATA]` - Any proprietary data, survey results, experiments, or
case study metrics the author collected first-hand
@@ -265,6 +266,7 @@ After rewriting, verify all quality gates pass:
16. Rhetorical questions present (1 per 200-300 words)
17. AI content estimate reduced from audit baseline
18. Score improved across all 5 categories vs Phase 1 audit
+19. YouTube video embeds present with lazy loading, aria-labels, and noscript fallback
### Phase 6: Summary
@@ -310,6 +312,7 @@ After rewriting, verify all quality gates pass:
### Visual Elements
- Charts: [count] ([types])
- Images: [count]
+- YouTube videos: [count] ([titles])
### Ready for
- `/blog analyze <file>` to verify final score
diff --git a/skills/blog-schema/SKILL.md b/skills/blog-schema/SKILL.md
index 7013ceb..5d2a4e0 100644
--- a/skills/blog-schema/SKILL.md
+++ b/skills/blog-schema/SKILL.md
@@ -6,11 +6,6 @@ description: >
against Google requirements and warns about deprecated types. Use when user
says "schema", "blog schema", "json-ld", "structured data", "schema markup",
"generate schema".
-allowed-tools:
- - Read
- - Write
- - Grep
- - Glob
---
# Blog Schema -- JSON-LD Structured Data Generation
@@ -176,7 +171,34 @@ because:
- It structures content for future rich result eligibility changes
- It improves content organization signals
-### Step 7: Generate ImageObject
+### Step 7: Generate VideoObject (if videos present)
+
+For each YouTube video embedded in the post, generate a VideoObject schema:
+
+```json
+{
+ "@type": "VideoObject",
+ "@id": "{siteUrl}/blog/{slug}#video-{index}",
+ "name": "Video title",
+ "description": "Video description excerpt (first 200 chars)",
+ "thumbnailUrl": "https://img.youtube.com/vi/{videoId}/hqdefault.jpg",
+ "uploadDate": "{ISO 8601 date}",
+ "contentUrl": "https://www.youtube.com/watch?v={videoId}",
+ "embedUrl": "https://www.youtube.com/embed/{videoId}",
+ "duration": "PT{M}M{S}S",
+ "interactionStatistic": {
+ "@type": "InteractionCounter",
+ "interactionType": { "@type": "WatchAction" },
+ "userInteractionCount": {viewCount}
+ }
+}
+```
+
+Add each VideoObject to the @graph array. Use `#video-1`, `#video-2` etc. for
+the @id fragment. Extract video metadata from the embed's noscript fallback or
+from YouTube Data API if available via `blog-google`.
+
+### Step 7.5: Generate ImageObject
Cover image schema for the post's primary image:
@@ -220,9 +242,9 @@ Check for deprecated schema types and apply validation rules:
8. FAQPage has at least 2 questions
**AI citation optimization note:** Pages using 3 or more schema types have
-approximately 13% higher AI citation likelihood. This skill generates 6 types
-by default (BlogPosting, Person, Organization, BreadcrumbList, FAQPage,
-ImageObject) to maximize both search engine understanding and AI extraction.
+approximately 13% higher AI citation likelihood. This skill generates up to 7
+types (BlogPosting, Person, Organization, BreadcrumbList, FAQPage, ImageObject,
+VideoObject) to maximize both search engine understanding and AI extraction.
### Step 9: Output
@@ -238,6 +260,7 @@ Combine all schemas into a single `<script>` tag using the @graph pattern:
{ "@type": "Organization", ... },
{ "@type": "BreadcrumbList", ... },
{ "@type": "FAQPage", ... },
+ { "@type": "VideoObject", ... },
{ "@type": "ImageObject", ... }
]
}
diff --git a/skills/blog-seo-check/SKILL.md b/skills/blog-seo-check/SKILL.md
index 3fbfb1e..bc47269 100644
--- a/skills/blog-seo-check/SKILL.md
+++ b/skills/blog-seo-check/SKILL.md
@@ -9,11 +9,6 @@ description: >
prioritized fix list with specific recommendations. Use when user says "seo check",
"check seo", "validate seo", "blog seo", "seo validation", "on-page seo",
"title tag check", "meta description check", "heading check", "link audit".
-allowed-tools:
- - Read
- - Grep
- - Glob
- - WebFetch
---
# Blog SEO Check -- Post-Writing Validation
@@ -196,3 +191,15 @@ Status values:
- **FAIL** - Does not meet the criteria, fix provided
- **WARN** - Partially meets criteria or edge case, recommendation provided
- **N/A** - Not applicable (e.g., no Twitter Card tags if site has no X account)
+
+### Optional: Live Performance Check (blog-google)
+
+If the post has a published URL and blog-google credentials are available:
+
+1. Check credentials: `python3 skills/blog-google/scripts/run.py google_auth --check --json`
+2. If Tier 0+, run PageSpeed: `python3 skills/blog-google/scripts/run.py pagespeed_check <url> --json`
+3. Append to report:
+ - Lighthouse Performance, Accessibility, Best Practices, SEO scores
+ - CWV field data (LCP, INP, CLS) with traffic-light ratings
+ - Top 3 opportunities with estimated savings
+4. Falls back silently if credentials unavailable or URL not published.
diff --git a/skills/blog-strategy/SKILL.md b/skills/blog-strategy/SKILL.md
index d2f17fa..243464b 100644
--- a/skills/blog-strategy/SKILL.md
+++ b/skills/blog-strategy/SKILL.md
@@ -9,15 +9,6 @@ description: >
through original research and first-hand experience.
Use when user says "blog strategy", "content strategy", "blog positioning",
"what should I blog about", "blog topics", "content pillars", "blog ideation".
-allowed-tools:
- - Read
- - Write
- - Bash
- - Grep
- - Glob
- - WebFetch
- - WebSearch
- - Task
---
# Blog Strategy -- Positioning & Content Architecture
diff --git a/skills/blog-taxonomy/SKILL.md b/skills/blog-taxonomy/SKILL.md
index 8eb18e1..93e2ca7 100644
--- a/skills/blog-taxonomy/SKILL.md
+++ b/skills/blog-taxonomy/SKILL.md
@@ -10,12 +10,6 @@ description: >
"tag suggestions", "sync tags", "WordPress tags", "Shopify tags".
user-invokable: true
argument-hint: "[suggest|sync|audit] [file-or-cms]"
-allowed-tools:
- - Read
- - Grep
- - Glob
- - WebFetch
- - Bash
---
# Blog Taxonomy
diff --git a/skills/blog-write/SKILL.md b/skills/blog-write/SKILL.md
index 1d40d55..27b2111 100644
--- a/skills/blog-write/SKILL.md
+++ b/skills/blog-write/SKILL.md
@@ -9,16 +9,6 @@ description: >
and HTML output.
Use when user says "write blog", "new blog post", "create article",
"write about", "draft blog", "generate blog post".
-allowed-tools:
- - Read
- - Write
- - Edit
- - Bash
- - Grep
- - Glob
- - WebFetch
- - WebSearch
- - Task
---
# Blog Writer -- New Article Generation
@@ -108,6 +98,10 @@ Spawn a `blog-researcher` agent (or do inline research with WebSearch):
- Query via `blog-notebooklm` for source-grounded data from user-uploaded documents
- Treat NotebookLM responses as Tier 1 sources (user's own primary documents)
- Falls back silently if not configured or not authenticated
+7. **Find relevant YouTube videos** (2-3 per post):
+ - Use `blog-google` youtube command or WebSearch `site:youtube.com [topic] [year]`
+ - Apply quality criteria from `references/video-embeds.md` (min score 50/100)
+ - Select 2-3 best videos. Falls back silently if none found.
### Phase 3: Outline Generation
@@ -177,7 +171,7 @@ adapt this skeleton to match the template's section structure:
Present the outline to the user for approval before writing.
-**Visual element pacing**: Insert `[IMAGE]`, `[CHART]`, or `[CALLOUT]` markers
+**Visual element pacing**: Insert `[IMAGE]`, `[CHART]`, `[VIDEO]`, or `[CALLOUT]` markers
every 300-500 words. Alternate types (no consecutive same-type). See
`references/content-rules.md` Visual Rhythm section and
`references/cta-placement.md` for CTA positioning.
@@ -370,13 +364,17 @@ MDX format:
</figure>
```
-#### 5k. Citation Format
+#### 5k. Video Embedding
+Embed YouTube videos using srcdoc lazy-loading pattern from `references/video-embeds.md`.
+Include aria-label, noscript fallback for AI crawlers. Place after relevant H2, 500+ words apart.
+
+#### 5l. Citation Format
Inline attribution (always):
```markdown
Organic CTR declined 61% with AI Overviews ([Seer Interactive](https://www.seerinteractive.com/), 2025).
```
-#### 5l. FAQ Section
+#### 5m. FAQ Section
Add 3-5 FAQ items with 40-60 word answers. Each answer must contain a statistic.
For MDX with FAQSchema component:
@@ -395,7 +393,7 @@ For standard markdown:
Answer with statistic and source attribution (40-60 words).
```
-#### 5m. Internal Linking
+#### 5n. Internal Linking
- 5-10 internal links per 2,000-word post
- Link to relevant existing content naturally
- Use descriptive anchor text (not "click here")
@@ -433,6 +431,7 @@ Before delivering, verify:
- Full list in `agents/blog-writer.md`
17. **Contractions** - Verify natural use of contractions ("it's", "we've", "don't", "isn't"). Formal AI prose avoids contractions; natural writing uses them.
18. **Rhetorical questions** - Verify at least one rhetorical question every 200-300 words to break up declarative patterns.
+19. **YouTube videos** - 2-3 embeds with lazy loading, aria-labels, and noscript fallback (see `references/video-embeds.md`)
### Phase 7: Delivery
@@ -452,6 +451,7 @@ Present the completed article with a summary:
- Cover image: [source - Pixabay/Unsplash/Pexels or generated SVG]
- [N] inline images (Pixabay/Unsplash/Pexels)
- [N] SVG charts (types: bar, lollipop, donut, line)
+- [N] YouTube video embeds (titles: ...)
### Dual-Optimization Elements
- TL;DR box: present (N words)
@@ -476,5 +476,6 @@ Present the completed article with a summary:
- Resolve [INTERNAL-LINK] placeholders with actual URLs
- Add internal links to your existing content
- Run `/blog analyze <file>` to verify quality score
+- Generate VideoObject schema: `/blog schema <file>` (includes video markup)
- Generate audio narration: `/blog audio generate <file>` (optional)
```
diff --git a/skills/blog/SKILL.md b/skills/blog/SKILL.md
index 7d952c6..0520fa5 100644
--- a/skills/blog/SKILL.md
+++ b/skills/blog/SKILL.md
@@ -18,19 +18,9 @@ license: MIT
compatibility: Requires Claude Code and Python 3.11+ for quality scoring
metadata:
author: AgriciDaniel
- version: "1.6.0"
+ version: "1.7.0"
user-invokable: true
argument-hint: "[write|rewrite|analyze|brief|calendar|cannibalization|strategy|outline|seo-check|schema|repurpose|geo|image|audit|factcheck|persona|taxonomy|notebooklm|audio] [topic-or-file]"
-allowed-tools:
- - Read
- - Write
- - Edit
- - Bash
- - Grep
- - Glob
- - WebFetch
- - WebSearch
- - Task
---
# Blog -- Content Engine for Rankings & AI Citations
@@ -63,6 +53,7 @@ Perplexity, Google AI Overviews, Gemini).
| `/blog taxonomy [suggest\|sync\|audit]` | Tag/category management across CMS platforms |
| `/blog notebooklm <question>` | Query NotebookLM for source-grounded research |
| `/blog audio [generate\|voices\|setup]` | Generate audio narration of blog posts |
+| `/blog google [command] [args]` | Google API data: PSI, CrUX, GSC, GA4, NLP, YouTube, Keywords |
| `/blog update <file>` | Update existing post with fresh stats (routes to rewrite) |
## Orchestration Logic
@@ -91,6 +82,7 @@ Perplexity, Google AI Overviews, Gemini).
- `image` → `blog-image` (AI image generation and editing)
- `notebooklm` / `notebook` / `query-notebook` → `blog-notebooklm` (source-grounded notebook queries)
- `audio` / `narrate` / `tts` → `blog-audio` (audio narration generation)
+ - `google` / `gsc` / `psi` / `pagespeed` / `crux` / `cwv` → `blog-google` (Google API data and reports)
- `update` → `blog-rewrite` (with freshness-update mode)
### Platform Detection
@@ -119,7 +111,7 @@ Every blog post targets these 6 optimization pillars:
|--------|--------|---------------|
| Answer-First Formatting | +340% AI citations | Every H2 opens with 40-60 word stat-rich paragraph |
| Real Sourced Data | E-E-A-T trust | Tier 1-3 sources only, inline attribution |
-| Visual Media | Engagement + citations | Pixabay/Unsplash images + AI generation via Gemini + built-in SVG charts |
+| Visual Media | Engagement + citations | Pixabay/Unsplash images + AI generation via Gemini + built-in SVG charts + YouTube video embeds |
| FAQ Schema | +28% AI citations | Structured FAQ with 40-60 word answers |
| Content Structure | AI extractability | 50-150 word chunks, question headings, proper H hierarchy |
| Freshness Signals | 76% of top citations | Updated within 30 days, dateModified schema |
@@ -176,6 +168,7 @@ Load on-demand as needed (12 references):
- `references/ai-crawler-guide.md` -- AI bot management, robots.txt, SSR requirements
- `references/schema-stack.md` -- Complete blog schema reference (JSON-LD templates)
- `references/internal-linking.md` -- Link architecture, anchor text, hub-and-spoke model
+- `references/video-embeds.md` -- YouTube video embedding patterns, quality criteria, VideoObject schema
## Content Templates
@@ -222,6 +215,7 @@ Templates are in `templates/` and contain section structure, markers, and checkl
| `blog-taxonomy` | CMS taxonomy management (WordPress, Shopify, Ghost, Strapi, Sanity) |
| `blog-notebooklm` | Query Google NotebookLM for source-grounded research from user documents |
| `blog-audio` | Generate audio narration with Gemini TTS (summary/full/dialogue modes, 30 voices) |
+| `blog-google` | Google API integration: PSI, CrUX CWV, GSC, URL Inspection, Indexing, GA4, NLP, YouTube, Keywords, PDF reports |
## Agents
@@ -286,6 +280,12 @@ offered as an optional final step after blog-write completes. Generates summary,
full-article, or two-speaker dialogue narration via Gemini TTS. Falls back
gracefully when `GOOGLE_AI_API_KEY` is not configured.
+The `blog-google` sub-skill is both user-invocable (`/blog google pagespeed`)
+and callable internally by `blog-seo-check`, `blog-rewrite`, `blog-geo`, and
+`blog-audit` for real Google performance data. Falls back gracefully when
+credentials are not configured. Shares config with claude-seo at
+`~/.config/claude-seo/google-api.json`.
+
## Integration
Chart generation is built-in - no external dependencies required for full functionality.
diff --git a/skills/blog/references/schema-stack.md b/skills/blog/references/schema-stack.md
index a40f0fa..8cf363e 100644
--- a/skills/blog/references/schema-stack.md
+++ b/skills/blog/references/schema-stack.md
@@ -325,6 +325,57 @@ Used within BlogPosting for featured images and inline article images.
---
+## VideoObject Schema
+
+Used for YouTube videos embedded in blog posts. YouTube has the strongest
+AI visibility correlation (0.737). Each embedded video gets its own VideoObject.
+
+### Properties
+
+| Property | Required | Type | Description |
+|----------|----------|------|-------------|
+| `@type` | Yes | String | `"VideoObject"` |
+| `@id` | Yes | URI | `{siteUrl}/blog/{slug}#video-{index}` |
+| `name` | Yes | String | Video title |
+| `description` | Yes | String | First 200 chars of video description |
+| `thumbnailUrl` | Yes | URL | `https://img.youtube.com/vi/{id}/hqdefault.jpg` |
+| `uploadDate` | Yes | ISO 8601 | Video publish date |
+| `contentUrl` | Yes | URL | `https://www.youtube.com/watch?v={id}` |
+| `embedUrl` | Yes | URL | `https://www.youtube.com/embed/{id}` |
+| `duration` | Recommended | ISO 8601 | Duration (e.g., `PT10M30S`) |
+| `interactionStatistic` | Recommended | InteractionCounter | View count |
+| `publisher` | Optional | Organization | Channel name and URL |
+
+### Complete VideoObject Example
+
+```json
+{
+ "@type": "VideoObject",
+ "@id": "https://example.com/blog/seo-guide#video-1",
+ "name": "Complete Guide to Technical SEO in 2026",
+ "description": "Learn the essential technical SEO strategies for 2026 including Core Web Vitals optimization, structured data, and AI search readiness.",
+ "thumbnailUrl": "https://img.youtube.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
+ "uploadDate": "2026-01-20T00:00:00Z",
+ "contentUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ "embedUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ",
+ "duration": "PT12M45S",
+ "interactionStatistic": {
+ "@type": "InteractionCounter",
+ "interactionType": { "@type": "WatchAction" },
+ "userInteractionCount": 25000
+ }
+}
+```
+
+### Guidelines
+
+- Only generate for YouTube videos actually embedded in the post
+- Use `#video-1`, `#video-2` for sequential @id fragments
+- Duration must be ISO 8601 format (PT prefix, M for minutes, S for seconds)
+- Extract metadata from embed noscript text or YouTube Data API
+
+---
+
## Speakable Schema
Optimizes content for voice search and voice assistants (Google Assistant,
@@ -394,6 +445,7 @@ and AI systems to deduplicate references.
| WebPage | `{siteUrl}/blog/{slug}` | `https://example.com/blog/seo-guide` |
| BreadcrumbList | `{siteUrl}/blog/{slug}#breadcrumb` | `https://example.com/blog/seo-guide#breadcrumb` |
| FAQPage | `{siteUrl}/blog/{slug}#faq` | `https://example.com/blog/seo-guide#faq` |
+| VideoObject | `{siteUrl}/blog/{slug}#video-{N}` | `https://example.com/blog/seo-guide#video-1` |
### Rules
diff --git a/skills/blog/references/video-embeds.md b/skills/blog/references/video-embeds.md
new file mode 100644
index 0000000..73791ee
--- /dev/null
+++ b/skills/blog/references/video-embeds.md
@@ -0,0 +1,185 @@
+# YouTube Video Embed Reference
+
+## Why YouTube Embeds Matter
+
+Video is the strongest signal for AI visibility. Key data points:
+
+- **0.737 correlation** with AI visibility -- the strongest single signal (Ahrefs 75K-brand study)
+- Video citations in AI Overviews up **414%** year-over-year (BrightEdge Q1 2025)
+- How-to video citations up **651%**, visual demo citations up **592%** (BrightEdge)
+- YouTube is cited **200x more** than any other video platform by AI systems
+- Pages with embedded video have **53x higher chance** of front-page ranking (Forrester)
+
+Embedding relevant YouTube videos is not optional -- it is a top-tier ranking and
+AI citation signal that every blog post should leverage when suitable videos exist.
+
+---
+
+## Video Quality Criteria
+
+### Minimum Standards
+
+| Criterion | Minimum | Preferred |
+|-----------|---------|-----------|
+| Views | >1,000 | >10,000 |
+| Like ratio | >90% | >95% |
+| Recency | <3 years | <18 months |
+| Channel subscribers | >1,000 | >10,000 |
+| Duration | >3 minutes | 5-15 minutes |
+| Captions | Present | Accurate/manual |
+| Relevance | Title keyword match | Title + description match |
+
+### Quality Scoring Formula (0-100)
+
+| Factor | Weight | Scoring Method |
+|--------|--------|---------------|
+| Relevance (title/description keyword match) | 35 pts | Exact keyword in title = 35, partial = 20, description only = 10 |
+| View count (log scale) | 20 pts | log10(views) / log10(10M) * 20, capped at 20 |
+| Recency (months since publish) | 20 pts | max(0, 20 - (months_old * 0.8)) |
+| Channel authority (subscribers, log scale) | 15 pts | log10(subs) / log10(1M) * 15, capped at 15 |
+| Engagement (like ratio) | 10 pts | (like_ratio - 0.80) / 0.20 * 10, capped at 10 |
+
+**Minimum score threshold: 50/100.** Videos scoring below 50 should be skipped.
+
+---
+
+## Embed Placement Strategy
+
+| Position | Video Purpose | When |
+|----------|--------------|------|
+| After introduction (before first H2 body) | Overview / explainer | Always place 1st video here |
+| Mid-article (after 2nd or 3rd H2) | Tutorial / demo / how-to | If video shows a process |
+| Before FAQ or conclusion | Summary or expert opinion | Optional 3rd video |
+
+### Placement Rules
+
+- **2-3 videos per post** (never more than 3)
+- Minimum **500 words** between video embeds
+- Never place a video immediately before or after a chart
+- Videos **complement** text -- they never replace written content
+
+---
+
+## Embed Code Patterns
+
+### MDX / Next.js (camelCase, srcdoc lazy loading)
+
+```jsx
+<figure className="video-embed" style={{margin: '2.5rem 0', textAlign: 'center'}}>
+ <div style={{position: 'relative', paddingBottom: '56.25%', height: 0, overflow: 'hidden', maxWidth: '100%', borderRadius: '12px'}}>
+ <iframe
+ srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href='https://www.youtube.com/embed/VIDEO_ID?autoplay=1'><img src='https://img.youtube.com/vi/VIDEO_ID/hqdefault.jpg' alt='VIDEO_TITLE'><span>&#x25BA;</span></a>"
+ style={{position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 'none'}}
+ loading="lazy"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowFullScreen
+ title="VIDEO_TITLE"
+ aria-label="YouTube video: VIDEO_TITLE"
+ />
+ </div>
+ <noscript>
+ <p><strong>Video:</strong> <a href="https://www.youtube.com/watch?v=VIDEO_ID">VIDEO_TITLE</a> by CHANNEL_NAME. DESCRIPTION_EXCERPT</p>
+ </noscript>
+</figure>
+```
+
+### HTML / WordPress (standard attributes, srcdoc lazy loading)
+
+```html
+<figure class="video-embed" style="margin: 2.5rem 0; text-align: center;">
+ <div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; border-radius: 12px;">
+ <iframe
+ srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href='https://www.youtube.com/embed/VIDEO_ID?autoplay=1'><img src='https://img.youtube.com/vi/VIDEO_ID/hqdefault.jpg' alt='VIDEO_TITLE'><span>&#x25BA;</span></a>"
+ style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none;"
+ loading="lazy"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowfullscreen
+ title="VIDEO_TITLE"
+ aria-label="YouTube video: VIDEO_TITLE">
+ </iframe>
+ </div>
+ <noscript>
+ <p><strong>Video:</strong> <a href="https://www.youtube.com/watch?v=VIDEO_ID">VIDEO_TITLE</a> by CHANNEL_NAME. DESCRIPTION_EXCERPT</p>
+ </noscript>
+</figure>
+```
+
+### Standard Markdown (thumbnail link fallback)
+
+```markdown
+[![VIDEO_TITLE](https://img.youtube.com/vi/VIDEO_ID/hqdefault.jpg)](https://www.youtube.com/watch?v=VIDEO_ID)
+*Video: [VIDEO_TITLE](https://www.youtube.com/watch?v=VIDEO_ID) by CHANNEL_NAME*
+```
+
+### Hugo
+
+Use the built-in shortcode -- do not use raw HTML embeds:
+
+```
+{{</* youtube VIDEO_ID */>}}
+```
+
+### Next.js Config Note
+
+For MDX projects using YouTube thumbnails, add to `next.config.ts` remotePatterns:
+
+```typescript
+{ protocol: 'https', hostname: 'img.youtube.com' }
+```
+
+---
+
+## VideoObject JSON-LD Schema
+
+Add a VideoObject to the page `@graph` for each embedded video. Use the stable
+`@id` pattern with a video index suffix.
+
+```json
+{
+ "@type": "VideoObject",
+ "@id": "{siteUrl}/blog/{slug}#video-{index}",
+ "name": "Video title",
+ "description": "Video description excerpt (first 200 chars)",
+ "thumbnailUrl": "https://img.youtube.com/vi/{videoId}/hqdefault.jpg",
+ "uploadDate": "YYYY-MM-DDTHH:MM:SSZ",
+ "contentUrl": "https://www.youtube.com/watch?v={videoId}",
+ "embedUrl": "https://www.youtube.com/embed/{videoId}",
+ "duration": "PT{M}M{S}S",
+ "interactionStatistic": {
+ "@type": "InteractionCounter",
+ "interactionType": { "@type": "WatchAction" },
+ "userInteractionCount": VIEW_COUNT
+ }
+}
+```
+
+Replace `{index}` with 1, 2, or 3 matching embed order. Include `duration` in
+ISO 8601 format (e.g., `PT12M30S` for 12 minutes 30 seconds).
+
+---
+
+## Noscript Fallback for AI Crawlers
+
+AI crawlers (GPTBot, PerplexityBot, ClaudeBot, Google-Extended) do not execute
+JavaScript, so YouTube iframes are invisible to them. The `<noscript>` block
+provides a text fallback containing:
+
+- Video title as anchor text linking to YouTube
+- Channel name for source attribution
+- Description excerpt for topical context
+
+This ensures AI systems can discover and reference the video content even without
+rendering the embed. Every video embed must include a noscript fallback.
+
+---
+
+## Graceful Degradation
+
+| Scenario | Behavior |
+|----------|----------|
+| No GOOGLE_API_KEY available | Use WebSearch `site:youtube.com [topic] [year]` to find videos |
+| No suitable videos found | Skip silently, continue blog generation without video |
+| API rate limit exceeded | Use cached/previously found videos, or skip |
+| Video removed after embedding | Noscript text provides graceful fallback with title and link |
+| Embed blocked by privacy settings | srcdoc pattern shows thumbnail placeholder until clicked |
+| Reader has JavaScript disabled | Noscript block renders video title, channel, and description |
diff --git a/skills/blog/references/visual-media.md b/skills/blog/references/visual-media.md
index 1f61d9c..beece73 100644
--- a/skills/blog/references/visual-media.md
+++ b/skills/blog/references/visual-media.md
@@ -402,3 +402,18 @@ The sub-skill returns complete SVG wrapped in a `<figure>`. Verify before embedd
| Same chart type twice | Visual monotony | Enforce chart diversity |
| No `role="img"` | Accessibility failure | Always include |
| No source attribution | Trust issue | Always cite data source |
+
+---
+
+## YouTube Video Embeds
+
+YouTube videos are part of the visual media mix alongside images, charts, and
+AI-generated images. YouTube has the strongest AI visibility correlation (0.737)
+of any signal (Ahrefs 75K brands).
+
+See `references/video-embeds.md` for:
+- Embed patterns (srcdoc lazy loading for MDX, HTML, Markdown, Hugo)
+- Video quality criteria and scoring (min 50/100)
+- Placement strategy (2-3 per post, 500+ words apart)
+- VideoObject JSON-LD schema template
+- Noscript fallback for AI crawlers