Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
release: v2.2.4 community maintenance
Agrici Daniel6b63c8bb7b2e
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex f63b878..1391f28 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -5,16 +5,15 @@"name": "AgriciDaniel"},"metadata": {- "description": "Comprehensive SEO analysis plugin for Claude Code. 25 sub-skills and 18 sub-agents, plus 8 optional MCP extensions (DataForSEO, Firecrawl, Banana, Ahrefs, SE Ranking, Profound, Bing Webmaster, Unlighthouse): headless rendering, QRG-aligned content quality gates, LCP subparts via CrUX, IndexNow, Schema.org generators, and AI Share-of-Voice tracking. v2.2.3 applies a 319-finding verified maintenance pass: GBP Q&A correction, Google-confirmed AI Mode model naming, refreshed image-model IDs, and a new reference-graph consistency gate."+ "description": "Comprehensive SEO analysis plugin for Claude Code. 25 sub-skills and 18 sub-agents, plus 8 optional MCP extensions (DataForSEO, Firecrawl, Banana, Ahrefs, SE Ranking, Profound, Bing Webmaster, Unlighthouse). v2.2.4 adds a managed cross-platform runtime and safe sitemap discovery, and repairs GSC pagination, Bing endpoints, extension paths, Windows portability, SPA rendering, and JSON-LD extraction."},"plugins": [{"name": "claude-seo","source": "./",- "description": "Comprehensive SEO analysis plugin for Claude Code. 25 sub-skills and 18 sub-agents, plus 8 optional MCP extensions. Shared headless rendering, QRG-aligned content quality gates, LCP subparts via CrUX, IndexNow, four Schema.org generators, AI Share-of-Voice tracking, and multi-platform portability. v2.2.3 applies a 319-finding verified maintenance pass: GBP Q&A correction, Google-confirmed AI Mode model naming, refreshed image-model IDs, and a new reference-graph consistency gate wired into CI.",+ "description": "Comprehensive SEO analysis plugin for Claude Code. 25 sub-skills and 18 sub-agents, plus 8 optional MCP extensions. v2.2.4 adds a managed cross-platform runtime and safe sitemap discovery, and repairs GSC pagination, Bing endpoints, extension paths, Windows portability, SPA rendering, JSON-LD extraction, and DataForSEO permissions.","author": {"name": "AgriciDaniel",- "email": "[email protected]","url": "https://github.com/AgriciDaniel"},"category": "marketing",diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex f181124..34f4e59 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,10 +1,9 @@{"name": "claude-seo",- "version": "2.2.3",+ "version": "2.2.4","description": "Comprehensive SEO analysis plugin for Claude Code. 25 sub-skills (21 core + 1 orchestrator + 1 framework + 2 extension mirrors) and 18 sub-agents cover technical SEO, content quality, schema, sitemaps, Core Web Vitals, local SEO, backlinks, AI/GEO, ecommerce, hreflang, SXO, clustering, drift monitoring, and Google APIs. Includes optional MCP extensions, SPA-aware rendering, portability, and hardened SSRF/DNS-rebinding safe fetchers.","author": {"name": "AgriciDaniel",- "email": "[email protected]","url": "https://github.com/AgriciDaniel"},"license": "MIT",diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2ba4f39..794b7e5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -14,10 +14,10 @@ jobs:name: Python Syntax Checkruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Set up Python 3.10- uses: actions/setup-python@v6+ uses: actions/setup-python@v7with:python-version: "3.10"@@ -36,10 +36,10 @@ jobs:# limit and the sync_flow dry-run test fails on shared-runner IPs.GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}steps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Set up Python 3.10- uses: actions/setup-python@v6+ uses: actions/setup-python@v7with:python-version: "3.10"@@ -59,7 +59,7 @@ jobs:name: Secret scanruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Scan tracked files for leaked credentialsrun: |diff --git a/.github/workflows/v2.yml b/.github/workflows/v2.ymlindex c29baa9..bcff9cf 100644--- a/.github/workflows/v2.yml+++ b/.github/workflows/v2.yml@@ -24,13 +24,13 @@ permissions:jobs:manifest:- name: Manifest consistency (13 assertions)+ name: Manifest consistency (15 assertions)runs-on: ubuntu-lateststeps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Set up Python 3.10- uses: actions/setup-python@v6+ uses: actions/setup-python@v7with:python-version: "3.10"@@ -44,10 +44,10 @@ jobs:name: SSRF + DNS rebinding suiteruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Set up Python 3.10- uses: actions/setup-python@v6+ uses: actions/setup-python@v7with:python-version: "3.10"@@ -76,10 +76,10 @@ jobs:# 60/hr anonymous rate limit. Identical to ci.yml.GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}steps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Set up Python 3.10- uses: actions/setup-python@v6+ uses: actions/setup-python@v7with:python-version: "3.10"@@ -95,7 +95,7 @@ jobs:name: Secret scanruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v6+ - uses: actions/checkout@v7- name: Scan tracked files for leaked credentialsrun: |diff --git a/AGENTS.md b/AGENTS.mdindex 000abf8..8276c4f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,7 @@# Claude SEO: Multi-Platform Agent Instructions> For **Cursor**, **Cursor Cloud Agents**, **Google Antigravity**, **Gemini CLI**,+> **Grok Build**,> **OpenAI Codex CLI**, **Cline**, **Aider**, and any other agent harness that> reads project-root agent instructions.>@@ -12,7 +13,7 @@ Every skill in `skills/*/SKILL.md` is authored to a portable subset of theClaude Code skill spec. Validate compatibility with your harness via:```bash-python3 scripts/portability_check.py+./bin/claude-seo run portability_check.py```The check confirms each `SKILL.md` has the minimum frontmatter every harness@@ -28,6 +29,7 @@ descriptive comments) that other harnesses may ignore but do not reject.| **Cursor Cloud Agents** | Push the repo; Cloud Agents read `AGENTS.md` automatically at session start. || **Google Antigravity** | Point the workspace at this repo root; Antigravity reads `AGENTS.md` first, falls back to `skills/`. || **Gemini CLI** | `gemini init` in this repo loads `AGENTS.md`. Skills are activated via `activate_skill <name>` in conversation. |+| **Grok Build** | Open this repository in Grok Build. It reads `AGENTS.md` and Claude Code compatible plugins and skills without a separate layout. Use `grok inspect` to verify discovery. See the [official compatibility guide](https://docs.x.ai/build/features/skills-plugins-marketplaces). || **OpenAI Codex CLI** | Reads `AGENTS.md` from project root. Bash tools work as documented; some Claude-specific tool names (Read/Write/Edit) are aliased to Codex equivalents transparently. || **Cline** | Loads `AGENTS.md` from project root. Skills appear as system messages; subagent delegation falls back to in-context expansion. || **Aider** | Reads `AGENTS.md` if present; otherwise falls back to README. Aider does not support sub-agent dispatch; the seo-* skills run inline. |@@ -54,7 +56,7 @@ in case a recipe needs a specific call.Claude SEO is a Tier 4 SEO analysis skill with 25 sub-skills (21 core + 1 orchestrator +1 framework integration + 2 extension mirrors), 18 sub-agents (15 core + 1 framework-integration + 2 extension mirrors), and 50 Python execution scripts.+integration + 2 extension mirrors), and 53 Python execution scripts.## Quick Reference@@ -104,24 +106,24 @@ provide execution capabilities.**Running scripts directly** (Cursor doesn't have MCP):```bash# Page fetching with SSRF protection-python3 scripts/fetch_page.py https://example.com+./bin/claude-seo run fetch_page.py https://example.com# HTML parsing for SEO elements-python3 scripts/parse_html.py https://example.com+./bin/claude-seo run parse_html.py https://example.com# PageSpeed Insights-python3 scripts/pagespeed_check.py https://example.com --json+./bin/claude-seo run pagespeed_check.py https://example.com --json# Drift baseline-python3 scripts/drift_baseline.py https://example.com+./bin/claude-seo run drift_baseline.py https://example.com# DataForSEO (requires credentials)-DATAFORSEO_USERNAME=user DATAFORSEO_PASSWORD=pass python3 scripts/dataforseo_merchant.py search "keyword"+DATAFORSEO_USERNAME=user DATAFORSEO_PASSWORD=pass ./bin/claude-seo run dataforseo_merchant.py search "keyword"```**Cursor Cloud gotchas:**- SSL certificates may not resolve for some domains. Investigate the certificate issue rather than disabling verification.-- PATH may not include Python venv. Use full path: `~/.claude/skills/seo/.venv/bin/python`+- Run bundled tools through `claude-seo`; never call the venv interpreter directly.- Screenshots save to `/tmp/` not CWD. Check absolute paths.## Using with Google Antigravity@@ -163,7 +165,7 @@ skills/ # 25 sub-skills (auto-discovered)seo-dataforseo/ # DataForSEO (extension)seo-image-gen/ # AI images (extension)agents/ # 18 subagents-scripts/ # 50 Python scripts+scripts/ # 53 Python scripts, including the managed runtimeschema/ # JSON-LD templatesextensions/ # 8 MCP extensions: DataForSEO, Firecrawl, Banana, Ahrefs, SE Ranking, Profound, Bing Webmaster, Unlighthouse```diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 738706c..fe1f226 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,45 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [2.2.4] - 2026-07-20++Community maintenance release following a full review of every open issue and pull request.+Accepted findings were reconciled against the current release base, with superseded or unsafe+patches excluded. No breaking command changes. Full suite: 410 passing tests.++### Added++- Managed cross-platform Python runtime with `claude-seo run`, `/seo setup`, and `/seo doctor`.+ Plugin environments persist under Claude's plugin data directory, manual installs use an+ isolated local environment, and bundled scripts no longer depend on the caller's working+ directory or a hardcoded Python executable.+- SSRF-safe sitemap discovery covering robots.txt directives, common CMS locations, stale+ fallbacks, bounded responses, and strict cross-host validation.+- Contributor and issue-reporter acknowledgements for the complete maintenance review cycle.++### Fixed++- GSC queries now honor exact result limits, validate dimensions before API access, support+ dimensionless totals, and report whether aggregate totals are complete.+- Bing Webmaster backlink commands now use supported endpoints, bounded pagination, deduplication,+ registered-property comparison, partial-failure reporting, and sanitized errors.+- DataForSEO agents now expose only the required MCP tool family and fail closed when it is absent.+- Banana extension paths now work in plugin and manual layouts.+- OAuth token persistence is safe on Windows, hook and child-process output is UTF-8, and report+ input handling is explicitly UTF-8.+- SPA rendering recognizes common hosted builders, uses bounded DOM stabilization, and extracts+ JSON-LD before HTML truncation without leaking malformed fragments in routine output.+- Removed unsupported FAQPage rich-result benefit claims and templates after Google's retirement+ of FAQ rich results.+- GitHub Actions checkout and Python setup actions moved to v7. Anonymous FLOW synchronization now+ retries rate-limited requests through the authenticated path when available.++### Security++- Runtime dispatch is allowlisted, setup upgrades are rollback-safe, diagnostics redact paths and+ identity-like values, and structured-data output is bounded.+- Removed the maintainer email address from public package and citation metadata.+## [2.2.3] - 2026-07-14Prompt-hygiene alignment to the Fable 5 prompt principles. No behavior, routing, or output changes.diff --git a/CITATION.cff b/CITATION.cffindex 477f101..f3e3643 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -7,13 +7,12 @@ authors:- alias: AgriciDanielgiven-names: Danielfamily-names: Agrici- email: [email protected]website: 'https://agricidaniel.com'repository-code: 'https://github.com/AgriciDaniel/claude-seo'url: 'https://github.com/AgriciDaniel/claude-seo'license: MIT-version: 2.2.3-date-released: '2026-07-10'+version: 2.2.4+date-released: '2026-07-20'keywords:- seo- claude-codediff --git a/CLAUDE.md b/CLAUDE.mdindex 363f7be..7109749 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -21,7 +21,7 @@ claude-seo/CONTRIBUTORS.md # Community credits (Pro Hub Challenge)AGENTS.md # Multi-platform agent instructions (Cursor, Antigravity).claude-plugin/- plugin.json # Plugin manifest (v2.2.3)+ plugin.json # Plugin manifest (v2.2.4)marketplace.json # Marketplace catalog for distributionskills/ # 25 sub-skills (auto-discovered)seo/ # Main orchestrator skill@@ -85,11 +85,11 @@ claude-seo/seo-flow.md # FLOW framework integrationhooks/ # Quality gate hookshooks.json # PostToolUse schema validation- scripts/ # Python execution scripts (51 tracked + dev-only helpers)+ scripts/ # 53 Python execution scriptsgoogle_auth.py # Credential management (OAuth, SA, API key, 4-tier detection)backlinks_auth.py # Backlink API credential management (Moz, Bing)moz_api.py # Moz Link Explorer API (DA/PA, spam, domains, anchors)- bing_webmaster.py # Bing Webmaster Tools API (links, competitor comparison)+ bing_webmaster.py # Bing Webmaster Tools API (registered-site links/comparison)commoncrawl_graph.py # Common Crawl web graph parser (PageRank, in-degree)verify_backlinks.py # Backlink existence verification crawlerpagespeed_check.py # PSI v5 + CrUX API@@ -194,15 +194,16 @@ claude-seo/- Scripts must have docstrings, CLI interface, and JSON output- Follow kebab-case naming for all skill directories- Agents invoked via Agent tool, never via Bash-- Python dependencies install into `~/.claude/skills/seo/.venv/`+- Bundled tools run through `claude-seo run`; plugin state uses `CLAUDE_PLUGIN_DATA`+- Manual Python dependencies install into `~/.claude/skills/seo/.venv/`- Test with `python3 -m pytest tests/` after changes (if applicable)## Security Rules- **Never commit credentials**: `.env`, `client_secret*.json`, `oauth-token.json`, `service_account*.json` are all in `.gitignore`-- **URL validation**: All scripts that accept user URLs must call `validate_url()` from `google_auth.py` before making API calls. This blocks private IPs, loopback, and GCP metadata endpoints (SSRF protection).+- **URL validation**: All scripts that connect to user-supplied URLs must use `scripts/url_safety.py` (`validate_url_strict()` plus the pinned safe request helpers). This blocks private IPs, loopback, metadata endpoints, redirect rebinding, and DNS rebinding.- **OAuth tokens**: Never store `client_secret` in the token file. Read it from the client_secret.json file at runtime.-- **No hardcoded paths**: Use `os.path.dirname(os.path.abspath(__file__))` for relative paths, never `/home/username/...`+- **No hardcoded paths**: Use `os.path.dirname(os.path.abspath(__file__))` for relative paths, never a user-specific absolute path- **Config location**: `~/.config/claude-seo/google-api.json` and `~/.config/claude-seo/backlinks-api.json` (user-space, not in repo)## Report Generation Rules@@ -271,7 +272,7 @@ Promoting to public on release:- **`aimh` accepts day-to-day pushes.** No release-gate ceremony requiredfor the private remote.- **Tags push to private first.** Historical pre-release illustration: v2.0.0- once lived on `aimh` before `origin`. Current released tags through v2.2.3+ once lived on `aimh` before `origin`. Current released tags through v2.2.4are on both remotes.- **History stays shared.** Never rewrite history on either remote withforce-push unless explicitly authorized for that specific operation.diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.mdindex b2827f6..8cb493a 100644--- a/CONTRIBUTORS.md+++ b/CONTRIBUTORS.md@@ -31,6 +31,28 @@ Attribution header on every bundled prompt file (automated by `scripts/sync_flow## Community Pull Requests+### 2026 maintenance review cycle++These contributors supplied implementation work or substantive design proposals.+Credit is preserved when a patch was superseded, selectively reimplemented, or+not merged after review.++| Contributor | PR | Contribution category | Review outcome |+|------------|----|-----------------------|----------------|+| [@wonsukchoi](https://github.com/wonsukchoi) | [#165](https://github.com/AgriciDaniel/claude-seo/pull/165), [#166](https://github.com/AgriciDaniel/claude-seo/pull/166), [#167](https://github.com/AgriciDaniel/claude-seo/pull/167), [#168](https://github.com/AgriciDaniel/claude-seo/pull/168), [#169](https://github.com/AgriciDaniel/claude-seo/pull/169), [#170](https://github.com/AgriciDaniel/claude-seo/pull/170), [#171](https://github.com/AgriciDaniel/claude-seo/pull/171) | Image paths, runtime setup, sitemap discovery, DataForSEO permissions, Bing API redesign, and Windows launcher proposals | Findings informed current-base implementations; patches were superseded or consolidated after review |+| [@powehi-ai](https://github.com/powehi-ai) | [#162](https://github.com/AgriciDaniel/claude-seo/pull/162) | Codex manifest and documentation proposal | Reviewed; not integrated because the repository already uses its portable Codex surface |+| [@maticyorg](https://github.com/maticyorg) | [#160](https://github.com/AgriciDaniel/claude-seo/pull/160) | Subagent model inheritance proposal | Reviewed; the proposed model value was not portable, so the patch was not integrated |+| [@GilboBlagins](https://github.com/GilboBlagins) | [#159](https://github.com/AgriciDaniel/claude-seo/pull/159) | Optional external knowledge-directory design | Reviewed; not integrated because the trust boundary needs a stricter design |+| [@voipcomjohn](https://github.com/voipcomjohn) | [#158](https://github.com/AgriciDaniel/claude-seo/pull/158) | Windows UTF-8 hook output | Reconciled into the current-base Windows encoding work |+| [@MSADTP](https://github.com/MSADTP) | [#157](https://github.com/AgriciDaniel/claude-seo/pull/157) | Full JSON-LD extraction before output truncation | Reimplemented with bounded structured parsing and regression coverage |+| [@lukababu](https://github.com/lukababu) | [#154](https://github.com/AgriciDaniel/claude-seo/pull/154) | Grok Build installation documentation | Selectively integrated using current official Grok compatibility guidance |+| [@kuhlsnu](https://github.com/kuhlsnu) | [#150](https://github.com/AgriciDaniel/claude-seo/pull/150) | Hosted-builder SPA detection and render timeout handling | Selectively reimplemented with bounded renderer behavior and tests |+| [@SENTMarketing](https://github.com/SENTMarketing) | [#147](https://github.com/AgriciDaniel/claude-seo/pull/147) | Windows-safe OAuth token permissions | Superseded by the current guarded implementation and regression coverage |+| [@BubblyWolf](https://github.com/BubblyWolf) | [#145](https://github.com/AgriciDaniel/claude-seo/pull/145) | Broken references, documentation accuracy, Windows portability, and CI review | Useful findings were reconciled selectively against the current release base |+| [@mubashirsidiki](https://github.com/mubashirsidiki) | [#141](https://github.com/AgriciDaniel/claude-seo/pull/141) | Bright Data extension proposal | Fully reviewed; not integrated because the extension needs a separate security and cost-control design |+| [@mukulcodezz](https://github.com/mukulcodezz) | [#140](https://github.com/AgriciDaniel/claude-seo/pull/140) | Public marketplace branding correction | Superseded by the public branding already shipped on the release branch |+| [@us](https://github.com/us) | [#136](https://github.com/AgriciDaniel/claude-seo/pull/136) | fastCRW crawling extension proposal | Fully reviewed; not integrated because installer, safety, and integration contracts need redesign |+### v2.2.0| Contributor | PR | What |@@ -68,6 +90,21 @@ Attribution header on every bundled prompt file (automated by `scripts/sync_flow| [@MalteBerlin](https://github.com/MalteBerlin) | [#45](https://github.com/AgriciDaniel/claude-seo/pull/45) | Sub-skills count correction || [@olivierroy](https://github.com/olivierroy) | [#43](https://github.com/AgriciDaniel/claude-seo/pull/43) | Extension install fix |+## Community Issue Reports++### 2026 maintenance review cycle++| Reporter | Issue | Contribution category |+|----------|-------|-----------------------|+| [@sam-fakhreddine](https://github.com/sam-fakhreddine) | [#174](https://github.com/AgriciDaniel/claude-seo/issues/174) | Managed virtual-environment bypass in agent script commands |+| [@n-youn9](https://github.com/n-youn9) | [#173](https://github.com/AgriciDaniel/claude-seo/issues/173) | GSC total-limit pagination hang and reproducible root-cause analysis |+| [@jonathanlombi-debug](https://github.com/jonathanlombi-debug) | [#163](https://github.com/AgriciDaniel/claude-seo/issues/163) | Banana extension script-path and install-layout analysis |+| [@sohilshrestha0](https://github.com/sohilshrestha0) | [#161](https://github.com/AgriciDaniel/claude-seo/issues/161) | Missing render script path in delegated audit execution |+| [@Kickermax](https://github.com/Kickermax) | [#153](https://github.com/AgriciDaniel/claude-seo/issues/153) | Bing Webmaster endpoint failure reproduction and method probing |+| [@Arul-Raaj](https://github.com/Arul-Raaj) | [#149](https://github.com/AgriciDaniel/claude-seo/issues/149) | Retired FAQ rich-result guidance report |+| [@atahan150](https://github.com/atahan150) | [#137](https://github.com/AgriciDaniel/claude-seo/issues/137), [#138](https://github.com/AgriciDaniel/claude-seo/issues/138), [#139](https://github.com/AgriciDaniel/claude-seo/issues/139), [#148](https://github.com/AgriciDaniel/claude-seo/issues/148) | Plugin provisioning, Windows Python resolution, portable script roots, and DataForSEO MCP permissions |+| [@maulikvora](https://github.com/maulikvora) | [#142](https://github.com/AgriciDaniel/claude-seo/issues/142) | Non-default WordPress sitemap discovery |+## Security DisclosuresResponsible disclosures incorporated into v2.2.0. Thank you for reporting privately or via issues:diff --git a/README.md b/README.mdindex bc67c86..724cf4f 100644--- a/README.md+++ b/README.md@@ -8,7 +8,7 @@[](https://claude.ai/claude-code)[](LICENSE)[](https://github.com/AgriciDaniel/claude-seo/releases)-[](tests/)+[](tests/)[](https://www.skool.com/ai-marketing-hub-pro)> **Two versions of this skill.**@@ -82,8 +82,13 @@ The fastest path. One-time marketplace add, then plugin install:```bash/plugin marketplace add AgriciDaniel/claude-seo/plugin install claude-seo@agricidaniel-claude-seo+/seo setup```+The explicit setup step creates an isolated Python environment in Claude's+persistent plugin data and installs Playwright Chromium. Check it at any time+with `/seo doctor`. No global Python packages or PATH shims are created.+### Manual Install (Unix / macOS / Linux)```bash@@ -138,10 +143,12 @@ claude-30 user-invocable `/seo` commands across the orchestrator, its sub-skills, and 8 MCP extensions. Full reference in [docs/COMMANDS.md](docs/COMMANDS.md).+32 user-invocable `/seo` commands across the orchestrator, its sub-skills, and 8 MCP extensions. Full reference in [docs/COMMANDS.md](docs/COMMANDS.md).| Command | Description ||---------|-------------|+| `/seo setup` | Create or refresh the isolated Python runtime and Chromium |+| `/seo doctor` | Check runtime readiness without changing the system || `/seo audit <url>` | Full website audit with parallel sub-agent delegation || `/seo page <url>` | Deep single-page analysis || `/seo technical <url>` | Technical SEO audit across 9 categories |@@ -320,7 +327,7 @@ v2.0.0 is the largest release in the plugin's history. Six build phases, all shi- **Phase E: AI search reframing and 5 new MCP extensions.** Ahrefs, SE Ranking (AI Share-of-Voice), Profound (LLM citation tracker), Bing Webmaster plus IndexNow, Unlighthouse. Plus the parasite-SEO risk scanner per Google's November 2024 [site reputation abuse policy](https://developers.google.com/search/blog/2024/11/site-reputation-abuse-update).- **Phase F: Local, international, and privacy polish.** Google Business Profile deprecation linter (chat field and `.business.site` URLs, with Q&A treated as category/region-limited), DMA consent-mode-v2 click-through diagnostic, machine-translation QA flag per January 2025 QRG.-Test coverage grew from 39 (v1.9.9) to 326 across the v2 line; the url_safety suite alone runs 91 SSRF and DNS-rebinding bypass cases, closing the obfuscated-IPv4, FQDN-trailing-dot, and redirect-rebinding bypass classes. Full migration notes and breaking changes: [docs/MIGRATION-v1-to-v2.md](docs/MIGRATION-v1-to-v2.md).+Test coverage grew from 39 (v1.9.9) to 410 across the v2 line; the url_safety suite alone runs 91 SSRF and DNS-rebinding bypass cases, closing the obfuscated-IPv4, FQDN-trailing-dot, and redirect-rebinding bypass classes. Full migration notes and breaking changes: [docs/MIGRATION-v1-to-v2.md](docs/MIGRATION-v1-to-v2.md).### Since v2.0.0@@ -329,6 +336,7 @@ Test coverage grew from 39 (v1.9.9) to 326 across the v2 line; the url_safety su- **v2.2.1 (June 2026): Google-currency reconfirmation + full command audit.** Lighthouse 13.4.0 with the new Agentic Browsing category, Google Search ignores llms.txt, an internally-reweighted E-E-A-T scorecard (Trust highest, per Google's 'trust is most important'); every `/seo` command and subcommand audited and COMMANDS.md brought to 100% coverage.- **v2.2.2 (July 2026): full-review maintenance.** Corrected GBP Q&A handling, AI Mode model naming, image-model IDs, hook input behavior, and added a strict reference-graph consistency gate.- **v2.2.3 (July 2026): prompt-hygiene alignment.** Normalized emphasis and punctuation across the prompt surface without changing behavior, routing, or output contracts.+- **v2.2.4 (July 2026): community maintenance.** Added the managed cross-platform runtime and safe sitemap discovery, repaired GSC pagination and totals, replaced removed Bing endpoints, fixed extension and Windows portability gaps, and reconciled every open issue and pull request.## Limitationsdiff --git a/SECURITY.md b/SECURITY.mdindex 3783bf0..3c6764a 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -83,5 +83,5 @@ If you are auditing, these are the high-leverage files:- No credentials or API keys are committed to this repository. `.gitignore` blocks every known credential filename pattern.- Install scripts write only to user-level directories under `~/.claude/` and `~/.config/claude-seo/`.-- Python dependencies install into an isolated virtual environment at `~/.claude/skills/seo/.venv/`.+- Python dependencies install into an isolated virtual environment. Plugin installs use persistent `CLAUDE_PLUGIN_DATA`; manual installs use `~/.claude/skills/seo/.venv/`. The runtime never falls back to global or user package installation.- Every new fetcher must route through `scripts/url_safety.py` — there is no exception for "trusted" URLs.diff --git a/agents/seo-backlinks.md b/agents/seo-backlinks.mdindex 4937e93..6980113 100644--- a/agents/seo-backlinks.md+++ b/agents/seo-backlinks.md@@ -8,7 +8,7 @@ tools: Read, Bash, Write, Glob, GrepYou are a backlink profile analyst. When delegated tasks during an SEO audit:-1. Check credentials: `python3 scripts/backlinks_auth.py --check --json`+1. Check credentials: `claude-seo run backlinks_auth.py --check --json`2. Determine tier (0 = CC+verify, 1 = +Moz, 2 = +Bing, 3 = +DataForSEO)3. Run all available sources for the target domain4. Merge results with confidence weighting@@ -17,29 +17,31 @@ You are a backlink profile analyst. When delegated tasks during an SEO audit:## Tier-Based Workflow### Tier 0 (Always Available, No Config Needed)-- Common Crawl domain metrics: `python3 scripts/commoncrawl_graph.py <domain> --json`+- Common Crawl domain metrics: `claude-seo run commoncrawl_graph.py <domain> --json`- PageRank, PageRank rank, harmonic centrality, harmonic centrality rank, crawl/ranking presence-- If known backlinks provided, verify them: `python3 scripts/verify_backlinks.py --target <url> --links <file> --json`+- If known backlinks provided, verify them: `claude-seo run verify_backlinks.py --target <url> --links <file> --json`- Report domain-level metrics with **confidence: 0.50** note- At Tier 0, fewer than 4 scoring factors have data, report **INSUFFICIENT DATA**, not a numeric score- Never produce a misleading numeric score when most factors lack data sources### Tier 1 (+ Moz API)- All Tier 0 checks-- Moz URL metrics: `python3 scripts/moz_api.py metrics <url> --json`+- Moz URL metrics: `claude-seo run moz_api.py metrics <url> --json`- DA, PA, Spam Score, link counts, referring domains-- Moz referring domains: `python3 scripts/moz_api.py domains <url> --json`-- Moz anchor text: `python3 scripts/moz_api.py anchors <url> --json`-- Moz top pages: `python3 scripts/moz_api.py pages <domain> --json`+- Moz referring domains: `claude-seo run moz_api.py domains <url> --json`+- Moz anchor text: `claude-seo run moz_api.py anchors <url> --json`+- Moz top pages: `claude-seo run moz_api.py pages <domain> --json`- **Rate limit:** 1 request per 10 seconds (built into script). Plan calls carefully.- Report metrics with **confidence: 0.85** note### Tier 2 (+ Bing Webmaster)- All Tier 1 checks-- Bing inbound links: `python3 scripts/bing_webmaster.py links <url> --json`-- For competitor gap: `python3 scripts/bing_webmaster.py compare <url1> <url2> --json`+- Bing inbound links: `claude-seo run bing_webmaster.py links <url> --json`+- For comparison between two properties registered to the same Bing account:+ `claude-seo run bing_webmaster.py compare <url1> <url2> --json`- Report with **confidence: 0.70** for Bing data-- Bing's unique competitor comparison is especially valuable for gap analysis+- Never use Bing Webmaster data for an arbitrary competitor. Use Moz,+ DataForSEO, or Common Crawl when the second property is not registered.### Tier 3 (+ DataForSEO, Premium)- If DataForSEO MCP tools are available, use them for highest-fidelity data@@ -87,7 +89,7 @@ Before returning results, run the automated validator AND manual checks.### Step 1: Automated validationSave all collected data to a JSON file and run:```bash-python3 scripts/validate_backlink_report.py --report report_data.json --json+claude-seo run validate_backlink_report.py --report report_data.json --json```The validator checks: schema claims, JS false negatives, H1 accuracy, reciprocal links,CC interpretation, and health score sufficiency. If status is "FAIL", fix errors before proceeding.@@ -110,7 +112,7 @@ If any check fails, fix the report before returning it.## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.Backlink verification (`/seo backlinks verify`) primarily reads outbound `<a>` tags, which are reliably present in raw HTML. `--mode never` is the right choice for speed on bulk verification jobs.diff --git a/agents/seo-content.md b/agents/seo-content.mdindex 048e8c9..af02755 100644--- a/agents/seo-content.md+++ b/agents/seo-content.md@@ -67,7 +67,7 @@ Provide:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes summary fields including `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate); use `--output` or import `render_page.render_page()` when full raw/rendered HTML is required. SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes summary fields including `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate); use `--output` or import `render_page.render_page()` when full raw/rendered HTML is required. SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.## Persistence Contractdiff --git a/agents/seo-dataforseo.md b/agents/seo-dataforseo.mdindex 5f3c45a..f03e6ba 100644--- a/agents/seo-dataforseo.md+++ b/agents/seo-dataforseo.md@@ -3,7 +3,7 @@ name: seo-dataforseodescription: DataForSEO data analyst. Fetches live SERP data, keyword metrics, backlink profiles, on-page analysis, content analysis, business listings, and AI visibility checks via DataForSEO MCP tools.model: sonnetmaxTurns: 25-tools: Read, Bash, Write, Glob, Grep+tools: Read, Write, Glob, Grep, mcp__dataforseo__*---You are a DataForSEO data analyst. When delegated tasks during an SEO audit or analysis:@@ -12,6 +12,8 @@ You are a DataForSEO data analyst. When delegated tasks during an SEO audit or a2. Use the most efficient tool combination for the requested data3. Apply default parameters: location_code=2840 (US), language_code=en unless specified4. Format output to match claude-seo conventions (tables, priority levels, scores)+5. If the MCP tools are unavailable, fail closed. Never inspect credential or+ configuration stores and never bypass MCP with curl, raw HTTP, or another client.## Efficient Tool Usagediff --git a/agents/seo-drift.md b/agents/seo-drift.mdindex 81d1887..1a762e0 100644--- a/agents/seo-drift.md+++ b/agents/seo-drift.md@@ -17,10 +17,10 @@ elements by comparing current page state against stored baselines.## ToolsAll page fetching goes through the project's existing scripts with SSRF protection:-- `python3 scripts/drift_baseline.py <url>` -- capture a new baseline-- `python3 scripts/drift_compare.py <url>` -- compare current state to baseline-- `python3 scripts/drift_history.py <url>` -- show change history-- `python3 scripts/drift_report.py <file> --output report.html` -- generate HTML report+- `claude-seo run drift_baseline.py <url>` -- capture a new baseline+- `claude-seo run drift_compare.py <url>` -- compare current state to baseline+- `claude-seo run drift_history.py <url>` -- show change history+- `claude-seo run drift_report.py <file> --output report.html` -- generate HTML reportNever use curl, wget, or raw HTTP requests. All fetching is handled by`scripts/fetch_page.py` internally, which validates URLs against private/loopbackdiff --git a/agents/seo-ecommerce.md b/agents/seo-ecommerce.mdindex 0e33442..8ab6123 100644--- a/agents/seo-ecommerce.md+++ b/agents/seo-ecommerce.md@@ -27,7 +27,7 @@ When delegated tasks during an SEO audit or analysis:Before ANY DataForSEO Merchant API call:```bash-python3 scripts/dataforseo_costs.py check <endpoint>+claude-seo run dataforseo_costs.py check <endpoint>```Only proceed if `"status": "approved"`. If `"needs_approval"`, surface the cost@@ -36,7 +36,7 @@ the limitation.After each API call, log the cost:```bash-python3 scripts/dataforseo_costs.py log <endpoint> <actual_cost>+claude-seo run dataforseo_costs.py log <endpoint> <actual_cost>```## Analysis Priorities@@ -65,7 +65,7 @@ Match existing claude-seo patterns:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.E-commerce sites overwhelmingly inject product schema client-side (Shopify, Magento PWA, headless commerce on Next.js). Prefer `--mode always` for product page audits and compare `raw_content` vs `content` to confirm whether the JSON-LD is server-rendered.diff --git a/agents/seo-geo.md b/agents/seo-geo.mdindex d655050..39bdeb7 100644--- a/agents/seo-geo.md+++ b/agents/seo-geo.md@@ -65,7 +65,7 @@ Provide a structured report with:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.AI citation analysis benefits from the `extracted_text` field, passage-level scoring should run against trafilatura's boilerplate-stripped output, not the full HTML, so navigation chrome and footers don't dilute the signal.diff --git a/agents/seo-google.md b/agents/seo-google.mdindex 6751879..e27afa3 100644--- a/agents/seo-google.md+++ b/agents/seo-google.md@@ -8,7 +8,7 @@ tools: Read, Bash, Write, Glob, Grep # Write needed for report/data file outputYou are a Google SEO API data analyst. When delegated tasks during an SEO audit:-1. Check credentials: `python3 scripts/google_auth.py --check --json`+1. Check credentials: `claude-seo run google_auth.py --check --json`2. Determine tier (0 = API key, 1 = + service account, 2 = + GA4)3. Execute tier-appropriate analysis4. Format output to match claude-seo conventions@@ -16,20 +16,22 @@ You are a Google SEO API data analyst. When delegated tasks during an SEO audit:## Tier-Based Workflow### Tier 0 (API Key Only)-- Run PSI + CrUX on homepage: `python3 scripts/pagespeed_check.py <url> --json`-- Run CrUX History for origin: `python3 scripts/crux_history.py <origin> --origin --json`+- Run PSI + CrUX on homepage: `claude-seo run pagespeed_check.py <url> --json`+- Run CrUX History for origin: `claude-seo run crux_history.py <origin> --origin --json`- Report CWV field data with traffic-light ratings### Tier 1 (+ Service Account)- All Tier 0 checks-- GSC top queries/pages (28 days): `python3 scripts/gsc_query.py --property <prop> --json`-- URL Inspection on homepage + key pages: `python3 scripts/gsc_inspect.py <url> --json`-- GSC sitemap status: `python3 scripts/gsc_query.py sitemaps --property <prop> --json`+- GSC top queries/pages (28 days): `claude-seo run gsc_query.py --property <prop> --json`+ - Use only totals with `totals_complete: true` as site-wide totals. Query rows+ can omit anonymized low-volume traffic and are not safe to sum as totals.+- URL Inspection on homepage + key pages: `claude-seo run gsc_inspect.py <url> --json`+- GSC sitemap status: `claude-seo run gsc_query.py sitemaps --property <prop> --json`### Tier 2 (Full)- All Tier 1 checks-- GA4 organic traffic (28 days): `python3 scripts/ga4_report.py --property <id> --json`-- Top organic landing pages: `python3 scripts/ga4_report.py --property <id> --report top-pages --json`+- GA4 organic traffic (28 days): `claude-seo run ga4_report.py --property <id> --json`+- Top organic landing pages: `claude-seo run ga4_report.py --property <id> --report top-pages --json`## Core Web Vitals Thresholds@@ -56,7 +58,7 @@ After completing data collection at any tier, offer to generate a PDF report.The report uses the enterprise template: white cover, navy accents, Times New Roman, charts at 85% width, Google logo on title page. No page-break-inside: avoid (causes white gaps).```bash-python3 scripts/google_report.py --type full --data data.json --domain DOMAIN --format pdf --json+claude-seo run google_report.py --type full --data data.json --domain DOMAIN --format pdf --json```Report types: `cwv-audit`, `gsc-performance`, `indexation`, `full`.Before presenting: verify `"review": {"status": "PASS"}` in the JSON output.@@ -72,5 +74,6 @@ If `output_dir` is provided by the audit orchestrator, write:- If credentials are missing, report which tier is available and what can still be checked- If CrUX returns 404, note insufficient Chrome traffic and fall back to PSI lab data-- If GSC returns 403, report the service account email and instruct on adding permissions+- If GSC returns 403, report that the configured service identity lacks access,+ redact any identifier, and instruct the user on adding permissions- Never fail silently -- always report what succeeded and what faileddiff --git a/agents/seo-local.md b/agents/seo-local.mdindex ed4c9c8..3b8a9bf 100644--- a/agents/seo-local.md+++ b/agents/seo-local.md@@ -79,7 +79,7 @@ Provide a structured report with:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.Map embeds, GBP widgets, and review carousels are commonly injected client-side. When auditing local pages on JS-heavy sites prefer `--mode always` so the audit reflects what users (and Google's crawler) actually see post-render.diff --git a/agents/seo-performance.md b/agents/seo-performance.mdindex 0f926e5..c30f996 100644--- a/agents/seo-performance.md+++ b/agents/seo-performance.md@@ -25,7 +25,7 @@ Google evaluates the **75th percentile** of page visits, 75% of visits must meet## When Analyzing Performance1. Use PageSpeed Insights API if available-2. Use `python3 scripts/render_page.py <URL> --mode auto --json` before HTML/source inspection so SPA content is visible when needed+2. Use `claude-seo run render_page.py <URL> --mode auto --json` before HTML/source inspection so SPA content is visible when needed3. Provide specific, actionable optimization recommendations4. Prioritize by expected impact@@ -67,10 +67,10 @@ Google evaluates the **75th percentile** of page visits, 75% of visits must meet```bash# PageSpeed Insights API (uses header-based API key handling)-python3 scripts/pagespeed_check.py URL --json+claude-seo run pagespeed_check.py URL --json# SPA-aware HTML/render inspection-python3 scripts/render_page.py URL --mode auto --json+claude-seo run render_page.py URL --mode auto --json# Lighthouse CLInpx lighthouse URL --output json@@ -80,8 +80,8 @@ npx lighthouse URL --output jsonIf Google API credentials are configured, prefer CrUX field data over Lighthouse lab data for CWV assessment:```bash-python3 scripts/pagespeed_check.py URL --json-python3 scripts/crux_history.py URL --json+claude-seo run pagespeed_check.py URL --json+claude-seo run crux_history.py URL --json```Field data (28-day Chrome user average) is more representative than lab data (single Lighthouse run). Use lab data as fallback when CrUX returns 404 (insufficient traffic).diff --git a/agents/seo-schema.md b/agents/seo-schema.mdindex d76efb3..c5909aa 100644--- a/agents/seo-schema.md+++ b/agents/seo-schema.md@@ -68,7 +68,9 @@ Provide:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes summary fields including `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate); use `--output` or import `render_page.render_page()` when full raw/rendered HTML is required. SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes summary fields including `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate); use `--output` or import `render_page.render_page()` when full raw/rendered HTML is required. SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.++Use the JSON response's `structured_data` summary for routine JSON-LD detection. It is extracted from the full HTML before the HTML fields are truncated, but emits only bounded validity, size, and type metadata. When full blocks are necessary for validation, pass `--json-ld-output <path>` and read the bounded UTF-8 JSON artifact. Never copy unbounded page markup into an agent prompt.## Persistence Contractdiff --git a/agents/seo-sitemap.md b/agents/seo-sitemap.mdindex 334a858..7f43d0f 100644--- a/agents/seo-sitemap.md+++ b/agents/seo-sitemap.md@@ -10,12 +10,14 @@ You are a Sitemap Architecture specialist.When working with sitemaps:-1. Validate XML format and URL status codes-2. Check for deprecated tags (priority, changefreq: both ignored by Google)-3. Verify lastmod accuracy (valid W3C Datetime; reflects last *significant* change, not boilerplate)-4. Compare crawled pages vs sitemap coverage-5. Enforce the per-file limit: ≤50,000 URLs AND ≤50MB uncompressed (whichever first); for `news:` sitemaps the cap is 1,000 URLs-6. Apply location page quality gates+1. Discover candidates with `claude-seo run sitemap_discovery.py <url> --json`.+ Use only validated `found` entries and retain declared failures as findings.+2. Validate XML format and URL status codes+3. Check for deprecated tags (priority, changefreq: both ignored by Google)+4. Verify lastmod accuracy (valid W3C Datetime; reflects last *significant* change, not boilerplate)+5. Compare crawled pages vs sitemap coverage+6. Enforce the per-file limit: ≤50,000 URLs AND ≤50MB uncompressed (whichever first); for `news:` sitemaps the cap is 1,000 URLs+7. Apply location page quality gates## Quality Gatesdiff --git a/agents/seo-sxo.md b/agents/seo-sxo.mdindex 376df12..e40e1db 100644--- a/agents/seo-sxo.md+++ b/agents/seo-sxo.md@@ -19,8 +19,8 @@ then comparing that against the target page.### 1. Fetch and Parse Target Page-- Fetch the target URL using `python3 scripts/render_page.py "<url>" --mode auto --json` (SPA-aware SSRF-protected renderer)-- Parse with `python3 scripts/parse_html.py --url "<url>"` to extract SEO elements+- Fetch the target URL using `claude-seo run render_page.py "<url>" --mode auto --json` (SPA-aware SSRF-protected renderer)+- Parse with `claude-seo run parse_html.py --url "<url>"` to extract SEO elements- Identify: page type, title, H1, meta description, headings, word count, schema, CTAs, media- If no keyword was provided, derive primary keyword from title + H1 overlap@@ -95,7 +95,7 @@ Before presenting results, verify:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes `raw_content` (pre-JS), `content` (post-JS), `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate). SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.Search experience scoring needs the *rendered* DOM because users see what JS produces. Prefer `--mode always` so above-the-fold analysis matches what the persona actually encounters.diff --git a/agents/seo-technical.md b/agents/seo-technical.mdindex 2da40df..d88fd8b 100644--- a/agents/seo-technical.md+++ b/agents/seo-technical.md@@ -9,7 +9,9 @@ tools: Read, Bash, Write, Glob, Grep # Write needed for report/data file outputYou are a Technical SEO specialist. When given a URL or set of URLs:1. Fetch the page(s) and analyze HTML source-2. Check robots.txt and sitemap availability+2. Check sitemap availability with `claude-seo run sitemap_discovery.py <URL> --json`.+ A robots.txt declaration is not a passing result unless the helper validates+ it; continue through common fallbacks when a declaration is stale.3. Analyze meta tags, canonical tags, and security headers4. Evaluate URL structure and redirect chains5. Assess mobile-friendliness from HTML/CSS analysis@@ -53,7 +55,7 @@ Provide a structured report with:## Fetching pages (v2.0.0)-Use `python3 scripts/render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes summary fields including `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate); use `--output` or import `render_page.render_page()` when full raw/rendered HTML is required. SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.+Use `claude-seo run render_page.py <URL> --mode auto --json` for page HTML. `auto` does a raw fetch and only spins up Playwright when an SPA shell is detected; use `--mode always` to force a render or `--mode never` to skip Playwright entirely. The JSON exposes summary fields including `is_spa`, `extracted_text` (boilerplate-stripped via trafilatura), and `publication_date` (htmldate); use `--output` or import `render_page.render_page()` when full raw/rendered HTML is required. SSRF and DNS-rebinding protection live in `scripts/url_safety.py`, never call `requests.get` directly on user-supplied URLs.## Persistence Contractdiff --git a/agents/seo-visual.md b/agents/seo-visual.mdindex a2d1ea2..f17ca31 100644--- a/agents/seo-visual.md+++ b/agents/seo-visual.md@@ -29,8 +29,8 @@ pip install playwright && playwright install chromiumUse the screenshot script (`scripts/capture_screenshot.py` in the plugin root) for browser automation:```bash-python3 scripts/capture_screenshot.py URL --all --output screenshots/-python3 scripts/render_page.py URL --mode auto --a11y-tree --json+claude-seo run capture_screenshot.py URL --all --output screenshots/+claude-seo run render_page.py URL --mode auto --a11y-tree --json```## Viewports to Testdiff --git a/bin/claude-seo b/bin/claude-seonew file mode 100755index 0000000..a31fe66--- /dev/null+++ b/bin/claude-seo@@ -0,0 +1,35 @@+#!/usr/bin/env bash+set -euo pipefail++# Stable entry point for bundled Python tools. The launcher uses only shell+# built-ins until a usable Python 3 interpreter has been identified.+launcher_dir="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"+runtime="${launcher_dir}/../scripts/runtime.py"++if [[ ! -f "${runtime}" ]]; then+ echo "Claude SEO runtime is missing. Reinstall Claude SEO." >&2+ exit 2+fi++# An override is an executable path, not a shell command. Keeping it as one+# array element prevents command injection and supports paths containing spaces.+if [[ -n "${CLAUDE_SEO_PYTHON:-}" ]]; then+ if "${CLAUDE_SEO_PYTHON}" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' >/dev/null 2>&1; then+ exec "${CLAUDE_SEO_PYTHON}" "${runtime}" "$@"+ fi+ echo "CLAUDE_SEO_PYTHON is not a usable Python 3.10+ executable." >&2+ exit 2+fi++if command -v py >/dev/null 2>&1 && py -3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' >/dev/null 2>&1; then+ exec py -3 "${runtime}" "$@"+fi+if command -v python3 >/dev/null 2>&1 && python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' >/dev/null 2>&1; then+ exec python3 "${runtime}" "$@"+fi+if command -v python >/dev/null 2>&1 && python -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' >/dev/null 2>&1; then+ exec python "${runtime}" "$@"+fi++echo "Claude SEO requires Python 3.10 or newer. Tried CLAUDE_SEO_PYTHON, py -3, python3, and python." >&2+exit 2diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 89b4a70..77a6e56 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -222,6 +222,26 @@ User Request (e.g., /seo page)## Extensions+### Managed Python runtime++Bundled tools are dispatched through `bin/claude-seo` and+`scripts/runtime.py`, never through a working-directory-relative Python command.+The launcher resolves Python 3.10 or newer, while the standard-library runtime+provides three operations: `run`, `setup`, and read-only `doctor`.++Plugin environments live under persistent `CLAUDE_PLUGIN_DATA`. Manual installs+keep the compatible `~/.claude/skills/seo/.venv` location. A state marker records+the runtime schema, requirements SHA-256, Python major and minor version, public+plugin version, and browser state. Requirements, runtime-schema, or Python ABI+changes require explicit setup; a version-only difference remains compatible and+is refreshed on the next setup. Environment replacement is staged and rolled+back if validation or marker publication fails.++`run` accepts only allowlisted script basenames or a contained extension script.+It forwards arguments without a shell, preserves child exit codes, forces UTF-8+child streams, and uses the same persistent Playwright browser directory created+by setup.+Extensions are opt-in add-ons that integrate external data sources via MCP servers. They live in `extensions/<name>/` and ship their own install / uninstall scripts.```diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 6621945..a86888d 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -6,6 +6,17 @@ All Claude SEO commands start with `/seo` followed by a subcommand.## Command List+### `/seo setup`++Explicitly create or refresh the isolated Python runtime and Playwright Chromium.+This is required once after a marketplace plugin install. Manual installers run+the same setup automatically. It never installs packages globally.++### `/seo doctor`++Check runtime, dependency, and Chromium readiness without changing the system.+Diagnostic output omits absolute paths and environment values.+### `/seo audit <url>`Full website SEO audit with parallel analysis.diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.mdindex 6909a1a..eec66e7 100644--- a/docs/INSTALLATION.md+++ b/docs/INSTALLATION.md@@ -18,8 +18,13 @@ The recommended path. Inside Claude Code:```/plugin marketplace add AgriciDaniel/claude-seo/plugin install claude-seo@agricidaniel-claude-seo+/seo setup```+Plugin installation does not run package managers. `/seo setup` is an explicit,+one-time provisioning step that writes the virtual environment and browser only+to Claude's persistent plugin data. Use `/seo doctor` for a read-only check.+### Manual Install (Unix, macOS, Linux)```bash@@ -60,28 +65,18 @@ cd claude-seo./install.sh```-3. **Install Python dependencies** (if not done automatically)--The installer creates a venv at `~/.claude/skills/seo/.venv/`. If that fails, install manually:--```bash-# Option A: Use the venv-~/.claude/skills/seo/.venv/bin/pip install -r ~/.claude/skills/seo/requirements.txt--# Option B: User-level install-pip install --user -r ~/.claude/skills/seo/requirements.txt-```--4. **Install Playwright Chromium** (optional)+3. **Verify the managed runtime**-install.sh attempts to install it automatically; failure is non-fatal; needed only for SPA rendering and screenshots. To install it manually:+The installer delegates dependency and Chromium provisioning to the same runtime+used by every skill. It creates `~/.claude/skills/seo/.venv/` and never falls+back to global or user package installation.```bash-pip install playwright-playwright install chromium+~/.claude/skills/seo/bin/claude-seo doctor```-Without it, visual analysis uses WebFetch as a fallback.+If core setup failed, rerun the inspected installer. If only Chromium failed,+the installer reports a degraded result and raw-fetch analysis remains available.## Installation Paths@@ -92,6 +87,8 @@ The installer copies files to:| Main skill | `~/.claude/skills/seo/` || Sub-skills | `~/.claude/skills/seo-*/` || Subagents | `~/.claude/agents/seo-*.md` |+| Runtime launcher | `~/.claude/skills/seo/bin/claude-seo` |+| Isolated Python | `~/.claude/skills/seo/.venv/` |## Verify Installation@@ -155,18 +152,19 @@ If the file doesn't exist, re-run the installer.### Python dependency errors-Install dependencies manually:+Run the managed setup again:```bash-pip install --user -r ~/.claude/skills/seo/requirements.txt+~/.claude/skills/seo/bin/claude-seo setup```### Playwright screenshot errors-Install Chromium browser:+Run the managed setup again and inspect the result:```bash-playwright install chromium+~/.claude/skills/seo/bin/claude-seo setup+~/.claude/skills/seo/bin/claude-seo doctor```### Permission errors on Unixdiff --git a/docs/MIGRATION-v1-to-v2.md b/docs/MIGRATION-v1-to-v2.mdindex c4746e6..017a02f 100644--- a/docs/MIGRATION-v1-to-v2.md+++ b/docs/MIGRATION-v1-to-v2.md@@ -19,9 +19,9 @@ Everything else is additive — new commands, new scripts, new referencefiles, new extensions. Existing audit reports will look slightly fullerbut use exactly the same overall structure.-This guide covers the v1.x → v2.0.0 jump only; the v2.1.0 through v2.2.3+This guide covers the v1.x → v2.0.0 jump only; the v2.1.0 through v2.2.4releases are documented in [../CHANGELOG.md](../CHANGELOG.md), and the-suite is now at 326 tests.+suite is now at 410 tests.## What's new in v2diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 37b29d7..33fea50 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -49,22 +49,20 @@ curl -fsSL https://raw.githubusercontent.com/AgriciDaniel/claude-seo/main/instal**Solution:**-As of v1.2.0, dependencies are installed in a venv. Try:+Dependencies belong in the managed runtime. For a plugin install, run:```bash-# Use the venv pip-~/.claude/skills/seo/.venv/bin/pip install -r ~/.claude/skills/seo/requirements.txt+/seo doctor+/seo setup```-If the venv doesn't exist, install with `--user`:+For a manual install, run:```bash-pip install --user -r ~/.claude/skills/seo/requirements.txt+~/.claude/skills/seo/bin/claude-seo doctor+~/.claude/skills/seo/bin/claude-seo setup```-Do not install individual packages; use the shipped requirements file:-```bash-pip install --user -r ~/.claude/skills/seo/requirements.txt-```+Do not install individual packages, use `pip --user`, or create a PATH shim.### requirements.txt Not Found@@ -95,8 +93,8 @@ curl -fsSL https://raw.githubusercontent.com/AgriciDaniel/claude-seo/main/requir**Solution (v1.2.0+):** The Windows installer now tries both `python` and `py -3`. If both fail:1. Install Python from [python.org](https://python.org) and check "Add to PATH"-2. Or use the Windows launcher: `py -3 -m pip install -r requirements.txt`-3. Use `python3 -m pip` instead of bare `pip`+2. Rerun `install.ps1`; it resolves `py -3`, `python3`, then `python`+3. Run `/seo doctor` after installation---@@ -104,15 +102,11 @@ curl -fsSL https://raw.githubusercontent.com/AgriciDaniel/claude-seo/main/requir**Symptom:** `playwright._impl._errors.Error: Executable doesn't exist`-**Solution:**-```bash-playwright install chromium-```--If that fails:+**Solution:** rerun managed setup so the browser is installed through the same+interpreter and persistent browser directory:```bash-pip install playwright-python3 -m playwright install chromium+/seo setup+/seo doctor```---@@ -179,7 +173,7 @@ cp /path/to/claude-seo/agents/*.md ~/.claude/agents/1. Ensure placeholders are replaced2. Verify @context is `https://schema.org`3. Check for deprecated/retired types: HowTo and SpecialAnnouncement, plus the June 2025 retirements (ClaimReview, VehicleListing, EstimatedSalary, LearningVideo, and the CourseInfo carousel)-4. FAQPage rich results were retired for all sites on 2026-05-07: FAQPage no longer yields rich results, but the hook should NOT block it (still a valid AI/entity signal)+4. FAQPage rich results were retired for all sites on 2026-05-07. The hook does not block it because it remains a valid Schema.org type, but no AI or ranking benefit is confirmed.5. Validate at [Google's Rich Results Test](https://search.google.com/test/rich-results)---diff --git a/docs/WORKFLOW-public-private.md b/docs/WORKFLOW-public-private.mdindex dbba6d8..0b8b163 100644--- a/docs/WORKFLOW-public-private.md+++ b/docs/WORKFLOW-public-private.md@@ -150,13 +150,14 @@ upgrade.| Letting `aimh/main` lag behind `origin/main` | Always push to `aimh` first, then `origin` on release || Confusing `aimh/v2` with `origin/v2` | `origin` should never have an unreleased `v2` branch |-## State for the v2.2.3 public release (2026-07-20)+## State for the v2.2.4 public release (2026-07-20)-- v2.2.3 is the **current public release**. Latest tag on both remotes: `v2.2.3`.+- v2.2.4 is the **current public release**. Latest public tag: `v2.2.4`.- `aimh/main` = shared canonical (public-first README, private marketplace name).- `origin/main` = `aimh/main` + the public-branding commit (public marketplace name).-- `v2.2.3` tag points at each repo's own HEAD: `origin`'s tag includes the- branding commit, `aimh`'s does not (see "Public-branding divergence" above).+- The public `v2.2.4` tag points at the reviewed maintenance release on `origin/main`.+- Private synchronization for v2.2.4 requires a separate review because this release preserves+ public branding and intentionally excludes private-only content.- `aimh/v2` tracks the shared canonical for ongoing v2.x work.## Email-privacy caveat (one-time)diff --git a/extensions/ahrefs/skills/seo-ahrefs/SKILL.md b/extensions/ahrefs/skills/seo-ahrefs/SKILL.mdindex eeb4e4f..82de4ac 100644--- a/extensions/ahrefs/skills/seo-ahrefs/SKILL.md+++ b/extensions/ahrefs/skills/seo-ahrefs/SKILL.md@@ -2,7 +2,7 @@name: seo-ahrefsdescription: Ahrefs API analyst (extension). Reads referring domains, backlinks, organic keywords, and content explorer data via the tested @ahrefs/[email protected] server. Pairs with seo-backlinks for multi-source confidence weighting.metadata:- version: "2.2.3"+ version: "2.2.4"compatibility: "Tested with @ahrefs/[email protected] (installed by extensions/ahrefs/install.sh)."---@@ -46,7 +46,7 @@ provide the install command above.Ahrefs API usage is metered per unit. Before running a batch (>= 50 URLs):-1. Estimate cost with `python3 scripts/dataforseo_costs.py` (the cost-tracker module is generic and supports Ahrefs unit accounting).+1. Estimate cost with `claude-seo run dataforseo_costs.py` (the cost-tracker module is generic and supports Ahrefs unit accounting).2. Surface the estimate to the orchestrator.3. Log actual cost after each call.diff --git a/extensions/banana/README.md b/extensions/banana/README.mdindex e13823c..c4b377c 100644--- a/extensions/banana/README.md+++ b/extensions/banana/README.md@@ -39,7 +39,7 @@ The installer will:CSV batch planning helper:```bash-python3 extensions/banana/scripts/batch.py --csv requests.csv --model "$NANOBANANA_MODEL"+claude-seo run --extension banana batch.py --csv requests.csv --model "$NANOBANANA_MODEL"```## Use Case Defaultsdiff --git a/extensions/banana/docs/BANANA-SETUP.md b/extensions/banana/docs/BANANA-SETUP.mdindex bafd82f..2861800 100644--- a/extensions/banana/docs/BANANA-SETUP.md+++ b/extensions/banana/docs/BANANA-SETUP.md@@ -31,14 +31,14 @@ add to `~/.claude/settings.json`:Scripted setup helper:```bash-python3 extensions/banana/scripts/setup_mcp.py --key YOUR_KEY+claude-seo run --extension banana setup_mcp.py --key YOUR_KEY```## Verifying InstallationRun the validation script:```bash-python3 ~/.claude/skills/seo-image-gen/scripts/validate_setup.py+claude-seo run --extension banana validate_setup.py```Or check manually:diff --git a/extensions/banana/install.sh b/extensions/banana/install.shindex 3865aaa..a36bd8e 100755--- a/extensions/banana/install.sh+++ b/extensions/banana/install.sh@@ -154,6 +154,18 @@ PYcp "${SOURCE_DIR}/scripts/"*.py "${SKILL_DIR}/scripts/"cp "${SOURCE_DIR}/references/"*.md "${SKILL_DIR}/references/"+ # Rewrite only files copied by this extension install. Manual installs do+ # not receive plugin bin/ PATH injection.+ for installed_doc in "${SKILL_DIR}/SKILL.md" "${SKILL_DIR}/references/"*.md "${AGENT_DIR}/seo-image-gen.md"; do+ [ -f "${installed_doc}" ] || continue+ temp_doc="${installed_doc}.claude-seo-tmp"+ sed -e 's#claude-seo run#"$HOME/.claude/skills/seo/bin/claude-seo" run#g' \+ -e 's#claude-seo setup#"$HOME/.claude/skills/seo/bin/claude-seo" setup#g' \+ -e 's#claude-seo doctor#"$HOME/.claude/skills/seo/bin/claude-seo" doctor#g' \+ "${installed_doc}" > "${temp_doc}"+ mv "${temp_doc}" "${installed_doc}"+ done+# Pre-warm npm package without starting the MCP server binary.echo "→ Pre-downloading nanobanana-mcp..."npx --yes --package=@ycse/[email protected] -- node -e "" >/dev/null 2>&1 || truediff --git a/extensions/banana/references/seo-image-presets.md b/extensions/banana/references/seo-image-presets.mdindex 44fbd66..ce4880c 100644--- a/extensions/banana/references/seo-image-presets.md+++ b/extensions/banana/references/seo-image-presets.md@@ -123,7 +123,7 @@ preset format (see `references/presets.md` for schema details).Users can create their own presets:```bash-python3 ~/.claude/skills/seo-image-gen/scripts/presets.py create my-brand+claude-seo run --extension banana presets.py create my-brand```This creates `~/.banana/presets/my-brand.json` with the full schema.diff --git a/extensions/banana/skills/seo-image-gen/SKILL.md b/extensions/banana/skills/seo-image-gen/SKILL.mdindex dcc8de5..3880df3 100644--- a/extensions/banana/skills/seo-image-gen/SKILL.md+++ b/extensions/banana/skills/seo-image-gen/SKILL.md@@ -7,7 +7,7 @@ license: MITcompatibility: "Requires nanobanana MCP server"metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -72,8 +72,8 @@ For every generation request:2. **Apply SEO defaults** from the use cases table above3. **Set aspect ratio** via `set_aspect_ratio` MCP tool4. **Construct Reasoning Brief** using the banana Creative Director pipeline:- - Set `BANANA_EXTENSION_ROOT` to `extensions/banana` in-repo or the installed skill dir after extension install- - Load `$BANANA_EXTENSION_ROOT/references/prompt-engineering.md` for the 6-component system+ - Use `${CLAUDE_SKILL_DIR}` as the installed skill root+ - Load `${CLAUDE_SKILL_DIR}/references/prompt-engineering.md` for the 6-component system- Apply domain mode emphasis (Subject 30%, Style 25%, Context 15%, etc.)- Be SPECIFIC and VISCERAL: describe what the camera sees5. **Generate** via `gemini_generate_image` MCP tool@@ -83,9 +83,9 @@ For every generation request:If the user mentions a brand or has SEO presets configured:```bash-python3 "$BANANA_EXTENSION_ROOT/scripts/presets.py" list+claude-seo run --extension banana presets.py list```-Load matching preset and apply as defaults. Also check `$BANANA_EXTENSION_ROOT/references/seo-image-presets.md`+Load matching preset and apply as defaults. Also check `${CLAUDE_SKILL_DIR}/references/seo-image-presets.md`for SEO-specific preset templates.## Post-Generation SEO Checklist@@ -121,7 +121,7 @@ After every successful generation, guide the user on:Image generation costs money. Be transparent:- Show estimated cost before generating (especially for batch)-- Log every generation: `python3 "$BANANA_EXTENSION_ROOT/scripts/cost_tracker.py" log --model MODEL --resolution RES --prompt "brief"`+- Log every generation: `claude-seo run --extension banana cost_tracker.py log --model MODEL --resolution RES --prompt "brief"`- Run `cost_tracker.py summary` if user asks about usagePricing is not hard-coded. Check current Google pricing at@@ -141,12 +141,12 @@ https://ai.google.dev/gemini-api/docs/pricing, store dated values in| Error | Resolution ||-------|-----------|-| MCP not configured | Run `./extensions/banana/install.sh` or `python3 extensions/banana/scripts/setup_mcp.py --key YOUR_KEY` |+| MCP not configured | Run `./extensions/banana/install.sh` or `claude-seo run --extension banana setup_mcp.py --key YOUR_KEY` || API key invalid | New key at https://aistudio.google.com/apikey || Rate limited (429) | Wait 60s, retry. Check current free-tier limits before batch operations || `IMAGE_SAFETY` | Rephrase prompt - see `references/prompt-engineering.md` Safety section |-| MCP unavailable | Fall back: `python3 "$BANANA_EXTENSION_ROOT/scripts/generate.py" --prompt "..." --aspect-ratio "16:9" --model "$NANOBANANA_MODEL"` |-| CSV batch input | Plan first: `python3 "$BANANA_EXTENSION_ROOT/scripts/batch.py" --csv requests.csv --model "$NANOBANANA_MODEL"` |+| MCP unavailable | Fall back: `claude-seo run --extension banana generate.py --prompt "..." --aspect-ratio "16:9" --model "$NANOBANANA_MODEL"` |+| CSV batch input | Plan first: `claude-seo run --extension banana batch.py --csv requests.csv --model "$NANOBANANA_MODEL"` || Extension not installed | Show install instructions: `./extensions/banana/install.sh` |## Cross-Skill Integration@@ -158,13 +158,13 @@ https://ai.google.dev/gemini-api/docs/pricing, store dated values in## Reference DocumentationLoad on-demand. Do NOT load all at startup:-- `$BANANA_EXTENSION_ROOT/references/prompt-engineering.md`:6-component system, domain modes, templates-- `$BANANA_EXTENSION_ROOT/references/gemini-models.md`:Model specs, rate limits, capabilities-- `$BANANA_EXTENSION_ROOT/references/mcp-tools.md`:MCP tool parameters and responses-- `$BANANA_EXTENSION_ROOT/references/post-processing.md`:ImageMagick/FFmpeg pipeline recipes-- `$BANANA_EXTENSION_ROOT/references/cost-tracking.md`:Pricing, usage tracking-- `$BANANA_EXTENSION_ROOT/references/presets.md`:Brand preset management-- `$BANANA_EXTENSION_ROOT/references/seo-image-presets.md`:SEO-specific preset templates+- `${CLAUDE_SKILL_DIR}/references/prompt-engineering.md`:6-component system, domain modes, templates+- `${CLAUDE_SKILL_DIR}/references/gemini-models.md`:Model specs, rate limits, capabilities+- `${CLAUDE_SKILL_DIR}/references/mcp-tools.md`:MCP tool parameters and responses+- `${CLAUDE_SKILL_DIR}/references/post-processing.md`:ImageMagick/FFmpeg pipeline recipes+- `${CLAUDE_SKILL_DIR}/references/cost-tracking.md`:Pricing, usage tracking+- `${CLAUDE_SKILL_DIR}/references/presets.md`:Brand preset management+- `${CLAUDE_SKILL_DIR}/references/seo-image-presets.md`:SEO-specific preset templates## Response Formatdiff --git a/extensions/bing-webmaster/install.sh b/extensions/bing-webmaster/install.shindex b00a53c..ed6b936 100755--- a/extensions/bing-webmaster/install.sh+++ b/extensions/bing-webmaster/install.sh@@ -53,7 +53,7 @@ PYechoecho "Done. Verify your IndexNow key is published:"- echo " python scripts/indexnow_submit.py --host example.com \\"+ echo " claude-seo run indexnow_submit.py --host example.com \\"echo " --key \$INDEXNOW_KEY --key-location \$INDEXNOW_KEY_LOCATION --verify-only"}main "$@"diff --git a/extensions/bing-webmaster/skills/seo-bing/SKILL.md b/extensions/bing-webmaster/skills/seo-bing/SKILL.mdindex 8085939..abbb7d8 100644--- a/extensions/bing-webmaster/skills/seo-bing/SKILL.md+++ b/extensions/bing-webmaster/skills/seo-bing/SKILL.md@@ -2,7 +2,7 @@name: seo-bingdescription: Bing Webmaster Tools + IndexNow extension. Microsoft Copilot citations are fed by the Bing index; this skill makes Bing visibility, link data, and IndexNow URL submission first-class.metadata:- version: "2.2.3"+ version: "2.2.4"compatibility: "Requires BING_WEBMASTER_API_KEY and (optionally) INDEXNOW_KEY in ~/.claude/settings.json env. Run extensions/bing-webmaster/install.sh to configure."---@@ -24,11 +24,11 @@ specifically for **Amazon/Bing/Naver/Seznam.cz/Yandex/Yep indexing** and| Command | Underlying script ||---|---|-| `/seo bing links <url>` | `python3 scripts/bing_webmaster.py links <url>` |-| `/seo bing compare <urlA> <urlB>` | `python3 scripts/bing_webmaster.py compare <urlA> <urlB>` |-| `/seo bing submit <url>` (single URL) | `python3 scripts/indexnow_submit.py --host ... --urls <url>` |-| `/seo bing submit-batch <file>` | `python3 scripts/indexnow_submit.py --host ... --urls-file <file>` |-| `/seo bing verify-indexnow` | `python3 scripts/indexnow_submit.py --host ... --verify-only` |+| `/seo bing links <url>` | `claude-seo run bing_webmaster.py links <url>` |+| `/seo bing compare <urlA> <urlB>` | `claude-seo run bing_webmaster.py compare <urlA> <urlB>`; both properties must be registered to the API account |+| `/seo bing submit <url>` (single URL) | `claude-seo run indexnow_submit.py --host ... --urls <url>` |+| `/seo bing submit-batch <file>` | `claude-seo run indexnow_submit.py --host ... --urls-file <file>` |+| `/seo bing verify-indexnow` | `claude-seo run indexnow_submit.py --host ... --verify-only` |## When this skill applies@@ -36,8 +36,8 @@ specifically for **Amazon/Bing/Naver/Seznam.cz/Yandex/Yep indexing** andcitation eligibility (Bing index ingestion).- The user wants to nudge Amazon/Bing/Naver/Seznam.cz/Yandex/Yep indexing for freshURLs.-- The user is doing competitor backlink analysis and wants Bing's- unique link data (Bing tracks links Google's API doesn't surface).+- The user manages both properties and wants to compare their Bing link data.+ For an arbitrary competitor, route to DataForSEO, Moz, or Common Crawl.## Cross-skill delegationdiff --git a/extensions/dataforseo/agents/seo-dataforseo.md b/extensions/dataforseo/agents/seo-dataforseo.mdindex b35ebec..700cd85 100644--- a/extensions/dataforseo/agents/seo-dataforseo.md+++ b/extensions/dataforseo/agents/seo-dataforseo.md@@ -1,7 +1,7 @@---name: seo-dataforseodescription: DataForSEO data analyst. Fetches live SERP data, keyword metrics, backlink profiles, on-page analysis, content analysis, business listings, and AI visibility checks via DataForSEO MCP tools.-tools: Read, Bash, Write, Glob, Grep+tools: Read, Write, Glob, Grep, mcp__dataforseo__*---You are a DataForSEO data analyst. When delegated tasks during an SEO audit or analysis:@@ -10,6 +10,8 @@ You are a DataForSEO data analyst. When delegated tasks during an SEO audit or a2. Use the most efficient tool combination for the requested data3. Apply default parameters: location_code=2840 (US), language_code=en unless specified4. Format output to match claude-seo conventions (tables, priority levels, scores)+5. If the MCP tools are unavailable, fail closed. Never inspect credential or+ configuration stores and never bypass MCP with curl, raw HTTP, or another client.## Efficient Tool Usagediff --git a/extensions/dataforseo/docs/DATAFORSEO-SETUP.md b/extensions/dataforseo/docs/DATAFORSEO-SETUP.mdindex 1f6bc17..64986a8 100644--- a/extensions/dataforseo/docs/DATAFORSEO-SETUP.md+++ b/extensions/dataforseo/docs/DATAFORSEO-SETUP.md@@ -51,10 +51,10 @@ If the installer's auto-configuration fails, add this to `~/.claude/settings.jso"command": "npx","args": ["-y", "dataforseo-mcp-server"],"env": {- "DATAFORSEO_USERNAME": "[email protected]",+ "DATAFORSEO_USERNAME": "<account-username>","DATAFORSEO_PASSWORD": "your-api-password","ENABLED_MODULES": "SERP,KEYWORDS_DATA,ONPAGE,DATAFORSEO_LABS,BACKLINKS,DOMAIN_ANALYTICS,BUSINESS_DATA,CONTENT_ANALYSIS,AI_OPTIMIZATION",- "FIELD_CONFIG_PATH": "/home/youruser/.claude/skills/seo/dataforseo-field-config.json"+ "FIELD_CONFIG_PATH": "/path/to/dataforseo-field-config.json"}}}diff --git a/extensions/dataforseo/skills/seo-dataforseo/SKILL.md b/extensions/dataforseo/skills/seo-dataforseo/SKILL.mdindex ff71146..2504edb 100644--- a/extensions/dataforseo/skills/seo-dataforseo/SKILL.md+++ b/extensions/dataforseo/skills/seo-dataforseo/SKILL.md@@ -13,7 +13,7 @@ license: MITcompatibility: "Requires DataForSEO MCP server"metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -48,7 +48,7 @@ DataForSEO charges per API call. Be efficient:**Before every DataForSEO MCP call**, run cost estimation:```-python3 scripts/dataforseo_costs.py check <endpoint> [--count N]+claude-seo run dataforseo_costs.py check <endpoint> [--count N]```- If `"status": "approved"` → proceed with the API call@@ -57,7 +57,7 @@ python3 scripts/dataforseo_costs.py check <endpoint> [--count N]**After each API call completes**, log the cost:```-python3 scripts/dataforseo_costs.py log <endpoint> <actual_cost>+claude-seo run dataforseo_costs.py log <endpoint> <actual_cost>```**User commands for cost management:**diff --git a/extensions/dataforseo/skills/seo-dataforseo/references/cost-tiers.md b/extensions/dataforseo/skills/seo-dataforseo/references/cost-tiers.mdindex 0c8364c..1734a28 100644--- a/extensions/dataforseo/skills/seo-dataforseo/references/cost-tiers.md+++ b/extensions/dataforseo/skills/seo-dataforseo/references/cost-tiers.md@@ -31,7 +31,7 @@| **Aggressive** | $50.00 | $2.00 | threshold | Agency bulk work || **Unlimited** | $999.00 | -- | none | Trusted pipelines |-Configure with: `python3 scripts/dataforseo_costs.py config --mode threshold --threshold 0.50 --daily-limit 10.00`+Configure with: `claude-seo run dataforseo_costs.py config --mode threshold --threshold 0.50 --daily-limit 10.00`## Cost Reduction Tips@@ -44,11 +44,11 @@ Configure with: `python3 scripts/dataforseo_costs.py config --mode threshold --t## Approval FlowBefore any DataForSEO MCP call:-1. Run `python3 scripts/dataforseo_costs.py check <endpoint> [--count N]`+1. Run `claude-seo run dataforseo_costs.py check <endpoint> [--count N]`2. If `status: "approved"` → proceed3. If `status: "needs_approval"` → show cost to user, ask to confirm4. If `status: "blocked"` → inform user daily limit would be exceeded-5. After call completes, log: `python3 scripts/dataforseo_costs.py log <endpoint> <cost>`+5. After call completes, log: `claude-seo run dataforseo_costs.py log <endpoint> <cost>`## Warn Endpointsdiff --git a/extensions/firecrawl/skills/seo-firecrawl/SKILL.md b/extensions/firecrawl/skills/seo-firecrawl/SKILL.mdindex 93382b3..28edcbd 100644--- a/extensions/firecrawl/skills/seo-firecrawl/SKILL.md+++ b/extensions/firecrawl/skills/seo-firecrawl/SKILL.md@@ -11,7 +11,7 @@ license: MITcompatibility: "Requires Firecrawl MCP server"metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/extensions/profound/skills/seo-profound/SKILL.md b/extensions/profound/skills/seo-profound/SKILL.mdindex c316e37..e96f5c1 100644--- a/extensions/profound/skills/seo-profound/SKILL.md+++ b/extensions/profound/skills/seo-profound/SKILL.md@@ -2,7 +2,7 @@name: seo-profounddescription: Profound LLM citation tracker (extension). Time-series brand citation rates across ChatGPT, Perplexity, and other LLMs. Pairs with seo-seranking for triangulated AI visibility coverage.metadata:- version: "2.2.3"+ version: "2.2.4"compatibility: "Requires a Profound API key (set PROFOUND_API_KEY by running extensions/profound/install.sh)."---diff --git a/extensions/seranking/skills/seo-seranking/SKILL.md b/extensions/seranking/skills/seo-seranking/SKILL.mdindex f63dba9..a0536be 100644--- a/extensions/seranking/skills/seo-seranking/SKILL.md+++ b/extensions/seranking/skills/seo-seranking/SKILL.md@@ -2,7 +2,7 @@name: seo-serankingdescription: SE Ranking AI visibility analyst (extension). Tracks AI Share-of-Voice across ChatGPT, Gemini, Perplexity, AI Overviews, and AI Mode in a single query.metadata:- version: "2.2.3"+ version: "2.2.4"compatibility: "Requires an SE Ranking API key (set SERANKING_API_KEY by running extensions/seranking/install.sh)."---diff --git a/extensions/unlighthouse/skills/seo-unlighthouse/SKILL.md b/extensions/unlighthouse/skills/seo-unlighthouse/SKILL.mdindex e449da6..320e2ec 100644--- a/extensions/unlighthouse/skills/seo-unlighthouse/SKILL.md+++ b/extensions/unlighthouse/skills/seo-unlighthouse/SKILL.md@@ -2,7 +2,7 @@name: seo-unlighthousedescription: Multi-page Lighthouse audit via the MIT-licensed Unlighthouse CLI. Free-tier alternative to running PageSpeed against every URL on a site, no API quota burn, runs locally.metadata:- version: "2.2.3"+ version: "2.2.4"compatibility: "Requires Node 18+ and the unlighthouse npm package. Run extensions/unlighthouse/install.sh to pre-warm."---diff --git a/hooks/validate-schema.py b/hooks/validate-schema.pyindex 1746789..aa769fb 100755--- a/hooks/validate-schema.py+++ b/hooks/validate-schema.py@@ -31,9 +31,9 @@ checks if the file contains schema markup before validating."""import json+import osimport reimport sys-import osfrom typing import List@@ -112,8 +112,8 @@ def _validate_schema_object(obj: dict, block_num: int) -> List[str]:# Check for restricted types used incorrectly.# FAQPage is intentionally NOT flagged: Google retired FAQ rich results for- # all sites (May 7, 2026), but the markup still aids AI Mode / AI Overviews- # entity resolution, so it is valid to ship. See skills/seo-schema/SKILL.md.+ # all sites (May 7, 2026), but FAQPage remains a valid Schema.org type.+ # This project makes no claim of a confirmed AI or ranking benefit.restricted: dict = {}if schema_type in restricted:errors.append(f"{prefix}: @type '{schema_type}' is {restricted[schema_type]}; verify site qualifies")diff --git a/install.ps1 b/install.ps1index 2c5ad14..4756950 100644--- a/install.ps1+++ b/install.ps1@@ -72,7 +72,7 @@ function Test-PythonCandidate {return $null}- $probeCode = 'import sys; print(sys.executable); print(sys.version.split()[0])'+ $probeCode = 'import sys; print(sys.executable); print(sys.version.split()[0]); raise SystemExit(0 if sys.version_info >= (3, 10) else 1)'$probe = Invoke-External -Exe $Exe -Args @($Args + @('-c', $probeCode)) -Quiet$probeText = ($probe.Output -join "`n")@@ -118,7 +118,7 @@ $RepoUrl = "https://github.com/AgriciDaniel/claude-seo"# This default MUST be bumped on every release. CI guard# (tests/test_manifest_consistency.py) enforces this matches plugin.json.# Override: $env:CLAUDE_SEO_TAG = 'main'; .\install.ps1-$RepoTag = if ($env:CLAUDE_SEO_TAG) { $env:CLAUDE_SEO_TAG } else { 'v2.2.3' }+$RepoTag = if ($env:CLAUDE_SEO_TAG) { $env:CLAUDE_SEO_TAG } else { 'v2.2.4' }# Create directoriesNew-Item -ItemType Directory -Force -Path $SkillDir | Out-Null@@ -188,6 +188,14 @@ try {Copy-Item -Recurse -Force "$ScriptsPath\*" $SkillScripts}+ # Copy the stable launcher used by skill and agent instructions.+ $BinPath = Join-Path $TempDir 'bin'+ $SkillBin = Join-Path $SkillDir 'bin'+ if (Test-Path (Join-Path $BinPath 'claude-seo')) {+ New-Item -ItemType Directory -Force -Path $SkillBin | Out-Null+ Copy-Item -Force (Join-Path $BinPath 'claude-seo') (Join-Path $SkillBin 'claude-seo')+ }+# Copy hooksWrite-Host " Note: hook enforcement requires plugin install; manual hook copy is best-effort." -ForegroundColor Yellow$HooksPath = "$TempDir\hooks"@@ -241,32 +249,74 @@ try {if (Test-Path $reqFile) {Copy-Item -Force $reqFile $installedReqFile}+ $pluginManifest = Join-Path $TempDir '.claude-plugin\plugin.json'+ if (Test-Path $pluginManifest) {+ Copy-Item -Force $pluginManifest (Join-Path $SkillDir 'runtime-plugin.json')+ }- # Install Python dependencies- Write-Host "=> Installing Python dependencies..." -ForegroundColor Yellow- if (Test-Path $reqFile) {- try {- $pip = Invoke-External -Exe $python.Exe -Args @($python.Args + @('-m','pip','install','-q','-r',$reqFile)) -Quiet- if ($pip.ExitCode -ne 0) {- throw ($pip.Output -join "`n")+ # Manual installs do not receive plugin bin/ PATH injection. Rewrite only+ # the canonical runtime token in installed Markdown. Claude Code's Bash tool+ # expands $HOME on Windows as well as Unix.+ $manualRunner = '"$HOME/.claude/skills/seo/bin/claude-seo" run'+ $installedDocs = @()+ Get-ChildItem -Path $SkillsPath -Directory | ForEach-Object {+ $sourceRoot = $_.FullName+ $targetRoot = "$env:USERPROFILE\.claude\skills\$($_.Name)"+ $installedDocs += Get-ChildItem -Path $sourceRoot -Recurse -File -Filter '*.md' | ForEach-Object {+ $relative = $_.FullName.Substring($sourceRoot.Length).TrimStart('\','/')+ Get-Item (Join-Path $targetRoot $relative) -ErrorAction SilentlyContinue+ }+ }+ Get-ChildItem -Path $ExtensionsPath -Directory -ErrorAction SilentlyContinue | ForEach-Object {+ $extName = $_.Name+ $extSkills = Join-Path $_.FullName 'skills'+ Get-ChildItem -Path $extSkills -Directory -ErrorAction SilentlyContinue | ForEach-Object {+ $sourceRoot = $_.FullName+ $targetRoot = "$env:USERPROFILE\.claude\skills\$($_.Name)"+ $installedDocs += Get-ChildItem -Path $sourceRoot -Recurse -File -Filter '*.md' | ForEach-Object {+ $relative = $_.FullName.Substring($sourceRoot.Length).TrimStart('\','/')+ Get-Item (Join-Path $targetRoot $relative) -ErrorAction SilentlyContinue+ }+ }+ $extRefs = Join-Path $_.FullName 'references'+ if (Test-Path $extRefs) {+ $targetRefs = Join-Path $SkillDir "extensions\$extName\references"+ $installedDocs += Get-ChildItem -Path $extRefs -Recurse -File -Filter '*.md' | ForEach-Object {+ $relative = $_.FullName.Substring($extRefs.Length).TrimStart('\','/')+ Get-Item (Join-Path $targetRefs $relative) -ErrorAction SilentlyContinue}- } catch {- Write-Host " [!] Could not auto-install Python packages." -ForegroundColor Yellow- Write-Host " Try: $($python.Exe) $($python.Args -join ' ') -m pip install -r `"$installedReqFile`"" -ForegroundColor Yellow}- } else {- Write-Host " [!] No requirements.txt found; skipping Python dependency install." -ForegroundColor Yellow}-- # Optional: Install Playwright browsers- Write-Host "=> Installing Playwright browsers (optional, for visual analysis)..." -ForegroundColor Yellow- try {- $pw = Invoke-External -Exe $python.Exe -Args @($python.Args + @('-m','playwright','install','chromium')) -Quiet- if ($pw.ExitCode -ne 0) {- throw ($pw.Output -join "`n")+ $agentSources = @()+ $agentSources += Get-ChildItem -Path $AgentsPath -File -Filter '*.md' -ErrorAction SilentlyContinue+ $agentSources += Get-ChildItem -Path $ExtensionsPath -Recurse -File -Filter '*.md' -ErrorAction SilentlyContinue |+ Where-Object { $_.Directory.Name -eq 'agents' }+ $installedDocs += $agentSources | ForEach-Object {+ Get-Item (Join-Path $AgentDir $_.Name) -ErrorAction SilentlyContinue+ }+ $utf8NoBom = New-Object System.Text.UTF8Encoding($false)+ $installedDocs | ForEach-Object {+ $text = [System.IO.File]::ReadAllText($_.FullName)+ $manualSetup = '"$HOME/.claude/skills/seo/bin/claude-seo" setup'+ $manualDoctor = '"$HOME/.claude/skills/seo/bin/claude-seo" doctor'+ $updated = $text.Replace('claude-seo run', $manualRunner)+ $updated = $updated.Replace('claude-seo setup', $manualSetup)+ $updated = $updated.Replace('claude-seo doctor', $manualDoctor)+ if ($updated -ne $text) {+ [System.IO.File]::WriteAllText($_.FullName, $updated, $utf8NoBom)}- } catch {- Write-Host " [!] Playwright install failed. Visual analysis will use WebFetch fallback." -ForegroundColor Yellow+ }++ # Use the same standard-library runtime on Windows. It creates an isolated+ # .venv with Scripts\python.exe and installs Chromium through that interpreter.+ Write-Host "=> Creating isolated Python runtime..." -ForegroundColor Yellow+ $runtimeScript = Join-Path $SkillDir 'scripts\runtime.py'+ $runtime = Invoke-External -Exe $python.Exe -Args @($python.Args + @($runtimeScript,'setup'))+ if ($runtime.ExitCode -ne 0 -and $runtime.ExitCode -ne 10) {+ throw "Core Python runtime setup failed. Installation is incomplete."+ }+ if ($runtime.ExitCode -eq 10) {+ Write-Host " [!] Core runtime installed, but Chromium setup is incomplete." -ForegroundColor Yellow}} catch {Write-Host ""diff --git a/install.sh b/install.shindex 84ae72b..151fdfc 100755--- a/install.sh+++ b/install.sh@@ -12,7 +12,7 @@ main() {# This default MUST be bumped on every release. CI guard# (tests/test_manifest_consistency.py) enforces this matches plugin.json.# Override: CLAUDE_SEO_TAG=main bash install.sh- REPO_TAG="${CLAUDE_SEO_TAG:-v2.2.3}"+ REPO_TAG="${CLAUDE_SEO_TAG:-v2.2.4}"echo "════════════════════════════════════════"echo "║ Claude SEO - Installer ║"@@ -20,26 +20,18 @@ main() {echo "════════════════════════════════════════"echo ""- # Check prerequisites- command -v python3 >/dev/null 2>&1 || { echo "✗ Python 3 is required but not installed."; exit 1; }+ # Check prerequisites. The runtime launcher performs cross-platform Python+ # resolution and validates the minimum supported version.command -v git >/dev/null 2>&1 || { echo "✗ Git is required but not installed."; exit 1; }- # Check Python version (3.10+ required)- PYTHON_VERSION=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')- PYTHON_OK=$(python3 -c 'import sys; print(1 if sys.version_info >= (3, 10) else 0)')- if [ "${PYTHON_OK}" = "0" ]; then- echo "✗ Python 3.10+ is required but ${PYTHON_VERSION} was found."- exit 1- fi- echo "✓ Python ${PYTHON_VERSION} detected"-# Create directoriesmkdir -p "${SKILL_DIR}"mkdir -p "${AGENT_DIR}"# Clone or updateTEMP_DIR=$(mktemp -d)- trap "rm -rf ${TEMP_DIR}" EXIT+ cleanup() { rm -rf -- "${TEMP_DIR}"; }+ trap cleanup EXITecho "↓ Downloading Claude SEO (${REPO_TAG})..."git clone --depth 1 --branch "${REPO_TAG}" "${REPO_URL}" "${TEMP_DIR}/claude-seo" 2>/dev/null@@ -80,6 +72,14 @@ main() {cp -r "${TEMP_DIR}/claude-seo/scripts/"* "${SKILL_DIR}/scripts/"fi+ # Copy the stable runtime launcher. Manual installs use its explicit path;+ # plugin installs expose the repository bin/ directory automatically.+ if [ -f "${TEMP_DIR}/claude-seo/bin/claude-seo" ]; then+ mkdir -p "${SKILL_DIR}/bin"+ cp "${TEMP_DIR}/claude-seo/bin/claude-seo" "${SKILL_DIR}/bin/claude-seo"+ chmod +x "${SKILL_DIR}/bin/claude-seo"+ fi+# Copy hooksif [ -d "${TEMP_DIR}/claude-seo/hooks" ]; thenmkdir -p "${SKILL_DIR}/hooks"@@ -125,27 +125,62 @@ main() {# Copy requirements.txt to skill dir so users can retry latercp "${TEMP_DIR}/claude-seo/requirements.txt" "${SKILL_DIR}/requirements.txt" 2>/dev/null || true-- # Install Python dependencies (venv preferred, --user fallback)- echo "→ Installing Python dependencies..."- VENV_DIR="${SKILL_DIR}/.venv"- if python3 -m venv "${VENV_DIR}" 2>/dev/null; then- "${VENV_DIR}/bin/pip" install --quiet -r "${TEMP_DIR}/claude-seo/requirements.txt" 2>/dev/null && \- echo " ✓ Installed in venv at ${VENV_DIR}" || \- echo " ⚠ Venv pip install failed. Run: ${VENV_DIR}/bin/pip install -r ${SKILL_DIR}/requirements.txt"- else- pip install --quiet --user -r "${TEMP_DIR}/claude-seo/requirements.txt" 2>/dev/null || \- echo " ⚠ Could not auto-install. Run: pip install --user -r ${SKILL_DIR}/requirements.txt"- fi-- # Optional: Install Playwright browsers (for screenshot analysis)- echo "→ Installing Playwright browsers (optional, for visual analysis)..."- if [ -f "${VENV_DIR}/bin/playwright" ]; then- "${VENV_DIR}/bin/python" -m playwright install chromium 2>/dev/null || \- echo " ⚠ Playwright install failed. Visual analysis will use WebFetch fallback."- else- python3 -m playwright install chromium 2>/dev/null || \- echo " ⚠ Playwright install failed. Visual analysis will use WebFetch fallback."+ cp "${TEMP_DIR}/claude-seo/.claude-plugin/plugin.json" "${SKILL_DIR}/runtime-plugin.json" 2>/dev/null || true++ # Manual installs cannot rely on plugin bin/ PATH injection. Rewrite only+ # exact files copied from this checkout during this install.+ rewrite_doc() {+ local doc="$1" temp_doc+ temp_doc="${doc}.claude-seo-tmp"+ sed -e 's#claude-seo run#"$HOME/.claude/skills/seo/bin/claude-seo" run#g' \+ -e 's#claude-seo setup#"$HOME/.claude/skills/seo/bin/claude-seo" setup#g' \+ -e 's#claude-seo doctor#"$HOME/.claude/skills/seo/bin/claude-seo" doctor#g' \+ "${doc}" > "${temp_doc}"+ mv "${temp_doc}" "${doc}"+ }+ for source_root in "${TEMP_DIR}/claude-seo/skills"/*; do+ [ -d "${source_root}" ] || continue+ skill_name=$(basename "${source_root}")+ while IFS= read -r -d '' source_doc; do+ relative_doc=${source_doc#"${source_root}/"}+ doc="${HOME}/.claude/skills/${skill_name}/${relative_doc}"+ [ -f "${doc}" ] && rewrite_doc "${doc}"+ done < <(find "${source_root}" -type f -name '*.md' -print0)+ done+ for source_root in "${TEMP_DIR}/claude-seo/extensions"/*/skills/*; do+ [ -d "${source_root}" ] || continue+ skill_name=$(basename "${source_root}")+ while IFS= read -r -d '' source_doc; do+ relative_doc=${source_doc#"${source_root}/"}+ doc="${HOME}/.claude/skills/${skill_name}/${relative_doc}"+ [ -f "${doc}" ] && rewrite_doc "${doc}"+ done < <(find "${source_root}" -type f -name '*.md' -print0)+ done+ for source_root in "${TEMP_DIR}/claude-seo/extensions"/*/references; do+ [ -d "${source_root}" ] || continue+ ext_name=$(basename "$(dirname "${source_root}")")+ while IFS= read -r -d '' source_doc; do+ relative_doc=${source_doc#"${source_root}/"}+ doc="${SKILL_DIR}/extensions/${ext_name}/references/${relative_doc}"+ [ -f "${doc}" ] && rewrite_doc "${doc}"+ done < <(find "${source_root}" -type f -name '*.md' -print0)+ done+ for source_doc in "${TEMP_DIR}/claude-seo/agents"/*.md "${TEMP_DIR}/claude-seo/extensions"/*/agents/*.md; do+ [ -f "${source_doc}" ] || continue+ doc="${AGENT_DIR}/$(basename "${source_doc}")"+ [ -f "${doc}" ] && rewrite_doc "${doc}"+ done++ echo "→ Creating isolated Python runtime..."+ set +e+ "${SKILL_DIR}/bin/claude-seo" setup+ runtime_status=$?+ set -e+ if [ "${runtime_status}" -ne 0 ] && [ "${runtime_status}" -ne 10 ]; then+ echo "✗ Core Python runtime setup failed. Installation is incomplete." >&2+ exit 1+ elif [ "${runtime_status}" -eq 10 ]; then+ echo "⚠ Core runtime installed, but Chromium setup is incomplete." >&2fiecho ""diff --git a/pdf/google-seo-reference.md b/pdf/google-seo-reference.mdindex e316a24..1c96d69 100644--- a/pdf/google-seo-reference.md+++ b/pdf/google-seo-reference.md@@ -99,7 +99,7 @@ Measured at the 75th percentile of real user data (field data).### Deprecated/Restricted Types (as of May 2026)- **HowTo**: Rich results removed (September 2023)-- **FAQ**: Rich results retired for all sites (May 7, 2026). FAQPage markup can still aid AI/entity-signal use, but not rich-result eligibility.+- **FAQ**: Rich results retired for all sites (May 7, 2026). FAQPage remains a valid Schema.org type, but no AI or ranking benefit is confirmed.- **SpecialAnnouncement**: Deprecated (July 31, 2025)- **CourseInfo, EstimatedSalary, LearningVideo**: Retired (June 2025)- **ClaimReview**: Retired (June 2025)diff --git a/pyproject.toml b/pyproject.tomlindex d92b58d..14c36c7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,12 +1,12 @@[project]name = "claude-seo"-version = "2.2.3"+version = "2.2.4"description = "Comprehensive SEO analysis skill for Claude Code"requires-python = ">=3.10"license = "MIT"readme = "README.md"authors = [- {name = "Daniel Agrici", email = "[email protected]"}+ {name = "Daniel Agrici"}]keywords = ["seo", "claude-code", "ai-tools", "schema-markup", "e-e-a-t", "geo"]diff --git a/requirements.txt b/requirements.txtindex 76df0f5..9b6a3f2 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,6 +1,6 @@# Claude SEO - Python Dependencies# Bounded version pinning with security-conscious minimums-# Last updated: July 14, 2026 (v2.2.3)+# Last updated: July 20, 2026 (v2.2.4)beautifulsoup4>=4.12.0,<5.0.0 # No known CVEsrequests>=2.32.4,<3.0.0 # CVE-2024-47081, CVE-2024-35195 fixesdiff --git a/scripts/backlinks_auth.py b/scripts/backlinks_auth.pyindex 6709f70..5e1fd54 100644--- a/scripts/backlinks_auth.py+++ b/scripts/backlinks_auth.py@@ -225,7 +225,7 @@ def detect_tier() -> dict:"Moz DA/PA/Spam Score (any domain)","Moz referring domains and anchors","Bing inbound links (verified sites)",- "Bing competitor comparison",+ "Bing comparison between registered properties","Common Crawl domain-level graph","Backlink verification crawler",],@@ -242,7 +242,7 @@ def detect_tier() -> dict:"Backlink verification crawler",],"missing": (- "Add Bing Webmaster API key for competitor comparison. "+ "Add Bing Webmaster API key for registered-property link data. ""Free at https://www.bing.com/webmasters"),}diff --git a/scripts/bing_webmaster.py b/scripts/bing_webmaster.pyindex 5b7453a..847ab33 100644--- a/scripts/bing_webmaster.py+++ b/scripts/bing_webmaster.py@@ -3,7 +3,7 @@Bing Webmaster Tools API client for Claude SEO.Queries the Bing Webmaster API for inbound link data, referring domain counts,-and competitor backlink comparison. Free for verified site owners.+and comparison between properties accessible to the same API account.Usage:python bing_webmaster.py links https://example.com --json@@ -13,11 +13,11 @@ Usage:import argparseimport json-import re+import osimport sysimport timefrom typing import Optional-from urllib.parse import urlparse, quote+from urllib.parse import urlparsetry:import requests@@ -25,33 +25,24 @@ except ImportError:print("Error: requests library required. Install with: pip install requests")sys.exit(1)-import os_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, _SCRIPTS_DIR)try:- from backlinks_auth import get_bing_api_key, get_bing_verified_sites, load_config+ from backlinks_auth import get_bing_api_key, get_bing_verified_sitesfrom google_auth import validate_urlexcept ImportError:print("Error: backlinks_auth.py and google_auth.py required in scripts/", file=sys.stderr)sys.exit(1)BING_API_BASE = "https://ssl.bing.com/webmaster/api.svc/json"+MAX_LINK_COUNT_PAGES = 10+MAX_TARGETS_TO_EXPAND = 10+MAX_URL_LINK_PAGES = 3# Polite delay between requestsREQUEST_DELAY = 1_last_request_time = 0-_BING_APIKEY_RE = re.compile(r"(?i)(apikey=)[^&\s'\"<>)]*")---def _redact_bing_api_key(error_text: object, api_key: str) -> str:- """Redact Bing API keys from request exception strings."""- text = str(error_text)- if api_key:- text = text.replace(api_key, "***REDACTED***")- return _BING_APIKEY_RE.sub(r"\1***REDACTED***", text)--def _rate_limit():"""Enforce polite 1-second delay between Bing API requests."""global _last_request_time@@ -79,9 +70,8 @@ def _bing_request(endpoint: str, api_key: str, params: Optional[dict] = None,_rate_limit()url = f"{BING_API_BASE}/{endpoint}"- if params is None:- params = {}- params["apikey"] = api_key+ request_params = dict(params or {})+ request_params["apikey"] = api_keyheaders = {"Content-Type": "application/json",@@ -90,9 +80,9 @@ def _bing_request(endpoint: str, api_key: str, params: Optional[dict] = None,try:if method == "GET":- response = requests.get(url, params=params, headers=headers, timeout=30)+ response = requests.get(url, params=request_params, headers=headers, timeout=30)else:- response = requests.post(url, params=params, headers=headers, timeout=30)+ response = requests.post(url, params=request_params, headers=headers, timeout=30)if response.status_code == 401:return {@@ -140,7 +130,7 @@ def _bing_request(endpoint: str, api_key: str, params: Optional[dict] = None,return {"status": "error","data": None,- "error": _redact_bing_api_key(e, api_key),+ "error": f"Bing Webmaster request failed ({type(e).__name__})","metadata": {"source": "bing_webmaster"},}@@ -156,50 +146,172 @@ def _normalize_site_url(url: str) -> str:return url-def get_link_details(site_url: str, api_key: str, page: int = 0) -> dict:+def _bing_payload(data: object) -> dict:+ """Unwrap Bing's JSON ``d`` envelope without trusting response shape."""+ if not isinstance(data, dict):+ return {}+ payload = data.get("d", data)+ return payload if isinstance(payload, dict) else {}+++def _bounded_int(value: object, default: int = 0) -> int:+ try:+ return max(0, int(value))+ except (TypeError, ValueError, OverflowError):+ return default+++def _metadata(endpoint: str) -> dict:+ return {+ "source": "bing_webmaster",+ "endpoint": endpoint,+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ }+++def _link_domain(url: str) -> str:+ host = (urlparse(url).hostname or "").lower().rstrip(".")+ return host[4:] if host.startswith("www.") else host+++def _safe_output_url(url: str) -> str:+ """Remove userinfo, query, and fragment from API-returned URLs."""+ parsed = urlparse(url)+ host = parsed.hostname or ""+ try:+ port = parsed.port+ except ValueError:+ port = None+ if port:+ host = f"{host}:{port}"+ return parsed._replace(netloc=host, query="", fragment="").geturl()+++def get_link_details(+ site_url: str,+ api_key: str,+ page: int = 0,+ max_pages_to_expand: int = MAX_TARGETS_TO_EXPAND,+ max_detail_pages: int = MAX_URL_LINK_PAGES,+) -> dict:"""Get inbound link details for a verified site.Args:site_url: Verified site URL.api_key: Bing API key.- page: Page number for pagination (0-based).+ page: GetLinkCounts discovery page (0-based).+ max_pages_to_expand: Maximum target URLs to expand from that page.+ max_detail_pages: Maximum GetUrlLinks pages fetched per target URL.Returns:Standard response dict with link data."""- normalized = _normalize_site_url(site_url)- endpoint = "GetLinkDetails"- params = {- "siteUrl": normalized,- "page": page,- }-- result = _bing_request(endpoint, api_key, params)+ limits = (page, max_pages_to_expand, max_detail_pages)+ if any(not isinstance(value, int) or isinstance(value, bool) for value in limits) \+ or page < 0 or max_pages_to_expand < 1 or max_detail_pages < 1:+ return {+ "status": "error", "data": None,+ "error": "page must be non-negative and expansion limits must be positive",+ "metadata": _metadata("GetLinkCounts+GetUrlLinks"),+ }- if result["status"] == "success" and result["data"]:- raw_data = result["data"]- links = []- link_list = raw_data if isinstance(raw_data, list) else raw_data.get("d", raw_data.get("results", []))- if isinstance(link_list, list):- for item in link_list:+ normalized = _normalize_site_url(site_url)+ counts = _bing_request("GetLinkCounts", api_key, {"siteUrl": normalized, "page": page})+ if counts.get("status") != "success":+ return counts++ payload = _bing_payload(counts.get("data"))+ raw_targets = payload.get("Links", [])+ targets = [item for item in raw_targets if isinstance(item, dict) and item.get("Url")]+ targets.sort(key=lambda item: _bounded_int(item.get("Count")), reverse=True)+ targets = targets[:max_pages_to_expand]++ links = []+ seen = set()+ warnings = []+ partial_errors = []+ successful_detail_calls = 0+ detail_pages_fetched = 0+ count_total_pages = max(1, _bounded_int(payload.get("TotalPages"), 1))+ complete = len(targets) == len(raw_targets) and page + 1 >= count_total_pages++ for target in targets:+ target_url = target["Url"]+ detail_page = 0+ total_detail_pages = 1+ while detail_page < total_detail_pages and detail_page < max_detail_pages:+ detail = _bing_request(+ "GetUrlLinks",+ api_key,+ {"siteUrl": normalized, "link": target_url, "page": detail_page},+ )+ if detail.get("status") != "success":+ partial_errors.append({"target_url": _safe_output_url(target_url), "page": detail_page})+ complete = False+ break+ successful_detail_calls += 1+ detail_pages_fetched += 1+ detail_payload = _bing_payload(detail.get("data"))+ details = detail_payload.get("Details", [])+ if not isinstance(details, list):+ details = []+ complete = False+ warnings.append(f"Unexpected GetUrlLinks payload for target page {len(warnings) + 1}")+ total_detail_pages = max(1, _bounded_int(detail_payload.get("TotalPages"), 1))+ for item in details:+ if not isinstance(item, dict):+ continue+ source_url = item.get("Url", "")+ safe_source = _safe_output_url(source_url)+ safe_target = _safe_output_url(target_url)+ key = (safe_source, safe_target, item.get("AnchorText", ""))+ if not source_url or key in seen:+ continue+ seen.add(key)links.append({- "source_url": item.get("SourceUrl", item.get("sourceUrl", "")),- "target_url": item.get("TargetUrl", item.get("targetUrl", "")),- "anchor_text": item.get("AnchorText", item.get("anchorText", "")),- "date_discovered": item.get("DateDiscovered", item.get("dateDiscovered", "")),+ "source_url": safe_source,+ "target_url": safe_target,+ "anchor_text": item.get("AnchorText", ""),})- result["data"] = {- "site_url": site_url,- "page": page,- "total_returned": len(links),- "links": links,+ detail_page += 1+ if detail_page < total_detail_pages:+ complete = False++ if targets and successful_detail_calls == 0:+ return {+ "status": "error",+ "data": None,+ "error": "Bing returned link-count targets but none could be expanded",+ "metadata": _metadata("GetLinkCounts+GetUrlLinks"),}+ if targets and not links:+ warnings.append("Bing returned target pages but no referring-link details")+ complete = False- return result+ status = "success" if complete and not partial_errors else "partial"+ return {+ "status": status,+ "data": {+ "site_url": _safe_output_url(site_url),+ "count_page": page,+ "targets_available_on_page": len(raw_targets) if isinstance(raw_targets, list) else 0,+ "targets_expanded": len(targets),+ "detail_pages_fetched": detail_pages_fetched,+ "total_returned": len(links),+ "complete": complete,+ "links": links,+ "warnings": warnings,+ "partial_errors": partial_errors,+ },+ "error": None,+ "metadata": _metadata("GetLinkCounts+GetUrlLinks"),+ }-def get_link_counts(site_url: str, api_key: str) -> dict:+def get_link_counts(+ site_url: str, api_key: str, max_pages: int = MAX_LINK_COUNT_PAGES+) -> dict:"""Get total backlink and referring domain counts for a site.@@ -210,36 +322,69 @@ def get_link_counts(site_url: str, api_key: str) -> dict:Returns:Standard response dict with count data."""- normalized = _normalize_site_url(site_url)- endpoint = "GetUrlTrafficInfo"- params = {"siteUrl": normalized}-- result = _bing_request(endpoint, api_key, params)-- # Also get link details page 0 for basic counts- links_result = get_link_details(site_url, api_key, page=0)-- if result["status"] == "success":- raw = result["data"] or {}- link_count = 0- if links_result["status"] == "success" and links_result["data"]:- link_count = links_result["data"].get("total_returned", 0)-- result["data"] = {- "site_url": site_url,- "total_links_sample": link_count,- "traffic_info": raw,- "note": "Link counts are sampled from Bing's index. For comprehensive data, use Moz API or DataForSEO.",+ if not isinstance(max_pages, int) or isinstance(max_pages, bool) or max_pages < 1:+ return {+ "status": "error", "data": None,+ "error": "max_pages must be positive",+ "metadata": _metadata("GetLinkCounts"),}-- return result+ normalized = _normalize_site_url(site_url)+ page = 0+ total_pages = 1+ pages_fetched = 0+ targets = {}+ while page < total_pages and page < max_pages:+ response = _bing_request("GetLinkCounts", api_key, {"siteUrl": normalized, "page": page})+ if response.get("status") != "success":+ if page == 0:+ return response+ return {+ "status": "partial",+ "data": {+ "site_url": _safe_output_url(site_url),+ "pages_fetched": pages_fetched,+ "total_pages": total_pages,+ "pages_with_links_sample": len(targets),+ "sampled_inbound_link_count": sum(targets.values()),+ "complete": False,+ "warnings": [{"endpoint": "GetLinkCounts", "page": page}],+ },+ "error": None,+ "metadata": _metadata("GetLinkCounts"),+ }+ payload = _bing_payload(response.get("data"))+ links = payload.get("Links", [])+ if not isinstance(links, list):+ links = []+ total_pages = max(1, _bounded_int(payload.get("TotalPages"), 1))+ for item in links:+ if isinstance(item, dict) and item.get("Url"):+ targets[item["Url"]] = _bounded_int(item.get("Count"))+ pages_fetched += 1+ page += 1++ complete = page >= total_pages+ return {+ "status": "success" if complete else "partial",+ "data": {+ "site_url": _safe_output_url(site_url),+ "pages_fetched": pages_fetched,+ "total_pages": total_pages,+ "pages_with_links_sample": len(targets),+ "sampled_inbound_link_count": sum(targets.values()),+ "complete": complete,+ "warnings": [] if complete else [f"GetLinkCounts was capped at {max_pages} pages"],+ },+ "error": None,+ "metadata": _metadata("GetLinkCounts"),+ }def compare_links(site_url: str, competitor_url: str, api_key: str) -> dict:"""Compare backlink profiles between your site and a competitor.- This is Bing's unique free feature not available in other free tools.+ Both properties must be registered and accessible to the API account.Args:site_url: Your verified site URL.@@ -249,30 +394,50 @@ def compare_links(site_url: str, competitor_url: str, api_key: str) -> dict:Returns:Standard response dict with comparison data."""- # Get links for both sitesown_result = get_link_details(site_url, api_key)competitor_result = get_link_details(competitor_url, api_key)+ if own_result.get("status") == "error":+ return {+ "status": "error", "data": None,+ "error": "Could not retrieve links for the first registered property",+ "metadata": _metadata("verified-site-comparison"),+ }+ if competitor_result.get("status") == "error":+ return {+ "status": "error", "data": None,+ "error": "The second property is not accessible or its links could not be retrieved",+ "metadata": _metadata("verified-site-comparison"),+ }+ if not isinstance(own_result.get("data"), dict) or not isinstance(competitor_result.get("data"), dict):+ return {+ "status": "error", "data": None,+ "error": "Bing returned an invalid comparison payload",+ "metadata": _metadata("verified-site-comparison"),+ }+own_links = []competitor_links = []own_domains = set()competitor_domains = set()- if own_result["status"] == "success" and own_result["data"]:+ if own_result.get("status") in {"success", "partial"} and own_result.get("data"):own_links = own_result["data"].get("links", [])for link in own_links:source = link.get("source_url", "")if source:- parsed = urlparse(source)- own_domains.add(parsed.netloc)+ domain = _link_domain(source)+ if domain:+ own_domains.add(domain)- if competitor_result["status"] == "success" and competitor_result["data"]:+ if competitor_result.get("status") in {"success", "partial"} and competitor_result.get("data"):competitor_links = competitor_result["data"].get("links", [])for link in competitor_links:source = link.get("source_url", "")if source:- parsed = urlparse(source)- competitor_domains.add(parsed.netloc)+ domain = _link_domain(source)+ if domain:+ competitor_domains.add(domain)# Gap analysisgap_domains = competitor_domains - own_domains # Competitor has, you don't@@ -280,10 +445,10 @@ def compare_links(site_url: str, competitor_url: str, api_key: str) -> dict:unique_domains = own_domains - competitor_domains # You have, competitor doesn'treturn {- "status": "success",+ "status": "partial" if "partial" in {own_result.get("status"), competitor_result.get("status")} else "success","data": {- "site_url": site_url,- "competitor_url": competitor_url,+ "site_url": _safe_output_url(site_url),+ "competitor_url": _safe_output_url(competitor_url),"your_linking_domains": len(own_domains),"competitor_linking_domains": len(competitor_domains),"gap_domains": sorted(list(gap_domains))[:50],@@ -292,12 +457,15 @@ def compare_links(site_url: str, competitor_url: str, api_key: str) -> dict:"gap_count": len(gap_domains),"shared_count": len(shared_domains),"unique_count": len(unique_domains),- "note": "Based on Bing's index sample.",+ "complete": bool(+ own_result["data"].get("complete") and competitor_result["data"].get("complete")+ ),+ "note": "Bing comparison covers only properties accessible to the same API account.",},"error": None,"metadata": {"source": "bing_webmaster",- "comparison": True,+ "comparison": "verified_properties","timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),},}@@ -305,7 +473,7 @@ def compare_links(site_url: str, competitor_url: str, api_key: str) -> dict:def main():parser = argparse.ArgumentParser(- description="Bing Webmaster Tools API client for Claude SEO"+ description="Bing Webmaster Tools API client for registered properties")parser.add_argument("command",@@ -320,7 +488,7 @@ def main():"competitor_url",nargs="?",default=None,- help="Competitor URL (required for 'compare' command)",+ help="Second registered property URL (required for 'compare' command)",)parser.add_argument("--page",@@ -337,12 +505,12 @@ def main():args = parser.parse_args()# Validate URLs- target = args.url- if target.lower().startswith("http") and not validate_url(target):+ target = args.url if "://" in args.url else f"https://{args.url}"+ if not validate_url(target):result = {"status": "error","data": None,- "error": f"Invalid or blocked URL: {target}",+ "error": "Invalid or blocked target URL","metadata": {"source": "bing_webmaster"},}if args.json:@@ -357,12 +525,16 @@ def main():# Validate competitor URL if provided (SSRF protection)if args.competitor_url:- comp = args.competitor_url- if comp.lower().startswith("http") and not validate_url(comp):+ comp = (+ args.competitor_url+ if "://" in args.competitor_url+ else f"https://{args.competitor_url}"+ )+ if not validate_url(comp):result = {"status": "error","data": None,- "error": f"Invalid or blocked competitor URL: {comp}",+ "error": "Invalid or blocked competitor URL","metadata": {"source": "bing_webmaster"},}if args.json:@@ -370,6 +542,7 @@ def main():else:print(f"Error: {result['error']}", file=sys.stderr)sys.exit(1)+ args.competitor_url = comp# Get API keyapi_key = get_bing_api_key()@@ -377,7 +550,7 @@ def main():result = {"status": "error","data": None,- "error": "No Bing Webmaster API key configured. Run: python scripts/backlinks_auth.py --setup",+ "error": "No Bing Webmaster API key configured. Run: claude-seo run backlinks_auth.py --setup","metadata": {"source": "bing_webmaster"},}if args.json:@@ -388,7 +561,7 @@ def main():# Warn if site not in verified listverified = get_bing_verified_sites()- parsed_target = urlparse(target if target.lower().startswith("http") else f"https://{target}")+ parsed_target = urlparse(target)if verified and parsed_target.netloc not in verified and parsed_target.netloc.replace("www.", "") not in verified:print(f"Warning: {parsed_target.netloc} not in bing_verified_sites config. API may return limited data.",file=sys.stderr)@@ -407,7 +580,7 @@ def main():if args.json:print(json.dumps(result, indent=2))else:- if result["status"] == "success" and result["data"]:+ if result["status"] in {"success", "partial"} and result["data"]:data = result["data"]if args.command == "links":print(f"Bing Inbound Links for: {data.get('site_url', target)} ({data.get('total_returned', 0)} returned)")@@ -416,7 +589,8 @@ def main():print(f" {link.get('source_url', '?'):60s} [{anchor}]")elif args.command == "counts":print(f"Bing Link Counts for: {data.get('site_url', target)}")- print(f" Sample links found: {data.get('total_links_sample', 'N/A')}")+ print(f" Pages with links (sample): {data.get('pages_with_links_sample', 'N/A')}")+ print(f" Sampled inbound link count: {data.get('sampled_inbound_link_count', 'N/A')}")elif args.command == "compare":print(f"Backlink Gap: {data.get('site_url', '')} vs {data.get('competitor_url', '')}")print(f" Your linking domains: {data.get('your_linking_domains', 0)}")@@ -425,12 +599,13 @@ def main():print(f" Shared: {data.get('shared_count', 0)}")print(f" Unique to you: {data.get('unique_count', 0)}")if data.get("gap_domains"):- print(f"\n Top gap domains:")+ print("\n Top gap domains:")for d in data["gap_domains"][:10]:print(f" {d}")elif result.get("error"):print(f"Error: {result['error']}", file=sys.stderr)+ return 1 if result.get("status") == "error" else 0if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/scripts/consistency_check.py b/scripts/consistency_check.pyindex 8681f77..484ebae 100644--- a/scripts/consistency_check.py+++ b/scripts/consistency_check.py@@ -43,6 +43,7 @@ GENERIC_BASENAMES = {"README.md", "SKILL.md", "__init__.py", "LICENSE", "LICENSE"plugin.json", "marketplace.json", "hooks.json"}DOC_EXAMPLE_AGENTS = {"seo-newagent"}LOCK_PATH = "skills/seo-flow/references/flow-prompts.lock"+RUNTIME_UTILITY_COMMANDS = {"setup", "doctor"}def tracked_files():@@ -123,7 +124,7 @@ def check_script_refs(files, texts):candidates = [f"scripts/{m}"]if ext_root:candidates.insert(0, f"{ext_root}/scripts/{m}")- if not any(c in files for c in candidates):+ if not any(c in files or os.path.isfile(os.path.join(REPO, c)) for c in candidates):errors.append(f"{f}: dead script ref scripts/{m} "f"(checked: {', '.join(candidates)})")orphans = []@@ -138,6 +139,57 @@ def check_script_refs(files, texts):return errors, orphans+def check_skill_dir_script_refs(files, texts):+ """Validate scripts invoked through Claude's portable skill-root variable.++ Extension installers place their scripts beside the installed skill. In the+ source tree those scripts live at ``extensions/<name>/scripts``. Core skills+ must carry scripts inside their own skill directory before using this form.+ """+ pat = re.compile(r'\$\{CLAUDE_SKILL_DIR\}/scripts/([A-Za-z0-9_]+\.py)\b')+ errors = []+ for f in texts:+ for script in sorted(set(pat.findall(read(f)))):+ ext_root = extension_root(f)+ if ext_root:+ candidate = f"{ext_root}/scripts/{script}"+ elif f.startswith("skills/"):+ skill_root = "/".join(f.split("/")[:2])+ candidate = f"{skill_root}/scripts/{script}"+ else:+ errors.append(f"{f}: CLAUDE_SKILL_DIR script used outside a skill layout")+ continue+ if candidate not in files and not os.path.isfile(os.path.join(REPO, candidate)):+ errors.append(+ f"{f}: dead skill-root script {script} (checked: {candidate})"+ )+ return errors+++def check_runtime_invocations(texts):+ """Reject cwd-dependent or interpreter-dependent bundled script commands."""+ errors = []+ carriers = [+ f for f in texts+ if f.startswith(("skills/", "agents/", "extensions/")) and f.endswith(".md")+ ]+ bare = re.compile(+ r"\b(?:python3|python|py\s+-3)\s+[^\n`]*?scripts/[A-Za-z0-9_./-]+\.py"+ )+ runtime = re.compile(r"\bclaude-seo\s+run(?:\s+--extension\s+[a-z0-9-]+)?\s+([A-Za-z0-9_-]+\.py)")+ for f in carriers:+ content = read(f)+ for match in bare.finditer(content):+ errors.append(f"{f}: bare bundled-script invocation: {match.group(0)}")+ for script in sorted(set(runtime.findall(content))):+ if not os.path.isfile(os.path.join(REPO, "scripts", script)) and not any(+ os.path.isfile(path)+ for path in glob.glob(os.path.join(REPO, "extensions", "*", "scripts", script))+ ):+ errors.append(f"{f}: runtime invocation references missing script {script}")+ return errors++def check_routing(files):cmd_pat = re.compile(r'`/seo(?:\s+([a-z][a-z0-9-]*))?')tables = {src: {m for m in cmd_pat.findall(read(src)) if m}@@ -153,7 +205,7 @@ def check_routing(files):errors.append(f"routing: `/seo {c}` in orchestrator but not docs/COMMANDS.md")for c in sorted(b - a):errors.append(f"routing: `/seo {c}` in docs/COMMANDS.md but not orchestrator")- for c in sorted((a | b) - known):+ for c in sorted((a | b) - known - RUNTIME_UTILITY_COMMANDS):errors.append(f"routing: `/seo {c}` has no matching skill directory")return errors@@ -228,6 +280,8 @@ def main():ref_errors, ref_infos = check_references(fileset, md)script_errors, script_orphans = check_script_refs(fileset, texts)errors = (ref_errors + check_research_refs(fileset, texts) + script_errors+ + check_skill_dir_script_refs(fileset, texts)+ + check_runtime_invocations(texts)+ check_routing(fileset) + check_agent_refs(fileset, texts)+ check_flow_lock(fileset))warnings = script_orphans + check_orphan_files(fileset, texts)diff --git a/scripts/google_auth.py b/scripts/google_auth.pyindex 7e3bbed..c7c88f4 100644--- a/scripts/google_auth.py+++ b/scripts/google_auth.py@@ -238,7 +238,9 @@ def _save_oauth_token(token_data: dict):# os.fdopen takes ownership of fd — it closes the fd whether the# write succeeds or raises, so there is no fd-leak path here.try:- os.fchmod(fd, 0o600)+ fchmod = getattr(os, "fchmod", None)+ if fchmod is not None:+ fchmod(fd, 0o600)except OSError:pass # FS may not support fchmod (e.g. some Windows filesystems)with os.fdopen(fd, "w") as f:diff --git a/scripts/google_report.py b/scripts/google_report.pyindex 3b18211..d08ed91 100644--- a/scripts/google_report.py+++ b/scripts/google_report.py@@ -28,15 +28,17 @@ try:import matplotlib.pyplot as pltimport matplotlib.patches as mpatchesimport numpy as np-except ImportError:- print("Error: matplotlib required. Install with: pip install matplotlib", file=sys.stderr)- sys.exit(1)+ _CHART_IMPORT_ERROR = None+except (ImportError, OSError, RuntimeError) as exc:+ matplotlib = plt = mpatches = np = None+ _CHART_IMPORT_ERROR = exctry:from weasyprint import HTML-except ImportError:- print("Error: weasyprint required. Install with: pip install weasyprint", file=sys.stderr)- sys.exit(1)+ _PDF_IMPORT_ERROR = None+except (ImportError, OSError) as exc:+ HTML = None+ _PDF_IMPORT_ERROR = exc# ─── Brand Colors ────────────────────────────────────────────────────────────@@ -140,7 +142,17 @@ def _setup_matplotlib():})-_setup_matplotlib()+if plt is not None:+ _setup_matplotlib()+++def _require_chart_dependencies() -> None:+ """Raise a runtime error only when a requested report needs charts."""+ if plt is None or np is None:+ raise RuntimeError(+ "matplotlib and numpy are required for chart generation. "+ "Install the report dependencies from requirements.txt."+ ) from _CHART_IMPORT_ERROR# ─── Chart Functions ─────────────────────────────────────────────────────────@@ -150,6 +162,7 @@ def chart_lighthouse_gauges(data: dict, output_dir: Path) -> str:scores = data.get("lighthouse_scores", {})if not scores:return ""+ _require_chart_dependencies()fig, axes = plt.subplots(2, 2, figsize=(8, 4), subplot_kw={"projection": "polar"})categories = [@@ -210,6 +223,7 @@ def chart_cwv_distributions(data: dict, output_dir: Path) -> str:if not labels:return ""+ _require_chart_dependencies()fig, ax = plt.subplots(figsize=(8, max(2.5, len(labels) * 0.7)))y = range(len(labels))@@ -259,6 +273,7 @@ def chart_cwv_timeline(data: dict, output_dir: Path) -> str:available = [m for m in cwv_metrics if m in metrics]if not available:return ""+ _require_chart_dependencies()fig, axes = plt.subplots(len(available), 1, figsize=(10, 3 * len(available)), sharex=True)if len(available) == 1:@@ -327,6 +342,7 @@ def chart_top_queries(data: dict, output_dir: Path) -> str:if not impressions or max(impressions) < 3:return ""+ _require_chart_dependencies()fig, ax = plt.subplots(figsize=(7, max(2, len(labels) * 0.3)))y = range(len(labels))@@ -375,6 +391,7 @@ def chart_index_status(data: dict, output_dir: Path) -> str:if not sizes:return ""+ _require_chart_dependencies()fig, ax = plt.subplots(figsize=(4.5, 3.5))wedges, texts, autotexts = ax.pie(@@ -2063,35 +2080,39 @@ def generate_report(report_type, data, domain, output_dir, output_format="pdf"):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 {}- path = chart_lighthouse_gauges(mobile, charts_dir)- if path:- chart_paths["gauges_path"] = path-- crux = data.get("crux", {})- path = chart_cwv_distributions({"crux": crux} if crux else data, charts_dir)- if path:- chart_paths["distributions_path"] = path+ try:+ if report_type in ("cwv-audit", "full"):+ psi = data.get("psi", data)+ mobile = psi.get("psi", {}).get("mobile", psi) if isinstance(psi, dict) else {}+ path = chart_lighthouse_gauges(mobile, charts_dir)+ if path:+ chart_paths["gauges_path"] = path- history = data.get("crux_history", {})- if history and not history.get("error"):- path = chart_cwv_timeline(history, charts_dir)+ crux = data.get("crux", {})+ path = chart_cwv_distributions({"crux": crux} if crux else data, charts_dir)if path:- chart_paths["timeline_path"] = path+ chart_paths["distributions_path"] = path- if report_type in ("gsc-performance", "full"):- gsc = data.get("gsc", data)- path = chart_top_queries(gsc, charts_dir)- if path:- chart_paths["top_queries_path"] = path+ history = data.get("crux_history", {})+ if history and not history.get("error"):+ path = chart_cwv_timeline(history, charts_dir)+ if path:+ chart_paths["timeline_path"] = path- if report_type in ("indexation", "full"):- inspect = data.get("inspection", data)- path = chart_index_status(inspect, charts_dir)- if path:- chart_paths["index_status_path"] = path+ if report_type in ("gsc-performance", "full"):+ gsc = data.get("gsc", data)+ path = chart_top_queries(gsc, charts_dir)+ if path:+ chart_paths["top_queries_path"] = path++ if report_type in ("indexation", "full"):+ inspect = data.get("inspection", data)+ path = chart_index_status(inspect, charts_dir)+ if path:+ chart_paths["index_status_path"] = path+ except RuntimeError as exc:+ result["error"] = str(exc)+ return result# ── Build HTML Sections ──────────────────────────────────────────────────@@ -2362,6 +2383,12 @@ def generate_report(report_type, data, domain, output_dir, output_format="pdf"):result["files"].append(str(html_path))if output_format in ("pdf", "both", "all"):+ if HTML is None:+ result["error"] = (+ "weasyprint is required for PDF generation. "+ "Install the report dependencies from requirements.txt."+ )+ return resultpdf_path = output_dir / f"{base_name}.pdf"try:HTML(string=html_content).write_pdf(str(pdf_path))@@ -2643,7 +2670,7 @@ def main():# Load dataif args.data:try:- with open(args.data, "r") as f:+ with open(args.data, "r", encoding="utf-8") as f:data = json.load(f)except (json.JSONDecodeError, IOError) as e:print(f"Error reading data file: {e}", file=sys.stderr)diff --git a/scripts/gsc_query.py b/scripts/gsc_query.pyindex 954ab97..4112b0b 100644--- a/scripts/gsc_query.py+++ b/scripts/gsc_query.py@@ -47,6 +47,41 @@ GSC_ANOMALY_WARNING = ("GSC impressions logging error affected impressions, CTR, and average ""position from 2025-05-13 through 2026-04-27; clicks were not affected.")+MAX_TOTAL_ROWS = 100000+VALID_DIMENSIONS = {+ "query", "page", "country", "device", "date", "hour", "searchAppearance",+}+++def _validate_dimensions(dimensions: Optional[list]) -> list[str]:+ """Validate API dimensions before credentials or a service are loaded."""+ if dimensions is None:+ return ["query", "page"]+ if not isinstance(dimensions, list):+ raise ValueError("GSC dimensions must be a list or None")+ if any(not isinstance(item, str) for item in dimensions):+ raise ValueError("GSC dimensions must contain only strings")+ invalid = sorted(set(dimensions) - VALID_DIMENSIONS)+ if invalid:+ raise ValueError(f"Unsupported GSC dimensions: {', '.join(invalid)}")+ if len(dimensions) != len(set(dimensions)):+ raise ValueError("GSC dimensions cannot contain duplicates")+ return list(dimensions)+++def _parse_dimensions(raw: str) -> list[str]:+ """Parse a comma-separated CLI dimension list, preserving an empty list."""+ return _validate_dimensions([item.strip() for item in raw.split(",") if item.strip()])+++def _totals_from_row(row: dict) -> dict:+ """Normalize a Search Analytics aggregate row for public output."""+ return {+ "clicks": row.get("clicks", 0),+ "impressions": row.get("impressions", 0),+ "ctr": round(row.get("ctr", 0) * 100, 2),+ "position": round(row.get("position", 0), 1),+ }def _date_range_overlaps(start_date: str, end_date: str, overlap_start: str, overlap_end: str) -> bool:@@ -106,13 +141,7 @@ def _query_site_totals(rows = response.get("rows", [])if not rows:return {"clicks": 0, "impressions": 0, "ctr": 0, "position": 0}- agg = rows[0]- return {- "clicks": agg.get("clicks", 0),- "impressions": agg.get("impressions", 0),- "ctr": round(agg.get("ctr", 0) * 100, 2),- "position": round(agg.get("position", 0), 1),- }+ return _totals_from_row(rows[0])def query_search_analytics(@@ -134,7 +163,8 @@ def query_search_analytics(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.+ row_limit: Maximum total rows to return. Requests are internally paged+ at up to 25,000 rows and the public result is capped at 100,000.filters: List of filter dicts with dimension, operator, expression.data_state: 'final' or 'all' (includes fresh/unfinalized data).@@ -145,12 +175,24 @@ def query_search_analytics("property": site_url,"rows": [],"totals": {"clicks": 0, "impressions": 0, "ctr": 0, "position": 0},+ "totals_source": None,+ "totals_complete": False,"quick_wins": [],"warnings": [],"row_count": 0,"error": None,}+ if not isinstance(row_limit, int) or isinstance(row_limit, bool) or row_limit < 1:+ result["error"] = "row_limit must be a positive integer"+ return result++ try:+ dimensions = _validate_dimensions(dimensions)+ except ValueError as exc:+ result["error"] = str(exc)+ return result+service = _build_gsc_service()if not service:result["error"] = "Could not build GSC service. Check service account credentials."@@ -160,19 +202,22 @@ def query_search_analytics(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}if _date_range_overlaps(start_date, end_date, GSC_ANOMALY_START, GSC_ANOMALY_END):result["warnings"].append(GSC_ANOMALY_WARNING)+ total_cap = min(row_limit, MAX_TOTAL_ROWS)+ if row_limit > MAX_TOTAL_ROWS:+ result["warnings"].append(+ f"Requested row limit {row_limit:,} was capped at {MAX_TOTAL_ROWS:,}."+ )+body = {"startDate": start_date,"endDate": end_date,"dimensions": dimensions,"type": search_type,- "rowLimit": min(row_limit, 25000),+ "rowLimit": min(total_cap, 25000),"dataState": data_state,}@@ -182,10 +227,11 @@ def query_search_analytics(# Auto-paginateall_rows = []start_row = 0- page_size = min(row_limit, 25000)try:- while True:+ while len(all_rows) < total_cap:+ remaining = total_cap - len(all_rows)+ page_size = min(remaining, 25000)body["startRow"] = start_rowbody["rowLimit"] = page_size@@ -194,15 +240,15 @@ def query_search_analytics().execute()rows = response.get("rows", [])- all_rows.extend(rows)+ all_rows.extend(rows[:remaining])- if len(rows) < page_size:+ if len(rows) < page_size or len(all_rows) >= total_cap:break- start_row += page_size+ start_row += len(rows)# Safety: cap at 100,000 rows- if start_row >= 100000:+ if start_row >= MAX_TOTAL_ROWS:breakexcept Exception as e:@@ -258,16 +304,31 @@ def query_search_analytics(# because GSC anonymizes low-volume queries, producing a false "0 clicks"# site total (issue #130). Fall back to the row sum only if the aggregate# query fails.- site_totals = _query_site_totals(- service, site_url, start_date, end_date, search_type, data_state, filters- )- if site_totals is not None:- result["totals"] = site_totals+ if dimensions == []:+ result["totals"] = (+ _totals_from_row(all_rows[0]) if all_rows+ else {"clicks": 0, "impressions": 0, "ctr": 0, "position": 0}+ )+ result["totals_source"] = "dimensionless_query"+ result["totals_complete"] = Trueelse:- result["totals"]["clicks"] = total_clicks- result["totals"]["impressions"] = total_impressions- if total_impressions > 0:- result["totals"]["ctr"] = round((total_clicks / total_impressions) * 100, 2)+ site_totals = _query_site_totals(+ service, site_url, start_date, end_date, search_type, data_state, filters+ )+ if site_totals is not None:+ result["totals"] = site_totals+ result["totals_source"] = "dimensionless_aggregate"+ result["totals_complete"] = True+ else:+ result["totals"]["clicks"] = total_clicks+ result["totals"]["impressions"] = total_impressions+ if total_impressions > 0:+ result["totals"]["ctr"] = round((total_clicks / total_impressions) * 100, 2)+ result["totals_source"] = "partial_row_sum"+ result["warnings"].append(+ "The dimensionless totals query failed. Reported totals are an "+ "incomplete sum of returned rows and must not be presented as site-wide totals."+ )# Quick wins: position 4-10 with high impressionsif "query" in dimensions:@@ -408,7 +469,10 @@ def main():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(",")]+ try:+ dims = _parse_dimensions(args.dimensions)+ except ValueError as exc:+ parser.error(str(exc))filters = []if args.device:filters.append({diff --git a/scripts/render_page.py b/scripts/render_page.pyindex d5ebb42..2849576 100644--- a/scripts/render_page.py+++ b/scripts/render_page.py@@ -39,6 +39,7 @@ A dict with::headers response headers from the main documentredirect_chain list of {url, status_code}console_errors list of browser console error strings+ render_diagnostics list of non-fatal render degradation messagesrender_engine 'playwright-chromium' or Nonerender_ms elapsed wall-clock for the render stepmode_used 'rendered' or 'raw'@@ -70,6 +71,8 @@ import sysimport timefrom typing import Optional+from bs4 import BeautifulSoup+# Optional native dependencies. Each is checked lazily so callers that# only need raw-mode (mode='never') don't pay the import cost.try:@@ -129,8 +132,124 @@ _SPA_SHELL_PATTERNS = ('please enable javascript',)+# Builder markers are supporting evidence only. Wix, Webflow, and Squarespace+# can all serve complete HTML, so auto-render requires multiple same-builder+# markers plus sparse meaningful body text.+_BUILDER_FINGERPRINT_GROUPS = (+ ("wix-warmup-data", "static.parastorage.com", 'content="wix.com'),+ ("data-wf-page", "data-wf-site"),+ ('content="squarespace', "static1.squarespace.com"),+)+_TAG_STRIP = re.compile(r"<[^>]+>")_WHITESPACE = re.compile(r"\s+")+_NON_VISIBLE_STRIP = re.compile(+ r"<(script|style|template|noscript)\b[^>]*>.*?</\1>",+ re.IGNORECASE | re.DOTALL,+)+_BUILDER_SPARSE_TEXT_MAX = 400++JSON_LD_MAX_BLOCKS = 50+JSON_LD_MAX_BLOCK_BYTES = 256 * 1024+JSON_LD_MAX_TOTAL_BYTES = 1024 * 1024+JSON_LD_MAX_NODES = 10_000+JSON_LD_MAX_DEPTH = 40+++def _visible_body_text(lower_html: str) -> str:+ body_start = lower_html.find("<body")+ body_end = lower_html.rfind("</body>")+ if body_start == -1 or body_end <= body_start:+ return ""+ body = _NON_VISIBLE_STRIP.sub(" ", lower_html[body_start:body_end])+ return _WHITESPACE.sub(" ", _TAG_STRIP.sub(" ", body)).strip()+++def _schema_types(data: object) -> tuple[list[str], bool]:+ """Collect bounded @type values without recursive attacker-controlled calls."""+ types: set[str] = set()+ stack: list[tuple[object, int]] = [(data, 0)]+ visited = 0+ truncated = False+ while stack:+ value, depth = stack.pop()+ visited += 1+ if visited > JSON_LD_MAX_NODES or depth > JSON_LD_MAX_DEPTH:+ truncated = True+ break+ if isinstance(value, dict):+ schema_type = value.get("@type")+ if isinstance(schema_type, str):+ types.add(schema_type)+ elif isinstance(schema_type, list):+ types.update(item for item in schema_type if isinstance(item, str))+ stack.extend((item, depth + 1) for item in value.values())+ elif isinstance(value, list):+ stack.extend((item, depth + 1) for item in value)+ return sorted(types)[:100], truncated or len(types) > 100+++def _extract_json_ld(html: Optional[str], *, include_full: bool = False) -> dict:+ """Extract full-page JSON-LD with strict block, byte, and traversal bounds."""+ result = {+ "block_count": 0,+ "processed_count": 0,+ "total_bytes": 0,+ "truncated": False,+ "blocks": [],+ }+ if not html:+ return result++ soup = BeautifulSoup(html, "html.parser")+ scripts = [+ script for script in soup.find_all("script")+ if str(script.get("type", "")).strip().lower() == "application/ld+json"+ ]+ result["block_count"] = len(scripts)++ for index, script in enumerate(scripts):+ if index >= JSON_LD_MAX_BLOCKS:+ result["truncated"] = True+ break+ raw = script.string if script.string is not None else script.get_text()+ raw = str(raw or "").strip()+ size_bytes = len(raw.encode("utf-8"))+ if result["total_bytes"] + size_bytes > JSON_LD_MAX_TOTAL_BYTES:+ result["truncated"] = True+ break+ result["total_bytes"] += size_bytes+ result["processed_count"] += 1++ entry = {"index": index + 1, "size_bytes": size_bytes}+ if size_bytes > JSON_LD_MAX_BLOCK_BYTES:+ entry.update({+ "valid": None,+ "error": "block exceeds the JSON-LD per-block byte limit",+ })+ result["truncated"] = True+ result["blocks"].append(entry)+ continue++ try:+ parsed = json.loads(raw)+ types, types_truncated = _schema_types(parsed)+ entry.update({+ "valid": True,+ "types": types,+ "types_truncated": types_truncated,+ })+ if include_full:+ entry["data"] = parsed+ except (json.JSONDecodeError, RecursionError) as exc:+ entry.update({+ "valid": False,+ "error": f"{type(exc).__name__}: {exc}",+ })+ if include_full:+ entry["raw"] = raw+ result["blocks"].append(entry)+ return resultdef _is_spa(raw_html: Optional[str]) -> bool:@@ -140,6 +259,11 @@ def _is_spa(raw_html: Optional[str]) -> bool:lc = raw_html.lower()if any(pattern in lc for pattern in _SPA_SHELL_PATTERNS):return True+ visible_text = _visible_body_text(lc)+ if len(visible_text) < _BUILDER_SPARSE_TEXT_MAX:+ for markers in _BUILDER_FINGERPRINT_GROUPS:+ if sum(marker in lc for marker in markers) >= 2:+ return True# Very thin <body> suggests JS-rendered content even without a shell.# Threshold (100 chars) sits between typical SPA shells (0-50 chars of# body text) and minimal informational pages like example.com (~125@@ -148,13 +272,39 @@ def _is_spa(raw_html: Optional[str]) -> bool:body_start = lc.find("<body")body_end = lc.rfind("</body>")if body_start != -1 and body_end > body_start:- body = lc[body_start:body_end]- text = _WHITESPACE.sub(" ", _TAG_STRIP.sub("", body)).strip()- if len(text) < 100:+ if len(visible_text) < 100:return Truereturn False+def _wait_for_dom_stability(page, timeout_ms: int) -> bool: # type: ignore[no-untyped-def]+ """Wait up to five seconds for meaningful body text and a stable DOM."""+ budget_ms = max(250, min(timeout_ms, 5000))+ previous = None+ stable_samples = 0+ elapsed_ms = 0+ while elapsed_ms < budget_ms:+ try:+ signature = tuple(page.evaluate(+ "() => ["+ "(document.body && document.body.innerText || '').trim().length,"+ "document.querySelectorAll('*').length"+ "]"+ ))+ except Exception:+ return False+ if signature == previous and signature[0] >= 100:+ stable_samples += 1+ if stable_samples >= 2:+ return True+ else:+ stable_samples = 0+ previous = signature+ page.wait_for_timeout(250)+ elapsed_ms += 250+ return False++def render_page(url: str,*,@@ -186,6 +336,7 @@ def render_page("headers": {},"redirect_chain": [],"console_errors": [],+ "render_diagnostics": [],"render_engine": None,"render_ms": None,"mode_used": None,@@ -263,11 +414,21 @@ def render_page(page.on("console", _on_console)page.route("**/*", route_handler)- response = page.goto(- norm_url, wait_until="networkidle", timeout=timeout_ms- )- # Allow late hydration (deferred islands, useEffect chains).- page.wait_for_timeout(500)+ try:+ response = page.goto(+ norm_url, wait_until="domcontentloaded", timeout=timeout_ms+ )+ except PlaywrightTimeout:+ response = None+ result["render_diagnostics"].append(+ f"DOMContentLoaded timed out after {timeout_ms}ms; "+ "captured the available DOM"+ )+ if not _wait_for_dom_stability(page, timeout_ms):+ result["render_diagnostics"].append(+ "DOM did not reach the bounded stability threshold; "+ "captured the available DOM"+ )result["url"] = page.urlresult["content"] = page.content()@@ -287,9 +448,6 @@ def render_page(result["accessibility_tree"] = Nonebrowser.close()- except PlaywrightTimeout:- result["error"] = f"playwright navigation timed out after {timeout_ms}ms"- return resultexcept Exception as exc:result["error"] = f"playwright error: {exc}"return result@@ -361,6 +519,13 @@ def _cli() -> None:action="store_true",help="emit a JSON summary (truncates content fields)",)+ parser.add_argument(+ "--json-ld-output",+ help=(+ "write bounded full JSON-LD extraction to a UTF-8 JSON file; "+ "normal --json output contains summaries only"+ ),+ )parser.add_argument("--output", "-o", help="write HTML content to file")args = parser.parse_args()@@ -375,8 +540,15 @@ def _cli() -> None:extract_accessibility=args.a11y_tree,)+ full_content = res.get("content") or res.get("raw_content") or ""+ if args.json_ld_output:+ extraction = _extract_json_ld(full_content, include_full=True)+ with open(args.json_ld_output, "w", encoding="utf-8") as fh:+ json.dump(extraction, fh, indent=2, ensure_ascii=False)+if args.json:summary = dict(res)+ summary["structured_data"] = _extract_json_ld(full_content)# JSON-safe truncation so the CLI is usable from agents without# piping megabytes of HTML across stdio.for field, limit in (diff --git a/scripts/runtime.py b/scripts/runtime.pynew file mode 100755index 0000000..be904f0--- /dev/null+++ b/scripts/runtime.py@@ -0,0 +1,404 @@+#!/usr/bin/env python3+"""Cross-platform runtime for Claude SEO's bundled Python scripts.++This module deliberately uses only the Python standard library. It is launched+by ``bin/claude-seo`` under a base Python, then dispatches work through the+managed virtual environment created by ``setup``.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import re+import shutil+import subprocess+import sys+import time+from pathlib import Path+from typing import Any++RUNTIME_SCHEMA = 1+LOCK_STALE_SECONDS = 30 * 60+SCRIPT_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*\.py$")+EXTENSION_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")+MANUAL_EXTENSION_SKILLS = {"banana": "seo-image-gen"}+ALLOWED_CORE_SCRIPTS = frozenset(+ {+ "agent_ux_check.py", "analyze_visual.py", "backlinks_auth.py",+ "bing_webmaster.py", "capture_screenshot.py", "commoncrawl_graph.py",+ "content_humanize.py", "content_quality.py", "content_verify.py",+ "crux_history.py", "dataforseo_costs.py", "dataforseo_merchant.py",+ "dataforseo_normalize.py", "domain_history.py", "drift_baseline.py",+ "drift_compare.py", "drift_history.py", "drift_report.py", "fetch_page.py",+ "ga4_report.py", "gbp_deprecation_lint.py", "google_auth.py",+ "google_report.py", "gsc_inspect.py", "gsc_query.py", "indexing_notify.py",+ "indexnow_submit.py", "iptc_ai_label.py", "keyword_planner.py",+ "lcp_subparts.py", "moz_api.py", "nlp_analyze.py", "pagespeed_check.py",+ "parasite_risk.py", "parse_html.py", "preload_check.py", "render_page.py",+ "portability_check.py", "consistency_check.py",+ "schema_ecommerce_validate.py", "schema_generate.py", "seo_updates.py",+ "sitemap_discovery.py", "sync_flow.py", "ucp_check.py", "unlighthouse_run.py",+ "url_safety.py", "validate_backlink_report.py", "verify_backlinks.py",+ "youtube_search.py",+ }+)+REDACTIONS = (+ (re.compile(r"(?i)(https?://[^\s:/]+:)[^@\s]+@"), r"\1<redacted>@"),+ (re.compile(r"(?i)(https?://[^\s?]+\?)[^\s]+"), r"\1<redacted>"),+ (re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"), "<redacted-email>"),+ (re.compile(r"(?i)(token|password|secret|api[_-]?key)([=:\s]+)[^\s]+"), r"\1\2<redacted>"),+)+++def _configure_utf8() -> None:+ for stream in (sys.stdout, sys.stderr):+ reconfigure = getattr(stream, "reconfigure", None)+ if reconfigure:+ reconfigure(encoding="utf-8", errors="replace")+++def _root() -> Path:+ return Path(__file__).resolve().parent.parent+++def _plugin_version(root: Path) -> str:+ for manifest in (root / ".claude-plugin" / "plugin.json", root / "runtime-plugin.json"):+ try:+ value = json.loads(manifest.read_text(encoding="utf-8")).get("version")+ if isinstance(value, str):+ return value+ except (OSError, ValueError):+ pass+ metadata = root / "pyproject.toml"+ try:+ match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', metadata.read_text(encoding="utf-8"))+ if match:+ return match.group(1)+ except OSError:+ pass+ return "unknown"+++def _requirements_hash(root: Path) -> str:+ try:+ content = (root / "requirements.txt").read_bytes()+ except OSError:+ return "missing"+ return hashlib.sha256(content).hexdigest()+++def _is_plugin(root: Path) -> bool:+ if os.environ.get("CLAUDE_PLUGIN_DATA") or os.environ.get("CLAUDE_PLUGIN_ROOT"):+ return True+ return (root / ".claude-plugin" / "plugin.json").is_file() and not (root / ".git").exists()+++def _configured_data_dir(raw: str) -> Path:+ """Resolve a configured data directory and reject destructive broad roots."""+ candidate = Path(raw).expanduser().resolve()+ filesystem_root = Path(candidate.anchor).resolve()+ try:+ user_home = Path.home().resolve()+ except RuntimeError:+ user_home = None+ if candidate == filesystem_root or candidate == user_home:+ raise ValueError("runtime data directory must be a dedicated subdirectory")+ return candidate+++def _data_dir(root: Path) -> tuple[Path, str]:+ override = os.environ.get("CLAUDE_SEO_DATA_DIR")+ if override:+ return _configured_data_dir(override), "override"+ plugin_data = os.environ.get("CLAUDE_PLUGIN_DATA")+ if plugin_data:+ return _configured_data_dir(plugin_data), "plugin"+ if _is_plugin(root):+ if sys.platform == "win32":+ base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))+ elif sys.platform == "darwin":+ base = Path.home() / "Library" / "Application Support"+ else:+ base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))+ return (base / "claude-seo").resolve(), "plugin-fallback"+ return root, "manual"+++def _venv_python(venv: Path) -> Path:+ return venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+++def _state_path(data_dir: Path) -> Path:+ return data_dir / "runtime-state.json"+++def _load_state(data_dir: Path) -> dict[str, Any]:+ try:+ value = json.loads(_state_path(data_dir).read_text(encoding="utf-8"))+ return value if isinstance(value, dict) else {}+ except (OSError, ValueError):+ return {}+++def _expected(root: Path) -> dict[str, Any]:+ return {+ "runtime_schema": RUNTIME_SCHEMA,+ "plugin_version": _plugin_version(root),+ "requirements_sha256": _requirements_hash(root),+ "python": f"{sys.version_info.major}.{sys.version_info.minor}",+ }+++def _status(root: Path) -> dict[str, Any]:+ data_dir, mode = _data_dir(root)+ venv = data_dir / ".venv"+ python = _venv_python(venv)+ state = _load_state(data_dir)+ expected = _expected(root)+ reasons: list[str] = []+ if not python.is_file():+ reasons.append("managed environment is missing")+ for key in ("runtime_schema", "requirements_sha256", "python"):+ if state.get(key) != expected[key]:+ reasons.append(f"{key} changed")+ browser_dir = data_dir / "ms-playwright"+ try:+ browser_installed = browser_dir.is_dir() and any(+ child.name.startswith(("chromium-", "chromium_headless_shell-"))+ for child in browser_dir.iterdir()+ )+ except OSError:+ browser_installed = False+ return {+ "ready": not reasons,+ "mode": mode,+ "python_version": expected["python"],+ "plugin_version": expected["plugin_version"],+ "browser_ready": bool(state.get("browser_ready")) and browser_installed,+ "reasons": reasons,+ "data_dir": data_dir,+ "venv": venv,+ "python_path": python,+ "state": state,+ "expected": expected,+ }+++def _safe_env(status: dict[str, Any]) -> dict[str, str]:+ env = os.environ.copy()+ env["PYTHONUTF8"] = "1"+ env["PYTHONIOENCODING"] = "utf-8"+ env["PLAYWRIGHT_BROWSERS_PATH"] = str(status["data_dir"] / "ms-playwright")+ return env+++def _redact(text: str) -> str:+ try:+ home = str(Path.home())+ if home:+ text = text.replace(home, "<home>")+ except RuntimeError:+ pass+ for pattern, replacement in REDACTIONS:+ text = pattern.sub(replacement, text)+ return text+++def _run_checked(+ argv: list[str], *, env: dict[str, str], stage: str+) -> subprocess.CompletedProcess[str]:+ result = subprocess.run(argv, env=env, capture_output=True, text=True, encoding="utf-8", errors="replace")+ if result.returncode:+ raise RuntimeError(f"{stage} failed with exit code {result.returncode}")+ return result+++class SetupLock:+ def __init__(self, path: Path):+ self.path = path++ def __enter__(self) -> "SetupLock":+ self.path.parent.mkdir(parents=True, exist_ok=True)+ try:+ with self.path.open("x", encoding="utf-8") as handle:+ handle.write(f"{os.getpid()}\n{int(time.time())}\n")+ except FileExistsError:+ try:+ age = time.time() - self.path.stat().st_mtime+ except OSError:+ age = 0+ if age <= LOCK_STALE_SECONDS:+ raise RuntimeError("another Claude SEO setup is already running")+ self.path.unlink(missing_ok=True)+ with self.path.open("x", encoding="utf-8") as handle:+ handle.write(f"{os.getpid()}\n{int(time.time())}\n")+ return self++ def __exit__(self, *_: object) -> None:+ self.path.unlink(missing_ok=True)+++def command_setup(args: argparse.Namespace) -> int:+ root = _root()+ status = _status(root)+ data_dir: Path = status["data_dir"]+ final_venv: Path = status["venv"]+ staged = data_dir / f".venv.next-{os.getpid()}"+ backup = data_dir / ".venv.previous"+ temp_state = data_dir / ".runtime-state.next"+ shutil.rmtree(staged, ignore_errors=True)+ env = _safe_env(status)+ browser_ready = False+ previous_moved = False+ swapped = False+ committed = False+ had_previous = final_venv.exists()+ try:+ with SetupLock(data_dir / ".setup.lock"):+ print("Creating isolated Claude SEO environment...")+ _run_checked([sys.executable, "-m", "venv", str(staged)], env=env, stage="virtual environment creation")+ staged_python = _venv_python(staged)+ _run_checked(+ [str(staged_python), "-m", "pip", "install", "--disable-pip-version-check", "-r", str(root / "requirements.txt")],+ env=env,+ stage="dependency installation",+ )+ if not args.skip_browser:+ try:+ _run_checked(+ [str(staged_python), "-m", "playwright", "install", "chromium"],+ env=env,+ stage="Chromium installation",+ )+ browser_ready = True+ except RuntimeError as exc:+ print(f"Browser setup incomplete: {exc}", file=sys.stderr)+ _run_checked(+ [str(staged_python), "-c", "import bs4, lxml, playwright, requests, trafilatura"],+ env=env,+ stage="runtime import validation",+ )+ shutil.rmtree(backup, ignore_errors=True)+ if final_venv.exists():+ final_venv.replace(backup)+ previous_moved = True+ staged.replace(final_venv)+ swapped = True+ state = dict(status["expected"])+ state["browser_ready"] = browser_ready+ temp_state.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ temp_state.replace(_state_path(data_dir))+ committed = True+ shutil.rmtree(backup, ignore_errors=True)+ except (OSError, RuntimeError) as exc:+ shutil.rmtree(staged, ignore_errors=True)+ temp_state.unlink(missing_ok=True)+ if not committed:+ if swapped:+ shutil.rmtree(final_venv, ignore_errors=True)+ if previous_moved and had_previous and backup.exists():+ backup.replace(final_venv)+ print(f"Claude SEO setup failed: {_redact(str(exc))}", file=sys.stderr)+ return 1+ if browser_ready or args.skip_browser:+ print("Claude SEO runtime is ready.")+ return 0+ print("Core runtime is ready, but Chromium is unavailable. Run setup again to enable rendered-page features.", file=sys.stderr)+ return 10+++def _resolve_script(root: Path, name: str, extension: str | None) -> Path:+ if not SCRIPT_NAME_RE.fullmatch(name):+ raise ValueError("script must be a bundled Python script basename")+ if extension:+ if not EXTENSION_NAME_RE.fullmatch(extension):+ raise ValueError("invalid extension name")+ scripts_dir = root / "extensions" / extension / "scripts"+ if not scripts_dir.is_dir() and extension in MANUAL_EXTENSION_SKILLS:+ scripts_dir = root.parent / MANUAL_EXTENSION_SKILLS[extension] / "scripts"+ else:+ if name not in ALLOWED_CORE_SCRIPTS:+ raise ValueError("script is not in the bundled runtime allowlist")+ scripts_dir = root / "scripts"+ candidate = (scripts_dir / name).resolve()+ scripts_root = scripts_dir.resolve()+ if candidate.parent != scripts_root or not candidate.is_file() or candidate == Path(__file__).resolve():+ raise ValueError("script is not in the bundled runtime allowlist")+ return candidate+++def command_run(args: argparse.Namespace) -> int:+ root = _root()+ try:+ script = _resolve_script(root, args.script, args.extension)+ except ValueError as exc:+ print(f"Claude SEO runtime: {exc}", file=sys.stderr)+ return 2+ status = _status(root)+ if not status["ready"]:+ print("Claude SEO runtime is not ready. Run `/seo setup` and retry.", file=sys.stderr)+ return 3+ result = subprocess.run(+ [str(status["python_path"]), str(script), *args.script_args],+ env=_safe_env(status),+ )+ if result.returncode < 0:+ os.kill(os.getpid(), -result.returncode)+ return 128 + (-result.returncode)+ return result.returncode+++def command_doctor(args: argparse.Namespace) -> int:+ status = _status(_root())+ public = {+ "ready": status["ready"],+ "mode": status["mode"],+ "plugin_version": status["plugin_version"],+ "python_version": status["python_version"],+ "browser_ready": status["browser_ready"],+ "reasons": status["reasons"],+ }+ if args.json:+ print(json.dumps(public, indent=2, sort_keys=True))+ else:+ print(f"Runtime: {'ready' if public['ready'] else 'setup required'}")+ print(f"Install mode: {public['mode']}")+ print(f"Python: {public['python_version']}")+ print(f"Chromium: {'ready' if public['browser_ready'] else 'not installed'}")+ for reason in public["reasons"]:+ print(f"Reason: {reason}")+ return 0 if status["ready"] else 3+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="claude-seo", description="Claude SEO managed Python runtime")+ sub = parser.add_subparsers(dest="command", required=True)+ setup = sub.add_parser("setup", help="create or refresh the isolated runtime")+ setup.add_argument("--skip-browser", action="store_true")+ setup.set_defaults(func=command_setup)+ doctor = sub.add_parser("doctor", help="check runtime readiness without changing it")+ doctor.add_argument("--json", action="store_true")+ doctor.set_defaults(func=command_doctor)+ run = sub.add_parser("run", help="run one bundled Python script")+ run.add_argument("--extension")+ run.add_argument("script")+ run.add_argument("script_args", nargs=argparse.REMAINDER)+ run.set_defaults(func=command_run)+ return parser+++def main(argv: list[str] | None = None) -> int:+ _configure_utf8()+ args = build_parser().parse_args(argv)+ try:+ return int(args.func(args))+ except (OSError, RuntimeError, ValueError) as exc:+ print(f"Claude SEO runtime failed: {_redact(str(exc))}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/sitemap_discovery.py b/scripts/sitemap_discovery.pynew file mode 100644index 0000000..47b237b--- /dev/null+++ b/scripts/sitemap_discovery.py@@ -0,0 +1,291 @@+#!/usr/bin/env python3+"""Discover sitemaps through robots.txt and common locations safely.++Every network request uses the repository's DNS-pinned URL safety layer. The+helper accepts cross-host Sitemap directives because the sitemap protocol+allows them, but validates each target independently before connecting.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import sys+from urllib.parse import urlparse, urlunparse++import requests+from lxml import etree++_SCRIPTS = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++from url_safety import URLSafetyError, safe_requests_session, validate_url # noqa: E402++COMMON_PATHS = (+ "/sitemap.xml",+ "/sitemap_index.xml",+ "/sitemap-index.xml",+ "/wp-sitemap.xml",+)+MAX_DECLARED = 16+MAX_ROBOTS_BYTES = 1024 * 1024+MAX_SITEMAP_BYTES = 50 * 1024 * 1024+USER_AGENT = "ClaudeSEO/2.2 SitemapDiscovery"+_SITEMAP_LINE = re.compile(r"^\s*sitemap\s*:\s*(\S+)\s*$", re.IGNORECASE)+++def _display_url(url: str) -> tuple[str, bool]:+ """Return a safe-to-display URL with userinfo, query, and fragment removed."""+ parsed = urlparse(url)+ host = parsed.hostname or ""+ try:+ port = parsed.port+ except ValueError:+ port = None+ redacted = True+ else:+ redacted = False+ if port:+ host = f"{host}:{port}"+ clean = urlunparse((parsed.scheme, host, parsed.path or "/", "", "", ""))+ redacted = redacted or bool(parsed.username or parsed.password or parsed.query or parsed.fragment)+ return clean, redacted+++def _origin(url: str) -> str:+ if "://" not in url:+ url = f"https://{url}"+ if not validate_url(url):+ raise ValueError("Target must be a public HTTP or HTTPS URL")+ parsed = urlparse(url)+ netloc = parsed.hostname or ""+ try:+ port = parsed.port+ except ValueError as exc:+ raise ValueError("Target URL contains an invalid port") from exc+ if port:+ netloc = f"{netloc}:{port}"+ return urlunparse((parsed.scheme, netloc, "", "", "", ""))+++def _bounded_fetch(url: str, max_bytes: int) -> dict:+ """Fetch at most max_bytes after decompression without exposing response text."""+ result = {+ "status_code": None,+ "content": b"",+ "content_type": "",+ "final_url": url,+ "too_large": False,+ "error": None,+ }+ try:+ with safe_requests_session(url) as session:+ response = session.get(+ url,+ headers={"User-Agent": USER_AGENT, "Accept": "application/xml,text/xml,text/plain,*/*"},+ timeout=30,+ allow_redirects=True,+ stream=True,+ )+ result["status_code"] = response.status_code+ result["content_type"] = response.headers.get("Content-Type", "")+ result["final_url"] = response.url+ chunks = []+ size = 0+ for chunk in response.iter_content(chunk_size=65536):+ if not chunk:+ continue+ size += len(chunk)+ if size > max_bytes:+ result["too_large"] = True+ break+ chunks.append(chunk)+ result["content"] = b"".join(chunks)+ response.close()+ except URLSafetyError:+ result["error"] = "URL safety validation failed"+ except requests.exceptions.Timeout:+ result["error"] = "Request timed out"+ except requests.exceptions.RequestException:+ result["error"] = "Request failed"+ return result+++def _robots_sitemaps(content: bytes) -> list[str]:+ text = content.decode("utf-8", errors="replace")+ found = []+ for line in text.splitlines():+ match = _SITEMAP_LINE.match(line)+ if match and match.group(1) not in found:+ found.append(match.group(1))+ return found+++def _valid_sitemap_url_syntax(value: str) -> bool:+ """Check a text-sitemap entry without resolving or connecting to its host."""+ if not value or any(char.isspace() for char in value) or "\\" in value:+ return False+ try:+ parsed = urlparse(value)+ _ = parsed.port+ except ValueError:+ return False+ return (+ parsed.scheme.lower() in {"http", "https"}+ and bool(parsed.hostname)+ and parsed.username is None+ and parsed.password is None+ )+++def _sitemap_kind(content: bytes, content_type: str, url: str) -> tuple[str | None, str | None]:+ if not content.strip():+ return None, "empty response"+ if b"<!DOCTYPE" in content.upper():+ return None, "DOCTYPE is not allowed in sitemap XML"++ stripped = content.lstrip()+ if stripped.startswith(b"<"):+ try:+ parser = etree.XMLParser(+ resolve_entities=False,+ no_network=True,+ load_dtd=False,+ recover=False,+ huge_tree=False,+ )+ root = etree.fromstring(content, parser=parser)+ except (etree.XMLSyntaxError, ValueError):+ return None, "invalid XML"+ local = etree.QName(root).localname.lower()+ if local in {"urlset", "sitemapindex"}:+ return local, None+ if local in {"rss", "feed"}:+ return local, None+ return None, "unsupported XML root"++ if "text/plain" in content_type.lower() or urlparse(url).path.lower().endswith(".txt"):+ lines = [line.strip() for line in content.decode("utf-8", errors="replace").splitlines() if line.strip()]+ if len(lines) > 50000:+ return None, "text sitemap exceeds the 50,000 URL protocol limit"+ # Entries are reported only as a sitemap classification, not fetched.+ # Avoid up to 50,000 DNS lookups here; connection-time validation still+ # applies to every sitemap candidate that discovery fetches.+ if lines and all(_valid_sitemap_url_syntax(line) for line in lines):+ return "text", None+ return None, "invalid text sitemap"+ return None, "response is not a supported sitemap format"+++def discover_sitemaps(target_url: str) -> dict:+ result = {+ "target": None,+ "robots_url": None,+ "declared": [],+ "found": [],+ "checked": [],+ "warnings": [],+ "error": None,+ }+ try:+ origin = _origin(target_url)+ except ValueError as exc:+ result["error"] = str(exc)+ return result++ result["target"] = origin+ robots_url = f"{origin}/robots.txt"+ result["robots_url"] = robots_url+ robots = _bounded_fetch(robots_url, MAX_ROBOTS_BYTES)+ declared_raw = []+ if robots["error"]:+ result["warnings"].append("robots.txt could not be fetched safely")+ elif robots["too_large"]:+ result["warnings"].append("robots.txt exceeded the 1 MiB discovery limit")+ elif robots["status_code"] == 200:+ declared_raw = _robots_sitemaps(robots["content"])+ elif robots["status_code"] is not None:+ result["warnings"].append(f"robots.txt returned HTTP {robots['status_code']}")++ if len(declared_raw) > MAX_DECLARED:+ result["warnings"].append(+ f"robots.txt declared more than {MAX_DECLARED} sitemaps; extra entries were not fetched"+ )+ declared_raw = declared_raw[:MAX_DECLARED]++ for item in declared_raw:+ display, redacted = _display_url(item)+ result["declared"].append({"url": display, "query_redacted": redacted})++ candidates = list(declared_raw)+ candidates.extend(f"{origin}{path}" for path in COMMON_PATHS)+ deduped = []+ seen = set()+ for candidate in candidates:+ if candidate not in seen:+ seen.add(candidate)+ deduped.append(candidate)++ target_host = urlparse(origin).hostname+ for candidate in deduped:+ display, query_redacted = _display_url(candidate)+ entry = {+ "url": display,+ "query_redacted": query_redacted,+ "source": "robots.txt" if candidate in declared_raw else "common_path",+ "status_code": None,+ "kind": None,+ "valid": False,+ "error": None,+ }+ if urlparse(candidate).hostname != target_host and candidate in declared_raw:+ entry["cross_host"] = True++ fetched = _bounded_fetch(candidate, MAX_SITEMAP_BYTES)+ entry["status_code"] = fetched["status_code"]+ if fetched["error"]:+ entry["error"] = fetched["error"]+ elif fetched["too_large"]:+ entry["error"] = "Sitemap exceeds the 50 MiB uncompressed protocol limit"+ elif fetched["status_code"] is None or not 200 <= fetched["status_code"] < 300:+ entry["error"] = f"HTTP {fetched['status_code']}" if fetched["status_code"] is not None else "No response"+ else:+ kind, error = _sitemap_kind(+ fetched["content"], fetched["content_type"], fetched["final_url"]+ )+ entry["kind"] = kind+ entry["error"] = error+ entry["valid"] = kind is not None+ if entry["valid"]:+ final_display, final_redacted = _display_url(fetched["final_url"])+ entry["url"] = final_display+ entry["query_redacted"] = query_redacted or final_redacted+ result["found"].append(dict(entry))+ result["checked"].append(entry)++ return result+++def main() -> int:+ parser = argparse.ArgumentParser(description="Discover sitemaps safely")+ parser.add_argument("url", help="Public site URL")+ parser.add_argument("--json", action="store_true", help="Output structured JSON")+ args = parser.parse_args()+ result = discover_sitemaps(args.url)+ if args.json:+ print(json.dumps(result, indent=2))+ elif result["error"]:+ print(f"Error: {result['error']}", file=sys.stderr)+ elif result["found"]:+ for item in result["found"]:+ print(f"{item['url']} ({item['kind']})")+ else:+ print("No valid sitemap found")+ return 1 if result["error"] else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/sync_flow.py b/scripts/sync_flow.pyindex fdccd7e..8a0ccc7 100644--- a/scripts/sync_flow.py+++ b/scripts/sync_flow.py@@ -131,7 +131,7 @@ def api_get(path, ref, headers):raise ValueError(f"Response for {path!r} exceeds {_SIZE_LIMIT} bytes")return json.loads(data)except urllib.error.HTTPError as exc:- if exc.code == 403 and "Authorization" not in headers:+ if exc.code in (403, 429) and "Authorization" not in headers:authed = _authed_headers()if "Authorization" in authed:return api_get(path, ref, authed)diff --git a/skills/seo-audit/SKILL.md b/skills/seo-audit/SKILL.mdindex d31a010..eb0d280 100644--- a/skills/seo-audit/SKILL.md+++ b/skills/seo-audit/SKILL.md@@ -6,7 +6,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -14,7 +14,7 @@ metadata:## Process-1. **Render homepage**: use `python3 scripts/render_page.py <url> --mode auto --json` to capture raw HTML, rendered HTML, extracted text, SPA status, and accessibility data when needed+1. **Render homepage**: use `claude-seo run render_page.py <url> --mode auto --json` to capture raw HTML, rendered HTML, extracted text, SPA status, and accessibility data when needed2. **Detect business type**: analyze homepage signals per seo orchestrator3. **Crawl site**: follow internal links up to 500 pages, respect robots.txt4. **Delegate to subagents** (if available, otherwise run inline sequentially):@@ -27,11 +27,11 @@ metadata:- `seo-geo` -- AI crawler access, llms.txt, citability, brand mention signals- `seo-local` -- GBP signals, NAP consistency, reviews, local schema, industry-specific local factors (spawn when Local Service industry detected: brick-and-mortar, SAB, or hybrid business type)- `seo-maps` -- Geo-grid rank tracking, GBP audit, review intelligence, competitor radius mapping (spawn when Local Service detected AND DataForSEO MCP available)- - `seo-google` -- CWV field data (CrUX), URL indexation (GSC), organic traffic (GA4) (spawn when Google API credentials detected via `python3 scripts/google_auth.py --check`)- - `seo-backlinks` -- Backlink profile data: DA/PA, referring domains, anchor text, toxic links (spawn when Moz or Bing API credentials detected via `python3 scripts/backlinks_auth.py --check`, or always include Common Crawl domain-level metrics)+ - `seo-google` -- CWV field data (CrUX), URL indexation (GSC), organic traffic (GA4) (spawn when Google API credentials detected via `claude-seo run google_auth.py --check`)+ - `seo-backlinks` -- Backlink profile data: DA/PA, referring domains, anchor text, toxic links (spawn when Moz or Bing API credentials detected via `claude-seo run backlinks_auth.py --check`, or always include Common Crawl domain-level metrics)- `seo-cluster` -- Semantic clustering analysis (spawn when content strategy signals detected: blog, pillar pages, topic clusters)- `seo-sxo` -- Search experience analysis: page-type mismatch, user stories, persona scoring (always include in full audits)- - `seo-drift` -- Drift analysis: compare against stored baseline (spawn when drift baseline exists for the URL via `python3 scripts/drift_history.py <url>`)+ - `seo-drift` -- Drift analysis: compare against stored baseline (spawn when drift baseline exists for the URL via `claude-seo run drift_history.py <url>`)- `seo-ecommerce` -- Product schema, marketplace intelligence (spawn when E-commerce industry detected)5. **Score** -- aggregate into SEO Health Score (0-100)6. **Persist audit artifacts** -- write all outputs under `{domain}-audit/`@@ -55,11 +55,11 @@ Delay between requests: 1 second- `{domain}-audit/audit-data.json`: Structured audit envelope for report generation- `{domain}-audit/findings/*.md`: Per-category specialist findings (`technical.md`, `content.md`, `schema.md`, `performance.md`, `visual.md`, etc.)- `{domain}-audit/screenshots/`: Desktop + mobile captures (if Playwright available)-- **PDF Report** (recommended): Generate a professional A4 PDF using `scripts/google_report.py --type full --data {domain}-audit/audit-data.json --domain <domain> --output-dir {domain}-audit/`. This produces a white-cover enterprise report with TOC, executive summary, charts (Lighthouse gauges, query bars, index donut), metric cards, threshold tables, prioritized recommendations with effort estimates, and implementation roadmap. Always offer PDF generation after completing an audit.+- **PDF Report** (recommended): Generate a professional A4 PDF using `claude-seo run google_report.py --type full --data {domain}-audit/audit-data.json --domain <domain> --output-dir {domain}-audit/`. This produces a white-cover enterprise report with TOC, executive summary, charts (Lighthouse gauges, query bars, index donut), metric cards, threshold tables, prioritized recommendations with effort estimates, and implementation roadmap. Always offer PDF generation after completing an audit.## Structured Audit Data Envelope-Write `{domain}-audit/audit-data.json` with this shape so `python3 scripts/google_report.py --type full --data {domain}-audit/audit-data.json --domain <domain> --output-dir {domain}-audit/` can generate a report even when Google API data is unavailable:+Write `{domain}-audit/audit-data.json` with this shape so `claude-seo run google_report.py --type full --data {domain}-audit/audit-data.json --domain <domain> --output-dir {domain}-audit/` can generate a report even when Google API data is unavailable:```json{@@ -170,7 +170,7 @@ If DataForSEO MCP tools are available, spawn the `seo-dataforseo` agent alongsid## Google API Integration (Optional)-If Google API credentials are configured (`python3 scripts/google_auth.py --check`), spawn the `seo-google` agent to enrich the audit with real Google field data: CrUX Core Web Vitals (replaces lab-only estimates), GSC URL indexation status, search performance (clicks, impressions, CTR), and GA4 organic traffic trends. The Performance (CWV) category score benefits most from field data.+If Google API credentials are configured (`claude-seo run google_auth.py --check`), spawn the `seo-google` agent to enrich the audit with real Google field data: CrUX Core Web Vitals (replaces lab-only estimates), GSC URL indexation status, search performance (clicks, impressions, CTR), and GA4 organic traffic trends. The Performance (CWV) category score benefits most from field data.## Error Handlingdiff --git a/skills/seo-backlinks/SKILL.md b/skills/seo-backlinks/SKILL.mdindex 1d75f9f..fa3a7c4 100644--- a/skills/seo-backlinks/SKILL.md+++ b/skills/seo-backlinks/SKILL.md@@ -7,7 +7,7 @@ license: MITcompatibility: "Free: Common Crawl + verify always available. Optional: Moz API, Bing Webmaster (free signup). Premium: DataForSEO extension."metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -18,12 +18,12 @@ metadata:Before analysis, detect available data sources:1. **DataForSEO MCP** (premium): Check if `dataforseo_backlinks_summary` tool is available-2. **Moz API** (free signup): `python3 scripts/backlinks_auth.py --check moz --json`-3. **Bing Webmaster** (free signup): `python3 scripts/backlinks_auth.py --check bing --json`+2. **Moz API** (free signup): `claude-seo run backlinks_auth.py --check moz --json`+3. **Bing Webmaster** (free signup): `claude-seo run backlinks_auth.py --check bing --json`4. **Common Crawl** (always available): Domain-level graph with PageRank5. **Verification Crawler** (always available): Checks if known backlinks still exist-Run `python3 scripts/backlinks_auth.py --check --json` to detect all sources at once.+Run `claude-seo run backlinks_auth.py --check --json` to detect all sources at once.If no sources are configured beyond the always-available tier:- Still produce a report using Common Crawl domain metrics@@ -48,9 +48,9 @@ Produce all 7 sections below. Each section lists data sources in preference orde**DataForSEO:** `dataforseo_backlinks_summary` → total backlinks, referring domains, domain rank, follow ratio, trend.-**Moz API:** `python3 scripts/moz_api.py metrics <url> --json` → Domain Authority, Page Authority, Spam Score, linking root domains, external links.+**Moz API:** `claude-seo run moz_api.py metrics <url> --json` → Domain Authority, Page Authority, Spam Score, linking root domains, external links.-**Common Crawl:** `python3 scripts/commoncrawl_graph.py <domain> --json` → PageRank, harmonic centrality, and low-confidence rank/presence data.+**Common Crawl:** `claude-seo run commoncrawl_graph.py <domain> --json` → PageRank, harmonic centrality, and low-confidence rank/presence data.**Scoring:**@@ -65,9 +65,9 @@ Produce all 7 sections below. Each section lists data sources in preference orde**DataForSEO:** `dataforseo_backlinks_anchors`-**Moz API:** `python3 scripts/moz_api.py anchors <url> --json`+**Moz API:** `claude-seo run moz_api.py anchors <url> --json`-**Bing Webmaster:** `python3 scripts/bing_webmaster.py links <url> --json` (extract anchor text from link details)+**Bing Webmaster:** `claude-seo run bing_webmaster.py links <url> --json` (extract anchor text from link details)**Healthy distribution benchmarks:**@@ -86,9 +86,9 @@ Flag if exact-match anchors exceed 15% as a review heuristic; it may indicate un**DataForSEO:** `dataforseo_backlinks_referring_domains`-**Moz API:** `python3 scripts/moz_api.py domains <url> --json` → domains with DA scores+**Moz API:** `claude-seo run moz_api.py domains <url> --json` → domains with DA scores-**Common Crawl:** `python3 scripts/commoncrawl_graph.py <domain> --json` → domain-level rank/presence data, no verified referring-domain counts+**Common Crawl:** `claude-seo run commoncrawl_graph.py <domain> --json` → domain-level rank/presence data, no verified referring-domain countsAnalyze:- **TLD distribution**: .edu, .gov, .org = high authority. Excessive .xyz, .info = low quality@@ -100,9 +100,9 @@ Analyze:**DataForSEO:** `dataforseo_backlinks_bulk_spam_score` + toxic patterns from reference-**Moz API:** Raw vendor spam_score from `python3 scripts/moz_api.py metrics <url> --json` (source-label the value; apply thresholds only if verified against current Moz docs)+**Moz API:** Raw vendor spam_score from `claude-seo run moz_api.py metrics <url> --json` (source-label the value; apply thresholds only if verified against current Moz docs)-**Verification Crawler:** `python3 scripts/verify_backlinks.py --target <url> --links <file> --json` (verify suspicious links still exist)+**Verification Crawler:** `claude-seo run verify_backlinks.py --target <url> --links <file> --json` (verify suspicious links still exist)**High-risk indicators (flag immediately):**- Links from known PBN (Private Blog Network) domains@@ -124,7 +124,7 @@ Load `../seo/references/backlink-quality.md` for the full 30 toxic patterns and**DataForSEO:** `dataforseo_backlinks_backlinks` with target type "page"-**Moz API:** `python3 scripts/moz_api.py pages <domain> --json`+**Moz API:** `claude-seo run moz_api.py pages <domain> --json`Find:- Which pages attract the most backlinks@@ -136,9 +136,11 @@ Find:**DataForSEO:** `dataforseo_backlinks_referring_domains` for both domains, then compare-**Bing Webmaster (unique!):** `python3 scripts/bing_webmaster.py compare <url1> <url2> --json`: the only free tool with built-in competitor comparison+**Bing Webmaster:** `claude-seo run bing_webmaster.py compare <url1> <url2> --json`+only when both properties are registered and accessible to the same Bing API+account. For arbitrary competitors, use DataForSEO, Moz, or Common Crawl.-**Moz API:** Compare DA/PA between domains via `python3 scripts/moz_api.py metrics <url> --json` for each+**Moz API:** Compare DA/PA between domains via `claude-seo run moz_api.py metrics <url> --json` for eachOutput:- Domains linking to competitor but NOT to target = link building opportunities@@ -150,7 +152,7 @@ Output:**DataForSEO only:** `dataforseo_backlinks_backlinks` with date filters for 30/60/90 day changes-**Verification Crawler:** For known links, verify current status with `python3 scripts/verify_backlinks.py --target <url> --links <file> --json`+**Verification Crawler:** For known links, verify current status with `claude-seo run verify_backlinks.py --target <url> --links <file> --json`**Note:** Free sources cannot track new/lost links over time. If this section is requested without DataForSEO, inform the user: "Link velocity tracking requires the DataForSEO extension. Free sources provide point-in-time snapshots only."@@ -218,7 +220,8 @@ the reality is we simply lack data.**Fallback cascade:**1. DataForSEO available? → Use as primary (confidence: 1.0)2. Moz configured? → Use for DA/PA/spam/anchors (confidence: 0.85)-3. Bing configured? → Use for links/competitor comparison (confidence: 0.70)+3. Bing configured? → Use for registered-property links and comparison only+ when both properties are accessible (confidence: 0.70)4. Always: Common Crawl for domain-level metrics (confidence: 0.50)5. Always: Verification crawler for known link checks (confidence: 0.95)6. Nothing works? → "Run `/seo backlinks setup` to configure free APIs"diff --git a/skills/seo-cluster/SKILL.md b/skills/seo-cluster/SKILL.mdindex 5aa83b1..26e08bf 100644--- a/skills/seo-cluster/SKILL.md+++ b/skills/seo-cluster/SKILL.md@@ -14,7 +14,7 @@ license: MITmetadata:author: AgriciDanieloriginal_author: "Lutfiya Miller (Pro Hub Challenge Winner)"- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -80,7 +80,7 @@ the full algorithm.- Skip pairs where both are long-tail variants of the same head term (assume same cluster)**DataForSEO integration:** If DataForSEO MCP is available, use `serp_organic_live_advanced`-instead of WebSearch for SERP data. Run `python3 scripts/dataforseo_costs.py check serp_organic_live_advanced --count N`+instead of WebSearch for SERP data. Run `claude-seo run dataforseo_costs.py check serp_organic_live_advanced --count N`before each batch. If `"status": "needs_approval"`, show cost estimate and ask user.If `"status": "blocked"`, fall back to WebSearch.@@ -312,7 +312,7 @@ After cluster planning or execution completes, offer:## Security-- All URLs fetched via `python3 scripts/render_page.py <url> --mode auto` (SPA-aware SSRF protection via `url_safety`)+- All URLs fetched via `claude-seo run render_page.py <url> --mode auto` (SPA-aware SSRF protection via `url_safety`)- No credentials stored or transmitted- Output files contain no PII or API keys- DataForSEO cost checks run before every API calldiff --git a/skills/seo-cluster/references/hub-spoke-architecture.md b/skills/seo-cluster/references/hub-spoke-architecture.mdindex e0878a5..372c4bc 100644--- a/skills/seo-cluster/references/hub-spoke-architecture.md+++ b/skills/seo-cluster/references/hub-spoke-architecture.md@@ -135,7 +135,7 @@ coverage; spokes provide deep dives into subtopics.```json{- "version": "2.2.3",+ "version": "2.2.4","seed_keyword": "string","created_at": "ISO-8601","pillar": {diff --git a/skills/seo-competitor-pages/SKILL.md b/skills/seo-competitor-pages/SKILL.mdindex 7b201fb..a155d72 100644--- a/skills/seo-competitor-pages/SKILL.md+++ b/skills/seo-competitor-pages/SKILL.md@@ -11,7 +11,7 @@ argument-hint: "[url or generate] [competitor]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-content-brief/references/page-type-templates.md b/skills/seo-content-brief/references/page-type-templates.mdindex ae97388..ca7b9d5 100644--- a/skills/seo-content-brief/references/page-type-templates.md+++ b/skills/seo-content-brief/references/page-type-templates.md@@ -18,7 +18,7 @@ Select the template that matches the page type. Adapt sections based on the spec| FAQ | Capture PAA traffic | 5-8 questions, 40-60 words each, FS target || CTA | Convert | Clear action, reduce risk (free consult, no obligation) |-**Schema:** Service + FAQPage + LocalBusiness (if location-specific). FAQPage no longer produces Google FAQ rich results.+**Schema:** Service + LocalBusiness (if location-specific). Do not add FAQPage for Google visibility; no AI or ranking benefit is confirmed.**Primary keyword placement:** H1, first 100 words, one H2, URL slug, meta title## Blog Post@@ -34,7 +34,7 @@ Select the template that matches the page type. Adapt sections based on the spec| FAQ | Capture long-tail traffic | 5 questions from gap analysis || CTA to relevant service | Convert intent | Contextual link, not hard sell |-**Schema:** Article + FAQPage. FAQPage no longer produces Google FAQ rich results.+**Schema:** Article. Do not add FAQPage for Google visibility; no AI or ranking benefit is confirmed.**Primary keyword placement:** H1, first 100 words, URL slug, meta title, one image alt text## Case Study@@ -67,7 +67,7 @@ Select the template that matches the page type. Adapt sections based on the spec| FAQ | Capture variations | 5-8 questions || CTA | Convert | Clear next step |-**Schema:** Service + BreadcrumbList + FAQPage. FAQPage no longer produces Google FAQ rich results.+**Schema:** Service + BreadcrumbList. Do not add FAQPage for Google visibility; no AI or ranking benefit is confirmed.**Primary keyword:** Category name, in H1, title, URL, first paragraph**Site Structure Rule:** MUST include every relevant sub-page from the sitemap.@@ -85,7 +85,7 @@ Select the template that matches the page type. Adapt sections based on the spec| Objection handling / FAQ | Remove doubts | 4-6 common objections answered || Final CTA | Convert | Repeat the offer |-**Schema:** WebPage + FAQPage. FAQPage no longer produces Google FAQ rich results.+**Schema:** WebPage. Do not add FAQPage for Google visibility; no AI or ranking benefit is confirmed.**Primary keyword:** Offer or outcome, in H1, title, hero subheading## FAQ Page@@ -97,7 +97,7 @@ Select the template that matches the page type. Adapt sections based on the spec| 8-15 questions | Grouped by subtopic | Each answered in 40-60 words, FS target for each || CTA after last question | Convert | Contextual next step |-**Schema:** FAQPage (every Q&A as mainEntity). Google retired FAQ rich results for all sites on May 7, 2026, so this no longer produces a SERP rich result. For genuine user Q&A pages, use QAPage instead. See the seo-schema skill for the canonical position.+**Schema:** WebPage. Google retired FAQ rich results for all sites on May 7, 2026, and no AI or ranking benefit is confirmed. Use QAPage only when users can submit answers to a single question. See the seo-schema skill for the canonical position.**Primary keyword:** In H1 as "[Topic]: Frequently Asked Questions", in first answer## Location Pagediff --git a/skills/seo-content/SKILL.md b/skills/seo-content/SKILL.mdindex 658ed77..750c792 100644--- a/skills/seo-content/SKILL.md+++ b/skills/seo-content/SKILL.md@@ -9,7 +9,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-dataforseo/SKILL.md b/skills/seo-dataforseo/SKILL.mdindex df7e109..326d452 100644--- a/skills/seo-dataforseo/SKILL.md+++ b/skills/seo-dataforseo/SKILL.md@@ -13,7 +13,7 @@ license: MITcompatibility: "Requires DataForSEO MCP server"metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -48,7 +48,7 @@ DataForSEO charges per API call. Be efficient:**Before every DataForSEO MCP call**, run cost estimation:```-python3 scripts/dataforseo_costs.py check <endpoint> [--count N]+claude-seo run dataforseo_costs.py check <endpoint> [--count N]```- If `"status": "approved"` → proceed with the API call@@ -57,7 +57,7 @@ python3 scripts/dataforseo_costs.py check <endpoint> [--count N]**After each API call completes**, log the cost:```-python3 scripts/dataforseo_costs.py log <endpoint> <actual_cost>+claude-seo run dataforseo_costs.py log <endpoint> <actual_cost>```**User commands for cost management:**diff --git a/skills/seo-dataforseo/references/cost-tiers.md b/skills/seo-dataforseo/references/cost-tiers.mdindex 0c8364c..1734a28 100644--- a/skills/seo-dataforseo/references/cost-tiers.md+++ b/skills/seo-dataforseo/references/cost-tiers.md@@ -31,7 +31,7 @@| **Aggressive** | $50.00 | $2.00 | threshold | Agency bulk work || **Unlimited** | $999.00 | -- | none | Trusted pipelines |-Configure with: `python3 scripts/dataforseo_costs.py config --mode threshold --threshold 0.50 --daily-limit 10.00`+Configure with: `claude-seo run dataforseo_costs.py config --mode threshold --threshold 0.50 --daily-limit 10.00`## Cost Reduction Tips@@ -44,11 +44,11 @@ Configure with: `python3 scripts/dataforseo_costs.py config --mode threshold --t## Approval FlowBefore any DataForSEO MCP call:-1. Run `python3 scripts/dataforseo_costs.py check <endpoint> [--count N]`+1. Run `claude-seo run dataforseo_costs.py check <endpoint> [--count N]`2. If `status: "approved"` → proceed3. If `status: "needs_approval"` → show cost to user, ask to confirm4. If `status: "blocked"` → inform user daily limit would be exceeded-5. After call completes, log: `python3 scripts/dataforseo_costs.py log <endpoint> <cost>`+5. After call completes, log: `claude-seo run dataforseo_costs.py log <endpoint> <cost>`## Warn Endpointsdiff --git a/skills/seo-drift/SKILL.md b/skills/seo-drift/SKILL.mdindex bf39fde..56757a2 100644--- a/skills/seo-drift/SKILL.md+++ b/skills/seo-drift/SKILL.md@@ -12,7 +12,7 @@ license: MITmetadata:author: AgriciDanieloriginal_author: "Dan Colta (Pro Hub Challenge)"- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -103,8 +103,8 @@ Captures the current state of a page and stores it.**Execution:**```bash-python3 scripts/drift_baseline.py <url>-python3 scripts/drift_baseline.py <url> --skip-cwv+claude-seo run drift_baseline.py <url>+claude-seo run drift_baseline.py <url> --skip-cwv```**Output:** JSON with baseline ID, timestamp, URL, and summary of captured elements.@@ -126,16 +126,16 @@ Fetches the current page state and diffs it against the most recent baseline.**Execution:**```bash-python3 scripts/drift_compare.py <url>-python3 scripts/drift_compare.py <url> --baseline-id 5-python3 scripts/drift_compare.py <url> --skip-cwv+claude-seo run drift_compare.py <url>+claude-seo run drift_compare.py <url> --baseline-id 5+claude-seo run drift_compare.py <url> --skip-cwv```**Output:** JSON with all triggered rules, old/new values, severity, and actions.After comparison, offer to generate an HTML report:```bash-python3 scripts/drift_report.py <comparison_json_file> --output drift-report.html+claude-seo run drift_report.py <comparison_json_file> --output drift-report.html```---@@ -146,8 +146,8 @@ Shows all baselines and comparisons for a URL.**Execution:**```bash-python3 scripts/drift_history.py <url>-python3 scripts/drift_history.py <url> --limit 10+claude-seo run drift_history.py <url>+claude-seo run drift_history.py <url> --limit 10```**Output:** JSON array of baselines (newest first) with timestamps and comparison summaries.diff --git a/skills/seo-ecommerce/SKILL.md b/skills/seo-ecommerce/SKILL.mdindex f9b5f53..b26e858 100644--- a/skills/seo-ecommerce/SKILL.md+++ b/skills/seo-ecommerce/SKILL.md@@ -14,7 +14,7 @@ compatibility: "Enhanced with DataForSEO Merchant API (optional)"metadata:author: AgriciDanieloriginal_author: "Matej Marjanovic (Pro Hub Challenge)"- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -42,8 +42,8 @@ Fetch and parse any product page for on-page SEO quality.### Workflow```-1. python3 scripts/render_page.py <url> --mode auto → raw/rendered HTML-2. python3 scripts/parse_html.py --url <url> → SEO elements+1. claude-seo run render_page.py <url> --mode auto → raw/rendered HTML+2. claude-seo run parse_html.py --url <url> → SEO elements3. Analyze product-specific signals (below)```@@ -107,7 +107,7 @@ Live competitive analysis from Google Shopping results.Before EVERY Merchant API call:```bash-python3 scripts/dataforseo_costs.py check merchant_google_products_search+claude-seo run dataforseo_costs.py check merchant_google_products_search```- `"status": "approved"` -- proceed@@ -116,20 +116,20 @@ python3 scripts/dataforseo_costs.py check merchant_google_products_searchAfter each call:```bash-python3 scripts/dataforseo_costs.py log merchant_google_products_search <cost>+claude-seo run dataforseo_costs.py log merchant_google_products_search <cost>```### Workflow```bash# Product search: who sells what at what price-python3 scripts/dataforseo_merchant.py search "<keyword>" --marketplace google+claude-seo run dataforseo_merchant.py search "<keyword>" --marketplace google# Seller analysis: merchant ratings and dominance-python3 scripts/dataforseo_merchant.py sellers "<keyword>"+claude-seo run dataforseo_merchant.py sellers "<keyword>"# Normalize results for analysis-python3 scripts/dataforseo_normalize.py results.json --module merchant+claude-seo run dataforseo_normalize.py results.json --module merchant```### Analysis Outputs@@ -163,7 +163,7 @@ Cross-marketplace intelligence comparing Google Shopping and Amazon.### Cost Guardrail (MANDATORY)```bash-python3 scripts/dataforseo_costs.py check merchant_amazon_products_search+claude-seo run dataforseo_costs.py check merchant_amazon_products_search```Amazon endpoints are in the `warn_endpoints` set -- always requires user approval.@@ -172,10 +172,10 @@ Amazon endpoints are in the `warn_endpoints` set -- always requires user approva```bash# Amazon product search-python3 scripts/dataforseo_merchant.py search "<keyword>" --marketplace amazon+claude-seo run dataforseo_merchant.py search "<keyword>" --marketplace amazon# Cross-marketplace comparison-python3 scripts/dataforseo_merchant.py compare "<keyword>"+claude-seo run dataforseo_merchant.py compare "<keyword>"```### Cross-Marketplace Report@@ -321,10 +321,10 @@ capability examples, and the relationship to AP2 (Agent Payments Protocol).```bash# Discover and validate the UCP profile-python3 scripts/ucp_check.py https://store.example.com --json+claude-seo run ucp_check.py https://store.example.com --json# With endpoint reachability probes (HEAD each declared capability)-python3 scripts/ucp_check.py https://store.example.com --probe-endpoints --json+claude-seo run ucp_check.py https://store.example.com --probe-endpoints --json```The script returns: profile presence, version, declared capabilities,diff --git a/skills/seo-flow/SKILL.md b/skills/seo-flow/SKILL.mdindex cb8819e..e0df635 100644--- a/skills/seo-flow/SKILL.md+++ b/skills/seo-flow/SKILL.md@@ -11,7 +11,7 @@ argument-hint: "[stage] [url|topic]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -82,7 +82,7 @@ Load prompt files on demand, only for the stage the user requests.2. Display the full index: all 41 prompts with stage, name, trigger conditions### On `/seo flow sync`-1. Run: `python3 scripts/sync_flow.py`+1. Run: `claude-seo run sync_flow.py`2. Display the JSON summary (files added, updated, unchanged)3. Show attribution notice after sync completesdiff --git a/skills/seo-geo/SKILL.md b/skills/seo-geo/SKILL.mdindex 42b8347..8a3e64d 100644--- a/skills/seo-geo/SKILL.md+++ b/skills/seo-geo/SKILL.md@@ -13,7 +13,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-google/SKILL.md b/skills/seo-google/SKILL.mdindex 38b9140..9fe3a90 100644--- a/skills/seo-google/SKILL.md+++ b/skills/seo-google/SKILL.md@@ -12,7 +12,7 @@ argument-hint: "[command] [url|property]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -29,7 +29,7 @@ service account -- run `/seo google setup` for step-by-step instructions.Before executing any command, check credentials:```bash-python3 scripts/google_auth.py --check --json+claude-seo run google_auth.py --check --json```Config file: `~/.config/claude-seo/google-api.json`@@ -89,7 +89,7 @@ Always communicate the detected tier before running commands.Combined Lighthouse lab data + CrUX field data.-**Script:** `python3 scripts/pagespeed_check.py <url> --json`+**Script:** `claude-seo run pagespeed_check.py <url> --json`**Reference:** `references/pagespeed-crux-api.md`**Default:** Both mobile + desktop strategies, all Lighthouse categories.@@ -100,13 +100,13 @@ Chrome user metrics). CrUX tries URL-level first, falls back to origin-level.CrUX field data only (no Lighthouse run). Faster.-**Script:** `python3 scripts/pagespeed_check.py <url> --crux-only --json`+**Script:** `claude-seo run pagespeed_check.py <url> --crux-only --json`### `/seo google crux-history <url>`25-week CrUX History trends. Shows whether CWV metrics are improving, stable, or degrading.-**Script:** `python3 scripts/crux_history.py <url> --json`+**Script:** `claude-seo run crux_history.py <url> --json`**Reference:** `references/pagespeed-crux-api.md`Output includes per-metric trend direction, percentage change, and weekly p75 values.@@ -119,11 +119,15 @@ Output includes per-metric trend direction, percentage change, and weekly p75 vaSearch Analytics: clicks, impressions, CTR, position for last 28 days.-**Script:** `python3 scripts/gsc_query.py --property <property> --json`+**Script:** `claude-seo run gsc_query.py --property <property> --json`**Reference:** `references/search-console-api.md`**Default:** 28 days, dimensions=query,page, type=web, limit=1000.Includes quick-win detection: queries at position 4-10 with high impressions.+The `totals` block comes from a separate dimensionless aggregate query because+query-level rows can omit anonymized low-volume traffic. Treat totals as+site-wide only when `totals_complete` is true. `--limit` caps total returned+dimension rows, not the size of every pagination request.> **AI surfaces in GSC (2026):**> - **Generative AI performance report** (launched 2026-06-03), a dedicated view of **AI Overviews + AI Mode** visibility. **Impressions only** (no clicks/CTR/position/query); dimensions Pages/Countries/Devices/Dates (Pacific Time); 1,000-row limit; newest data preliminary; a separate Discover gen-AI report also exists. Rolling out to a subset of properties.@@ -134,7 +138,7 @@ Includes quick-win detection: queries at position 4-10 with high impressions.URL Inspection: real indexation status from Google.-**Script:** `python3 scripts/gsc_inspect.py <url> --json`+**Script:** `claude-seo run gsc_inspect.py <url> --json`Returns: verdict (PASS/FAIL), coverage state, robots.txt status, indexing state,page fetch state, canonical selection, mobile usability, rich results.@@ -143,7 +147,7 @@ page fetch state, canonical selection, mobile usability, rich results.Batch inspection from a file (one URL per line). Rate limited to 2,000/day per site.-**Script:** `python3 scripts/gsc_inspect.py --batch <file> --json`+**Script:** `claude-seo run gsc_inspect.py --batch <file> --json`### `/seo google sitemaps <property>`@@ -151,7 +155,7 @@ List submitted sitemaps with status, errors, warnings. Sitemap contents reportsubmitted counts only; URL Inspection API is the indexation truth for whetherspecific URLs are indexed.-**Script:** `python3 scripts/gsc_query.py sitemaps --property <property> --json`+**Script:** `claude-seo run gsc_query.py sitemaps --property <property> --json`---@@ -161,7 +165,7 @@ specific URLs are indexed.Notify Google of a URL update.-**Script:** `python3 scripts/indexing_notify.py <url> --json`+**Script:** `claude-seo run indexing_notify.py <url> --json`**Reference:** `references/indexing-api.md`The Indexing API is officially for JobPosting and BroadcastEvent/VideoObject pages.@@ -171,7 +175,7 @@ Always inform the user of this restriction. Daily quota: 200 publish requests.Batch submit URLs from a file. Tracks quota usage.-**Script:** `python3 scripts/indexing_notify.py --batch <file> --json`+**Script:** `claude-seo run indexing_notify.py --batch <file> --json`---@@ -181,7 +185,7 @@ Batch submit URLs from a file. Tracks quota usage.Organic traffic report: daily sessions, users, pageviews, bounce rate, engagement.-**Script:** `python3 scripts/ga4_report.py --property <id> --json`+**Script:** `claude-seo run ga4_report.py --property <id> --json`**Reference:** `references/ga4-data-api.md`**Default:** 28 days, filtered to Organic Search channel group.@@ -191,7 +195,7 @@ Organic traffic report: daily sessions, users, pageviews, bounce rate, engagemenTop organic landing pages ranked by sessions.-**Script:** `python3 scripts/ga4_report.py --property <id> --report top-pages --json`+**Script:** `claude-seo run ga4_report.py --property <id> --report top-pages --json`---@@ -203,7 +207,7 @@ Some third-party studies report a 0.737 correlation between YouTube mentions andSearch YouTube for videos. Returns title, channel, views, likes, duration.-**Script:** `python3 scripts/youtube_search.py search "<query>" --json`+**Script:** `claude-seo run youtube_search.py search "<query>" --json`**Reference:** `references/youtube-api.md`**Quota:** 100 units per search (10,000 units/day free).@@ -211,7 +215,7 @@ Search YouTube for videos. Returns title, channel, views, likes, duration.Detailed video info + tags + top 10 comments.-**Script:** `python3 scripts/youtube_search.py video <video_id> --json`+**Script:** `claude-seo run youtube_search.py video <video_id> --json`**Quota:** 2 units (video details + comments).---@@ -224,7 +228,7 @@ Google NLP entity/sentiment output for internal content-quality checks. Do not tFull NLP analysis: entities, sentiment, content classification.-**Script:** `python3 scripts/nlp_analyze.py --url <url> --json` or `--text "..."`+**Script:** `claude-seo run nlp_analyze.py --url <url> --json` or `--text "..."`**Reference:** `references/nlp-api.md`**Free tier:** 5,000 units/month. Requires billing enabled on GCP project.@@ -232,7 +236,7 @@ Full NLP analysis: entities, sentiment, content classification.Entity extraction only (faster, less quota).-**Script:** `python3 scripts/nlp_analyze.py --url <url> --features entities --json`+**Script:** `claude-seo run nlp_analyze.py --url <url> --features entities --json`---@@ -244,7 +248,7 @@ Gold-standard keyword volume data. Requires Google Ads account.Generate keyword ideas from seed terms.-**Script:** `python3 scripts/keyword_planner.py ideas "<seed>" --json`+**Script:** `claude-seo run keyword_planner.py ideas "<seed>" --json`**Reference:** `references/keyword-planner-api.md`**Requires:** Ads developer token + customer ID in config (Tier 3).@@ -252,7 +256,7 @@ Generate keyword ideas from seed terms.Search volume for specific keywords (comma-separated).-**Script:** `python3 scripts/keyword_planner.py volume "<kw1>,<kw2>" --json`+**Script:** `claude-seo run keyword_planner.py volume "<kw1>,<kw2>" --json`---@@ -285,7 +289,7 @@ After any analysis command, offer to generate a PDF/HTML report.Generate a professional PDF report with charts and analytics.-**Script:** `python3 scripts/google_report.py --type <type> --data <json> --domain <domain> --format pdf`+**Script:** `claude-seo run google_report.py --type <type> --data <json> --domain <domain> --format pdf`| Type | Input | Output ||------|-------|--------|@@ -296,8 +300,8 @@ Generate a professional PDF report with charts and analytics.**Workflow:**1. Run data collection commands (pagespeed, gsc, inspect-batch, etc.)-2. Save JSON output to file: `python3 scripts/pagespeed_check.py <url> --json > data.json`-3. Generate report: `python3 scripts/google_report.py --type cwv-audit --data data.json --domain <domain>`+2. Save JSON output to file: `claude-seo run pagespeed_check.py <url> --json > data.json`+3. Generate report: `claude-seo run google_report.py --type cwv-audit --data data.json --domain <domain>`**Convention:** After completing analysis, suggest: "Generate a report? Use `/seo google report <type>`"diff --git a/skills/seo-google/references/auth-setup.md b/skills/seo-google/references/auth-setup.mdindex ead57e3..5f36214 100644--- a/skills/seo-google/references/auth-setup.md+++ b/skills/seo-google/references/auth-setup.md@@ -51,8 +51,8 @@ The JSON file looks like:"type": "service_account","project_id": "your-project-id","private_key_id": "...",- "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",- "client_email": "[email protected]",+ "private_key": "<service-account-private-key>",+ "client_email": "<service-account-identifier>","client_id": "...","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token"@@ -106,7 +106,7 @@ Save to `~/.config/claude-seo/google-api.json`:## Step 8: Verify Setup```bash-python3 scripts/google_auth.py --check+claude-seo run google_auth.py --check```Expected output at Tier 2 (full):@@ -117,7 +117,7 @@ Credential Tier: 2 -- Full (API key + Service Account + GA4)[OK] Chrome UX Report (CrUX) API[OK] CrUX History API[OK] Google Search Console API- Service account: [email protected]+ Service account: configured[OK] Google Indexing API v3[OK] GA4 Data API v1beta```diff --git a/skills/seo-google/references/search-console-api.md b/skills/seo-google/references/search-console-api.mdindex a282a46..73e7a2d 100644--- a/skills/seo-google/references/search-console-api.md+++ b/skills/seo-google/references/search-console-api.md@@ -66,6 +66,12 @@- `discover` and `googleNews` types do not support `query` dimension or `position` metric.- Country codes are **ISO 3166-1 alpha-3** (e.g., `USA`, `GBR`, `DEU`).- Pagination: increment `startRow` by `rowLimit` until fewer rows returned.+- `rowLimit` is per API request. The claude-seo `--limit` option is a total+ result cap and requests are paged internally at up to 25,000 rows.+- For accurate site totals, omit `query` and `page` dimensions. Query rows can+ omit anonymized low-volume traffic and must not be summed as site totals.+- Only present totals as authoritative when the script returns+ `"totals_complete": true`.### Rate Limits- 1,200 QPM per userdiff --git a/skills/seo-hreflang/SKILL.md b/skills/seo-hreflang/SKILL.mdindex 56ed014..fd0aac8 100644--- a/skills/seo-hreflang/SKILL.md+++ b/skills/seo-hreflang/SKILL.md@@ -10,7 +10,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-hreflang/references/machine-translation-qa.md b/skills/seo-hreflang/references/machine-translation-qa.mdindex 0fb36a3..7384e7c 100644--- a/skills/seo-hreflang/references/machine-translation-qa.md+++ b/skills/seo-hreflang/references/machine-translation-qa.md@@ -42,7 +42,7 @@ content abuse.- For per-page hreflang validation, stay inside `seo-hreflang`.- For broader scaled-content scoring (entropy of translated pages,AI-pattern detection in body), defer to `seo-content` via- `python3 scripts/content_quality.py`.+ `claude-seo run content_quality.py`.- For "is this translated by Google's own auto-translate widget"detection, look for the `.goog-te-banner-frame` iframe. There is **noper-mechanism exemption**: in June 2025 Google removed thediff --git a/skills/seo-image-gen/SKILL.md b/skills/seo-image-gen/SKILL.mdindex 61931df..ef302e7 100644--- a/skills/seo-image-gen/SKILL.md+++ b/skills/seo-image-gen/SKILL.md@@ -7,7 +7,7 @@ license: MITcompatibility: "Requires nanobanana MCP server"metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-image-gen/references/seo-image-presets.md b/skills/seo-image-gen/references/seo-image-presets.mdindex 44fbd66..69b9fc6 100644--- a/skills/seo-image-gen/references/seo-image-presets.md+++ b/skills/seo-image-gen/references/seo-image-presets.md@@ -121,10 +121,10 @@ preset format (see `references/presets.md` for schema details).## Creating Custom Presets-Users can create their own presets:-```bash-python3 ~/.claude/skills/seo-image-gen/scripts/presets.py create my-brand-```+Users can create their own presets with the installed Banana MCP preset tool.+If the standalone Banana extension is not installed, configure it before using+custom presets. The core claude-seo skill does not assume a local fallback+script or a fixed personal configuration directory.This creates `~/.banana/presets/my-brand.json` with the full schema.Custom presets override SEO defaults when specified.diff --git a/skills/seo-images/SKILL.md b/skills/seo-images/SKILL.mdindex 3879e69..cb4430b 100644--- a/skills/seo-images/SKILL.md+++ b/skills/seo-images/SKILL.md@@ -12,7 +12,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -321,13 +321,13 @@ https://support.google.com/merchants/answer/14743464```bash# Audit a directory for the IPTC label (counts: missing, ai, captured, etc.)-python3 scripts/iptc_ai_label.py audit ./images/ --json+claude-seo run iptc_ai_label.py audit ./images/ --json# Audit a single image-python3 scripts/iptc_ai_label.py audit ./hero.webp --json+claude-seo run iptc_ai_label.py audit ./hero.webp --json# Inject the AI label into an image-python3 scripts/iptc_ai_label.py inject ./ai-hero.webp \+claude-seo run iptc_ai_label.py inject ./ai-hero.webp \--source-type trainedAlgorithmicMedia# Other vocabulary values:diff --git a/skills/seo-local/SKILL.md b/skills/seo-local/SKILL.mdindex b5b0b5b..85cd87c 100644--- a/skills/seo-local/SKILL.md+++ b/skills/seo-local/SKILL.md@@ -13,7 +13,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-maps/SKILL.md b/skills/seo-maps/SKILL.mdindex 8096eb1..29a1de3 100644--- a/skills/seo-maps/SKILL.md+++ b/skills/seo-maps/SKILL.md@@ -14,7 +14,7 @@ license: MITcompatibility: "DataForSEO MCP for Tier 1+, Google Maps API for Tier 2"metadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-page/SKILL.md b/skills/seo-page/SKILL.mdindex 6dcbed9..083bf21 100644--- a/skills/seo-page/SKILL.md+++ b/skills/seo-page/SKILL.md@@ -10,7 +10,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-plan/SKILL.md b/skills/seo-plan/SKILL.mdindex 826cb48..d788c6e 100644--- a/skills/seo-plan/SKILL.md+++ b/skills/seo-plan/SKILL.md@@ -11,7 +11,7 @@ argument-hint: "[business-type]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-programmatic/SKILL.md b/skills/seo-programmatic/SKILL.mdindex 8bb78a6..2c14f7e 100644--- a/skills/seo-programmatic/SKILL.md+++ b/skills/seo-programmatic/SKILL.md@@ -11,7 +11,7 @@ argument-hint: "[url or plan]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-schema/SKILL.md b/skills/seo-schema/SKILL.mdindex 2455c1a..53e89e5 100644--- a/skills/seo-schema/SKILL.md+++ b/skills/seo-schema/SKILL.md@@ -9,7 +9,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-sitemap/SKILL.md b/skills/seo-sitemap/SKILL.mdindex 7911e79..7fd0e64 100644--- a/skills/seo-sitemap/SKILL.md+++ b/skills/seo-sitemap/SKILL.md@@ -9,7 +9,7 @@ argument-hint: "[url or generate]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -17,6 +17,18 @@ metadata:## Mode 1: Analyze Existing Sitemap+Discover candidates before reporting a sitemap missing:++```bash+claude-seo run sitemap_discovery.py <url> --json+```++The helper reads every bounded `Sitemap:` declaration in robots.txt, validates+cross-host targets through the shared SSRF-safe fetch layer, and still probes+common paths when a declared sitemap is stale or invalid. Use only entries in+`found`; preserve declared failures as findings instead of treating a robots.txt+line alone as proof that a sitemap works.+### Validation Checks- Valid XML format- Per-file limit: **≤50,000 URLs AND ≤50MB uncompressed** (whichever is hit first)@@ -125,7 +137,8 @@ Google documents three subtypes with their own rules, validate per-subtype:## Error Handling- **URL unreachable**: Report the HTTP status code and suggest checking if the site is live-- **No sitemap found**: Check common locations (/sitemap.xml, /sitemap_index.xml, robots.txt reference) before reporting "not found"+- **No sitemap found**: Run `sitemap_discovery.py` and report "not found" only+ when its `found` list is empty after declared and common candidates are checked- **Invalid XML format**: Report specific parsing errors with line numbers- **Rate limiting detected**: Back off and report partial results with a note about retry timingdiff --git a/skills/seo-sxo/SKILL.md b/skills/seo-sxo/SKILL.mdindex e669f08..e7c0c93 100644--- a/skills/seo-sxo/SKILL.md+++ b/skills/seo-sxo/SKILL.md@@ -13,7 +13,7 @@ license: MITmetadata:author: AgriciDanieloriginal_author: "Florian Schmitz (Pro Hub Challenge)"- version: "2.2.3"+ version: "2.2.4"category: seo---diff --git a/skills/seo-technical/SKILL.md b/skills/seo-technical/SKILL.mdindex 18efee2..dd4f934 100644--- a/skills/seo-technical/SKILL.md+++ b/skills/seo-technical/SKILL.md@@ -10,7 +10,7 @@ argument-hint: "[url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -20,7 +20,9 @@ metadata:### 1. Crawlability- robots.txt: exists, valid, not blocking important resources-- XML sitemap: exists, referenced in robots.txt, valid format+- XML sitemap: run `claude-seo run sitemap_discovery.py <url> --json`; require a+ valid entry in `found`, and report stale or unsafe robots.txt declarations+ separately from working fallback locations- Noindex tags: intentional vs accidental- Crawl depth: important pages within 3 clicks of homepage- JavaScript rendering: check if critical content requires JS execution@@ -165,7 +167,7 @@ heuristic below. The PSI REST API does not expose it; run via Lighthouse CLI```bash# Render with Playwright + capture accessibility tree, then score-python3 scripts/agent_ux_check.py https://example.com --json+claude-seo run agent_ux_check.py https://example.com --json```The scanner outputs an Agent-UX score (0-100) plus itemized issues:@@ -176,7 +178,7 @@ The scanner outputs an Agent-UX score (0-100) plus itemized issues:The accessibility-tree snapshot uses Playwright's`page.accessibility.snapshot(interesting_only=False)`. To capture the tree-without scoring, use `python3 scripts/render_page.py <url> --a11y-tree --json`.+without scoring, use `claude-seo run render_page.py <url> --a11y-tree --json`.Surface findings as **opportunities**, not failures; don't gate audits on asub-100 Agent-UX score. WebMCP origin-trial/sign-up status needs verification,@@ -210,7 +212,7 @@ If DataForSEO MCP tools are available, use `on_page_instant_pages` for real page## Google API Integration (Optional)-If Google API credentials are configured, use `python3 scripts/pagespeed_check.py <url> --json` for real PSI + CrUX field data (replaces lab-only CWV estimates), `python3 scripts/crux_history.py <url> --json` for 25-week CWV trends, and `python3 scripts/gsc_inspect.py <url> --json` for real indexation status per URL.+If Google API credentials are configured, use `claude-seo run pagespeed_check.py <url> --json` for real PSI + CrUX field data (replaces lab-only CWV estimates), `claude-seo run crux_history.py <url> --json` for 25-week CWV trends, and `claude-seo run gsc_inspect.py <url> --json` for real indexation status per URL.## Error Handlingdiff --git a/skills/seo/SKILL.md b/skills/seo/SKILL.mdindex 6453423..1a77062 100644--- a/skills/seo/SKILL.md+++ b/skills/seo/SKILL.md@@ -6,7 +6,7 @@ argument-hint: "[command] [url]"license: MITmetadata:author: AgriciDaniel- version: "2.2.3"+ version: "2.2.4"category: seo---@@ -14,7 +14,10 @@ metadata:**Invocation:** `/seo $1 $2` where `$1` is the command and `$2` is the URL or argument.-**Scripts:** Located at the plugin root `scripts/` directory.+**Runtime:** Run bundled Python tools through `claude-seo run <script.py>`. Plugin+installs expose this command automatically. Repository users run+`./bin/claude-seo`; manual installers rewrite the command to the isolated+launcher path. Never invoke bundled scripts with a bare Python interpreter.Comprehensive SEO analysis across all industries (SaaS, local services,e-commerce, publishers, agencies). Orchestrates 24 sub-skills (21 core + 1 framework@@ -52,20 +55,31 @@ extension is also installable (see "Optional Extensions" below).| `/seo dataforseo [command]` | Live SEO data via DataForSEO (extension) || `/seo image-gen [use-case] <description>` | AI image generation for SEO assets (extension) || `/seo flow [stage] [url\|topic]` | FLOW framework: evidence-led prompts for Find, Leverage, Optimize, Win, or Local stages |+| `/seo setup` | Explicitly create or refresh the isolated Python runtime and Chromium |+| `/seo doctor` | Check runtime readiness without changing the system |++## Runtime Setup++Run setup only when the user explicitly invokes `/seo setup` or explicitly asks+to repair dependencies. Execute `claude-seo setup`, report core and Chromium+status separately, and do not fall back to global or user package installation.+For diagnosis, execute `claude-seo doctor --json`; its output intentionally omits+absolute paths and environment values. If any `claude-seo run` command reports+that setup is required, suggest `/seo setup` and do not improvise a `pip install`.## Orchestration LogicWhen the user invokes `/seo audit`, delegate to subagents in parallel:1. Detect business type (SaaS, local, ecommerce, publisher, agency, other)2. Spawn subagents: seo-technical, seo-content, seo-schema, seo-sitemap, seo-performance, seo-visual, seo-geo-3. If Google API credentials detected (`python3 scripts/google_auth.py --check`), also spawn seo-google agent+3. If Google API credentials detected (`claude-seo run google_auth.py --check`), also spawn seo-google agent4. If local business detected, also spawn seo-local agent5. If local business detected AND DataForSEO MCP available, also spawn seo-maps agent-6. If backlink APIs detected (`python3 scripts/backlinks_auth.py --check`), also spawn seo-backlinks agent+6. If backlink APIs detected (`claude-seo run backlinks_auth.py --check`), also spawn seo-backlinks agent7. If Firecrawl MCP available, use `firecrawl_map` to discover all site URLs before analysis8. If content strategy signals detected (blog, pillar pages, topic clusters), also spawn seo-cluster agent9. If e-commerce detected, also spawn seo-ecommerce agent-10. If drift baseline exists for this URL (`python3 scripts/drift_history.py <url>`), also spawn seo-drift agent+10. If drift baseline exists for this URL (`claude-seo run drift_history.py <url>`), also spawn seo-drift agent11. Always include seo-sxo in full audits (search experience applies to all sites)12. Collect results and generate unified report with SEO Health Score (0-100)13. **Synthesize via the 10-principle framework** (see "Synthesis Methodology" below), walk PERCEIVE → ANALYZE → VALIDATE → ACT before bucketing findings into Critical / High / Medium / Lowdiff --git a/skills/seo/references/free-backlink-sources.md b/skills/seo/references/free-backlink-sources.mdindex cade8fc..4b14b86 100644--- a/skills/seo/references/free-backlink-sources.md+++ b/skills/seo/references/free-backlink-sources.md@@ -50,10 +50,13 @@ When only Common Crawl is available, cap the maximum health score at 70/100 and- **Endpoint:** `https://ssl.bing.com/webmaster/api.svc/json/`- **Free tier:** Unlimited for verified sites- **Signup:** https://www.bing.com/webmasters (Microsoft account)-- **Unique feature:** Competitor backlink comparison (no other free tool offers this)-- **Data:** Inbound links with anchor text, source URL, discovery date+- **Comparison:** Backlink-domain gaps between two registered properties that+ are accessible to the same API account+- **Data:** Inbound-link source URL, target URL, anchor text, sampled link+ counts, and referring-domain comparison totals- **Script:** `scripts/bing_webmaster.py`-- **Commands:** `links`, `counts`, `compare`+- **Commands:** `links`, `counts`, `compare` (comparison requires both+ properties to be registered to the same API account)- **Blind spots:** Only Bing-indexed pages (~15% of web), verified sites only,no authority metrics, no spam scoring@@ -79,7 +82,8 @@ When only Common Crawl is available, cap the maximum health score at 70/100 andSuggest the paid DataForSEO extension when:- User needs **toxic link detection** beyond Moz's basic Spam Score-- User needs **competitor gap analysis** at scale (Bing only compares verified sites)+- User needs **competitor gap analysis** at scale or against an unregistered+ domain (Bing comparison is limited to properties accessible to the account)- User needs **link velocity trends** (new/lost links over time)- User needs **real-time data** (free sources update monthly at best)- User manages **multiple client sites** (free tier limits are per-account)diff --git a/tests/test_agent_mcp_permissions.py b/tests/test_agent_mcp_permissions.pynew file mode 100644index 0000000..a5fac2b--- /dev/null+++ b/tests/test_agent_mcp_permissions.py@@ -0,0 +1,46 @@+"""MCP agent permission and fail-closed regressions."""++from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+AGENTS = (+ ROOT / "agents" / "seo-dataforseo.md",+ ROOT / "extensions" / "dataforseo" / "agents" / "seo-dataforseo.md",+)+++def _text(path: Path) -> str:+ return path.read_text(encoding="utf-8")+++def test_dataforseo_agent_mirrors_allow_only_sanctioned_mcp_path():+ for path in AGENTS:+ text = _text(path)+ frontmatter = text.split("---", 2)[1]+ tools_line = next(line for line in frontmatter.splitlines() if line.startswith("tools:"))+ assert "mcp__dataforseo__*" in tools_line+ assert "Bash" not in tools_line+++def test_dataforseo_agent_mirrors_fail_closed_without_mcp():+ required = (+ "fail closed",+ "Never inspect credential or",+ "never bypass MCP with curl, raw HTTP, or another client",+ )+ for path in AGENTS:+ text = _text(path)+ for phrase in required:+ assert phrase in text+++def test_dataforseo_agent_bodies_stay_mirrored():+ public_body = _text(AGENTS[0]).split("---", 2)[2]+ extension_body = _text(AGENTS[1]).split("---", 2)[2]+ assert public_body == extension_body+++def test_dataforseo_installers_use_matching_mcp_server_name():+ for rel in ("extensions/dataforseo/install.sh", "extensions/dataforseo/install.ps1"):+ text = _text(ROOT / rel)+ assert "['dataforseo']" in textdiff --git a/tests/test_audit_instructions.py b/tests/test_audit_instructions.pyindex 37317ed..b60fc4e 100644--- a/tests/test_audit_instructions.py+++ b/tests/test_audit_instructions.py@@ -4,14 +4,14 @@ from __future__ import annotationsfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]def test_seo_audit_starts_with_render_page_auto() -> None:text = (REPO_ROOT / "skills" / "seo-audit" / "SKILL.md").read_text(encoding="utf-8")process = text[text.index("## Process"):text.index("## Crawl Configuration")]- assert "scripts/render_page.py" in process+ assert "claude-seo run render_page.py" in process+ assert "python3 scripts/render_page.py" not in processassert "--mode auto" in processassert "scripts/fetch_page.py` to retrieve HTML" not in processdiff --git a/tests/test_banana_install_layout.py b/tests/test_banana_install_layout.pynew file mode 100644index 0000000..d7c6bfb--- /dev/null+++ b/tests/test_banana_install_layout.py@@ -0,0 +1,58 @@+"""Banana script references must match core and standalone install layouts."""++import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+CORE_SKILL = ROOT / "skills" / "seo-image-gen" / "SKILL.md"+CORE_PRESETS = ROOT / "skills" / "seo-image-gen" / "references" / "seo-image-presets.md"+EXTENSION = ROOT / "extensions" / "banana"+EXTENSION_SKILL = EXTENSION / "skills" / "seo-image-gen" / "SKILL.md"+EXTENSION_PRESETS = EXTENSION / "references" / "seo-image-presets.md"+++def _text(path: Path) -> str:+ return path.read_text(encoding="utf-8")+++def _runtime_extension_scripts(text: str) -> set[str]:+ return set(+ re.findall(r"claude-seo run --extension banana ([A-Za-z0-9_]+\.py)", text)+ )+++def test_core_image_skill_does_not_assume_banana_scripts_are_local():+ combined = _text(CORE_SKILL) + _text(CORE_PRESETS)+ assert "${CLAUDE_SKILL_DIR}/scripts/" not in combined+ assert "extensions/banana/scripts/" not in combined+ assert "~/.claude/skills/seo-image-gen/scripts/" not in combined+++def test_standalone_extension_uses_managed_runtime_for_every_script():+ combined = _text(EXTENSION_SKILL) + _text(EXTENSION_PRESETS)+ referenced = _runtime_extension_scripts(combined)+ assert referenced == {+ "batch.py",+ "cost_tracker.py",+ "generate.py",+ "presets.py",+ "setup_mcp.py",+ }+ for script in referenced:+ assert (EXTENSION / "scripts" / script).is_file()+ assert "BANANA_EXTENSION_ROOT" not in combined+ assert "python3" not in combined+ assert "~/.claude/skills/seo-image-gen/scripts/" not in combined+++def test_standalone_installer_copies_scripts_beside_skill_file():+ installer = _text(EXTENSION / "install.sh")+ assert 'mkdir -p "${SKILL_DIR}/scripts" "${SKILL_DIR}/references"' in installer+ assert 'cp "${SOURCE_DIR}/scripts/"*.py "${SKILL_DIR}/scripts/"' in installer+ assert '"$HOME/.claude/skills/seo/bin/claude-seo" run' in installer+++def test_top_level_installer_keeps_extension_scripts_under_core_extension_tree():+ installer = _text(ROOT / "install.sh")+ assert 'mkdir -p "${SKILL_DIR}/extensions/${ext_name}/scripts"' in installer+ assert 'cp -r "${ext_dir}scripts/"* "${SKILL_DIR}/extensions/${ext_name}/scripts/"' in installerdiff --git a/tests/test_bing_webmaster.py b/tests/test_bing_webmaster.pynew file mode 100644index 0000000..6cd12c6--- /dev/null+++ b/tests/test_bing_webmaster.py@@ -0,0 +1,238 @@+"""Bounded Bing Webmaster link regressions for issue #153."""++from __future__ import annotations++import json+import sys+from pathlib import Path+from unittest.mock import Mock, patch++import pytest++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts"))++import bing_webmaster as bing # noqa: E402+++def ok(data, endpoint="test"):+ return {+ "status": "success", "data": data, "error": None,+ "metadata": {"source": "bing_webmaster", "endpoint": endpoint, "timestamp": "now"},+ }+++def error(message="failed"):+ return {"status": "error", "data": None, "error": message, "metadata": {"source": "bing_webmaster"}}+++def count_page(page, total=2):+ return {"d": {"Links": [{"Url": f"https://site.test/p{page}", "Count": page + 2}], "TotalPages": total}}+++def detail_page(page, total=2, source=None):+ source = source or f"https://Ref.Example/path{page}?private=value"+ return {"d": {"Details": [{"Url": source, "AnchorText": "anchor"}], "TotalPages": total}}+++def test_link_counts_pages_to_documented_total():+ calls = []++ def request(endpoint, _key, params):+ calls.append((endpoint, params["page"]))+ return ok(count_page(params["page"], total=2), endpoint)++ with patch.object(bing, "_bing_request", side_effect=request):+ result = bing.get_link_counts("https://site.test/", "placeholder")+ assert result["status"] == "success"+ assert result["data"]["pages_fetched"] == 2+ assert result["data"]["sampled_inbound_link_count"] == 5+ assert result["data"]["complete"] is True+ assert calls == [("GetLinkCounts", 0), ("GetLinkCounts", 1)]+++def test_link_counts_cap_is_explicitly_partial():+ with patch.object(bing, "_bing_request", return_value=ok(count_page(0, total=5))):+ result = bing.get_link_counts("https://site.test/", "placeholder", max_pages=1)+ assert result["status"] == "partial"+ assert result["data"]["complete"] is False+ assert result["data"]["warnings"]+++def test_link_counts_later_failure_preserves_partial_data():+ def request(_endpoint, _key, params):+ return ok(count_page(0, total=2)) if params["page"] == 0 else error()++ with patch.object(bing, "_bing_request", side_effect=request):+ result = bing.get_link_counts("https://site.test/", "placeholder")+ assert result["status"] == "partial"+ assert result["data"]["pages_fetched"] == 1+ assert result["data"]["complete"] is False+++def test_link_counts_first_failure_is_propagated():+ with patch.object(bing, "_bing_request", return_value=error("access denied")):+ result = bing.get_link_counts("https://site.test/", "placeholder")+ assert result["status"] == "error"+ assert result["error"] == "access denied"+++def test_link_details_expands_bounded_pages_and_deduplicates():+ calls = []++ def request(endpoint, _key, params):+ calls.append((endpoint, params["page"]))+ if endpoint == "GetLinkCounts":+ return ok({"d": {"Links": [{"Url": "https://site.test/target?x=secret", "Count": 9}], "TotalPages": 1}})+ return ok(detail_page(params["page"], total=2, source="https://www.Ref.Example/a?token=secret"))++ with patch.object(bing, "_bing_request", side_effect=request):+ result = bing.get_link_details("https://site.test/", "placeholder", max_detail_pages=2)+ assert result["status"] == "success"+ assert result["data"]["complete"] is True+ assert result["data"]["total_returned"] == 1+ dumped = json.dumps(result)+ assert "secret" not in dumped+ assert result["data"]["links"][0]["source_url"] == "https://www.ref.example/a"+ assert calls == [("GetLinkCounts", 0), ("GetUrlLinks", 0), ("GetUrlLinks", 1)]+++def test_link_details_partial_failure_is_not_hollow_success():+ def request(endpoint, _key, params):+ if endpoint == "GetLinkCounts":+ return ok({"d": {"Links": [+ {"Url": "https://site.test/a", "Count": 4},+ {"Url": "https://site.test/b", "Count": 3},+ ], "TotalPages": 1}})+ if params["link"].endswith("a"):+ return ok(detail_page(0, total=1))+ return error()++ with patch.object(bing, "_bing_request", side_effect=request):+ result = bing.get_link_details("https://site.test/", "placeholder")+ assert result["status"] == "partial"+ assert result["data"]["links"]+ assert result["data"]["partial_errors"] == [{"target_url": "https://site.test/b", "page": 0}]+++def test_link_details_all_expansions_fail_as_error():+ def request(endpoint, _key, _params):+ if endpoint == "GetLinkCounts":+ return ok({"d": {"Links": [{"Url": "https://site.test/a", "Count": 4}], "TotalPages": 1}})+ return error()++ with patch.object(bing, "_bing_request", side_effect=request):+ result = bing.get_link_details("https://site.test/", "placeholder")+ assert result["status"] == "error"+ assert result["data"] is None+++def test_link_details_rejects_invalid_caps_without_request():+ with patch.object(bing, "_bing_request") as request:+ result = bing.get_link_details("https://site.test/", "placeholder", page=-1)+ assert result["status"] == "error"+ request.assert_not_called()+++def test_link_details_marks_unvisited_count_pages_partial():+ with patch.object(+ bing,+ "_bing_request",+ side_effect=[+ ok({"d": {"Links": [{"Url": "https://site.test/a", "Count": 4}], "TotalPages": 3}}),+ ok(detail_page(0, total=1)),+ ],+ ):+ result = bing.get_link_details("https://site.test/", "placeholder")+ assert result["status"] == "partial"+ assert result["data"]["complete"] is False+++def test_verified_property_comparison_propagates_second_side_failure():+ first = ok({"complete": True, "links": []})+ with patch.object(bing, "get_link_details", side_effect=[first, error()]):+ result = bing.compare_links("https://a.test", "https://b.test", "placeholder")+ assert result["status"] == "error"+ assert "second property" in result["error"]+++def test_verified_property_comparison_normalizes_referring_hosts():+ first = ok({"complete": True, "links": [{"source_url": "https://www.Shared.test/a"}]})+ second = ok({"complete": True, "links": [+ {"source_url": "https://shared.test/b"},+ {"source_url": "https://only.test/c"},+ ]})+ with patch.object(bing, "get_link_details", side_effect=[first, second]):+ result = bing.compare_links("https://a.test", "https://b.test", "placeholder")+ assert result["status"] == "success"+ assert result["data"]["shared_domains"] == ["shared.test"]+ assert result["data"]["gap_domains"] == ["only.test"]+++def test_bing_request_does_not_mutate_caller_params():+ params = {"siteUrl": "https://site.test/", "page": 0}+ response = Mock(status_code=200, text="{}")+ response.json.return_value = {}++ with patch.object(bing, "_rate_limit"), patch.object(+ bing.requests, "get", return_value=response+ ) as request:+ result = bing._bing_request("GetLinkCounts", "placeholder", params)++ assert result["status"] == "success"+ assert params == {"siteUrl": "https://site.test/", "page": 0}+ sent_params = request.call_args.kwargs["params"]+ assert sent_params is not params+ assert sent_params == {"siteUrl": "https://site.test/", "page": 0, "apikey": "placeholder"}+++def test_runtime_request_error_is_generic_and_contains_no_parameters():+ marker = "placeholder-secret-marker"++ def fail(*_args, **_kwargs):+ raise bing.requests.exceptions.ConnectionError(+ f"https://ssl.bing.test/?apikey={marker}&siteUrl=https://private.test/?token=value"+ )++ with patch.object(bing, "_rate_limit"), patch.object(bing.requests, "get", side_effect=fail):+ result = bing._bing_request("GetLinkCounts", marker, {"siteUrl": "https://private.test/?token=value"})+ dumped = json.dumps(result)+ assert marker not in dumped+ assert "token=value" not in dumped+ assert result["error"] == "Bing Webmaster request failed (ConnectionError)"+++ ("argv", "expected_error"),+ [+ (["bing_webmaster.py", "counts", "https://user:[email protected]/?token=value", "--json"],+ "Invalid or blocked target URL"),+ (["bing_webmaster.py", "counts", "user:[email protected]/?token=value", "--json"],+ "Invalid or blocked target URL"),+ (["bing_webmaster.py", "compare", "site.test",+ "https://user:[email protected]/?token=value", "--json"],+ "Invalid or blocked competitor URL"),+ ],+)+def test_cli_invalid_url_errors_do_not_echo_userinfo_or_query(+ argv, expected_error, capsys+):+ with patch.object(sys, "argv", argv), patch.object(+ bing, "validate_url", side_effect=lambda url: url == "https://site.test"+ ):+ with pytest.raises(SystemExit) as exc:+ bing.main()++ assert exc.value.code == 1+ output = capsys.readouterr().out+ assert expected_error in output+ assert "user:pass" not in output+ assert "token=value" not in output+++def test_removed_endpoints_are_absent_from_runtime_script():+ source = (ROOT / "scripts" / "bing_webmaster.py").read_text(encoding="utf-8")+ removed = "Get" + "LinkDetails"+ misused = "Get" + "UrlTrafficInfo"+ assert removed not in source+ assert misused not in sourcediff --git a/tests/test_contributors.py b/tests/test_contributors.pynew file mode 100644index 0000000..b622103--- /dev/null+++ b/tests/test_contributors.py@@ -0,0 +1,54 @@+"""Attribution consistency for the 2026 issue and pull-request review cycle."""++from __future__ import annotations++import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+CONTRIBUTORS = ROOT / "CONTRIBUTORS.md"++EXPECTED_HANDLES = {+ "wonsukchoi",+ "powehi-ai",+ "maticyorg",+ "GilboBlagins",+ "voipcomjohn",+ "MSADTP",+ "lukababu",+ "kuhlsnu",+ "SENTMarketing",+ "BubblyWolf",+ "mubashirsidiki",+ "mukulcodezz",+ "us",+ "sam-fakhreddine",+ "n-youn9",+ "jonathanlombi-debug",+ "sohilshrestha0",+ "Kickermax",+ "Arul-Raaj",+ "atahan150",+ "maulikvora",+ "fayerman-source",+}+++def test_review_cycle_human_contributors_are_credited_by_public_handle():+ text = CONTRIBUTORS.read_text(encoding="utf-8")+ linked_handles = set(+ re.findall(r"\[@([A-Za-z0-9-]+)\]\(https://github\.com/\1\)", text)+ )+ assert EXPECTED_HANDLES <= linked_handles+++def test_contributors_file_contains_no_email_addresses_or_mail_links():+ text = CONTRIBUTORS.read_text(encoding="utf-8")+ assert "mailto:" not in text.lower()+ assert re.search(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b", text) is None+++def test_review_cycle_excludes_bots_and_promotional_only_issue():+ text = CONTRIBUTORS.read_text(encoding="utf-8")+ assert "dependabot" not in text.lower()+ assert "/issues/155" not in textdiff --git a/tests/test_google_report_full_audit.py b/tests/test_google_report_full_audit.pyindex a3e72df..edd5154 100644--- a/tests/test_google_report_full_audit.py+++ b/tests/test_google_report_full_audit.py@@ -3,8 +3,11 @@from __future__ import annotationsimport os+import runpyimport sys+import builtinsfrom pathlib import Path+from unittest.mock import patch_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")@@ -14,6 +17,68 @@ if _SCRIPTS not in sys.path:import google_report # noqa: E402+def test_module_import_is_safe_without_native_report_dependencies() -> None:+ real_import = builtins.__import__++ def unavailable(name, *args, **kwargs):+ if name.split(".", 1)[0] in {"matplotlib", "weasyprint"}:+ raise ImportError(f"{name} unavailable")+ return real_import(name, *args, **kwargs)++ with patch.object(builtins, "__import__", side_effect=unavailable):+ namespace = runpy.run_path(str(Path(google_report.__file__)))++ assert namespace["plt"] is None+ assert namespace["HTML"] is None+++def test_html_report_without_chart_data_does_not_require_matplotlib(tmp_path: Path) -> None:+ with patch.object(google_report, "plt", None), \+ patch.object(google_report, "np", None), \+ patch.object(google_report, "_CHART_IMPORT_ERROR", ImportError("missing")):+ result = google_report.generate_report(+ "full",+ {"summary": {"health_score": 80}},+ "example.com",+ tmp_path,+ output_format="html",+ )++ assert result["error"] is None+ assert Path(result["files"][0]).is_file()+++def test_chart_report_returns_dependency_error_at_runtime(tmp_path: Path) -> None:+ with patch.object(google_report, "plt", None), \+ patch.object(google_report, "np", None), \+ patch.object(google_report, "_CHART_IMPORT_ERROR", ImportError("missing")):+ result = google_report.generate_report(+ "cwv-audit",+ {"lighthouse_scores": {"performance": 90}},+ "example.com",+ tmp_path,+ output_format="html",+ )++ assert result["files"] == []+ assert "matplotlib and numpy are required" in result["error"]+++def test_pdf_report_returns_dependency_error_at_runtime(tmp_path: Path) -> None:+ with patch.object(google_report, "HTML", None), \+ patch.object(google_report, "_PDF_IMPORT_ERROR", ImportError("missing")):+ result = google_report.generate_report(+ "full",+ {"summary": {"health_score": 80}},+ "example.com",+ tmp_path,+ output_format="pdf",+ )++ assert result["files"] == []+ assert "weasyprint is required" in result["error"]++def test_full_audit_html_includes_summary_categories_and_roadmap(tmp_path: Path) -> None:data = {"summary": {diff --git a/tests/test_gsc_pagination.py b/tests/test_gsc_pagination.pynew file mode 100644index 0000000..f59b311--- /dev/null+++ b/tests/test_gsc_pagination.py@@ -0,0 +1,141 @@+"""GSC total-limit and blank-dimension regressions for issues #130 and #173."""++from __future__ import annotations++import sys+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts"))++import gsc_query # noqa: E402+++class _Exec:+ def __init__(self, response):+ self.response = response++ def execute(self):+ return self.response+++class _SearchAnalytics:+ def __init__(self, available=30000):+ self.available = available+ self.calls = []++ def query(self, siteUrl=None, body=None):+ self.calls.append(dict(body))+ if body.get("dimensions") == []:+ return _Exec({"rows": [{"clicks": 9, "impressions": 90, "ctr": 0.1, "position": 3}]})+ start = body.get("startRow", 0)+ count = max(0, min(body["rowLimit"], self.available - start))+ rows = [+ {"keys": [f"q{start + i}"], "clicks": 1, "impressions": 2, "ctr": 0.5, "position": 4}+ for i in range(count)+ ]+ return _Exec({"rows": rows})+++class _Service:+ def __init__(self, available=30000):+ self.analytics = _SearchAnalytics(available)++ def searchanalytics(self):+ return self.analytics+++def _run(limit, available=30000, dimensions=None):+ service = _Service(available)+ with mock.patch.object(gsc_query, "_build_gsc_service", return_value=service):+ result = gsc_query.query_search_analytics(+ "sc-domain:example.com",+ dimensions=["query"] if dimensions is None else dimensions,+ row_limit=limit,+ )+ return result, service.analytics.calls+++def test_small_limit_is_one_small_request_plus_aggregate():+ result, calls = _run(5)+ assert result["row_count"] == 5+ assert [call["rowLimit"] for call in calls] == [5, 1]+ assert calls[0]["startRow"] == 0+++def test_exact_api_page_limit_does_not_fetch_an_extra_dimension_page():+ result, calls = _run(25000)+ assert result["row_count"] == 25000+ assert [call["rowLimit"] for call in calls] == [25000, 1]+++def test_limit_over_api_page_size_fetches_only_the_remaining_row():+ result, calls = _run(25001)+ assert result["row_count"] == 25001+ assert [call["rowLimit"] for call in calls] == [25000, 1, 1]+ assert calls[1]["startRow"] == 25000+++def test_short_page_stops_before_total_cap():+ result, calls = _run(100, available=7)+ assert result["row_count"] == 7+ assert [call["rowLimit"] for call in calls] == [100, 1]+++def test_invalid_limits_fail_before_building_service():+ with mock.patch.object(gsc_query, "_build_gsc_service") as build:+ for invalid in (0, -1, True):+ result = gsc_query.query_search_analytics("sc-domain:example.com", row_limit=invalid)+ assert result["error"] == "row_limit must be a positive integer"+ build.assert_not_called()+++def test_invalid_programmatic_dimensions_fail_before_building_service():+ invalid_cases = [+ (["query", "unsupported"], "Unsupported GSC dimensions: unsupported"),+ (["query", "query"], "GSC dimensions cannot contain duplicates"),+ (("query",), "GSC dimensions must be a list or None"),+ (["query", 1], "GSC dimensions must contain only strings"),+ ]+ with mock.patch.object(gsc_query, "_build_gsc_service") as build:+ for dimensions, expected in invalid_cases:+ result = gsc_query.query_search_analytics(+ "sc-domain:example.com", dimensions=dimensions+ )+ assert result["error"] == expected+ build.assert_not_called()+++def test_none_programmatic_dimensions_preserve_default():+ service = _Service(available=1)+ with mock.patch.object(gsc_query, "_build_gsc_service", return_value=service):+ result = gsc_query.query_search_analytics(+ "sc-domain:example.com", dimensions=None, row_limit=1+ )+ assert result["error"] is None+ assert service.analytics.calls[0]["dimensions"] == ["query", "page"]+++def test_blank_cli_dimensions_parse_to_empty_list():+ assert gsc_query._parse_dimensions("") == []+ assert gsc_query._parse_dimensions(" , ") == []+++def test_dimensionless_primary_query_is_reused_for_totals():+ result, calls = _run(1, dimensions=[])+ assert len(calls) == 1+ assert calls[0]["dimensions"] == []+ assert result["totals"]["clicks"] == 9+ assert result["totals_source"] == "dimensionless_query"+ assert result["totals_complete"] is True+++def test_filters_are_copied_to_dimensionless_aggregate():+ service = _Service(available=1)+ filters = [{"dimension": "country", "operator": "equals", "expression": "USA"}]+ with mock.patch.object(gsc_query, "_build_gsc_service", return_value=service):+ gsc_query.query_search_analytics(+ "sc-domain:example.com", dimensions=["query"], row_limit=1, filters=filters+ )+ assert service.analytics.calls[-1]["dimensionFilterGroups"] == [{"filters": filters}]diff --git a/tests/test_gsc_totals_aggregate.py b/tests/test_gsc_totals_aggregate.pyindex 3a439d4..996532c 100644--- a/tests/test_gsc_totals_aggregate.py+++ b/tests/test_gsc_totals_aggregate.py@@ -49,6 +49,8 @@ def test_totals_use_aggregate_not_query_sum():# Summing the query rows would yield 0 clicks; the aggregate is the truth.assert result["totals"]["clicks"] == 24, result["totals"]assert result["totals"]["impressions"] == 2734, result["totals"]+ assert result["totals_source"] == "dimensionless_aggregate"+ assert result["totals_complete"] is Trueassert result["row_count"] == 2 # rows still come from the dimensioned query@@ -67,3 +69,6 @@ def test_totals_fall_back_to_row_sum_when_aggregate_fails():result = gsc_query.query_search_analytics("sc-domain:example.com", dimensions=["query"])# Aggregate failed -> fall back to the summed rows (impressions still add up).assert result["totals"]["impressions"] == 928, result["totals"]+ assert result["totals_source"] == "partial_row_sum"+ assert result["totals_complete"] is False+ assert any("incomplete" in warning for warning in result["warnings"])diff --git a/tests/test_manifest_consistency.py b/tests/test_manifest_consistency.pyindex 710fe05..2fc28e8 100644--- a/tests/test_manifest_consistency.py+++ b/tests/test_manifest_consistency.py@@ -48,7 +48,7 @@ def _extract_count(text: str, unit: str) -> int:def test_plugin_json_skill_count_matches_disk():"""plugin.json description's 'N sub-skills' claim must equal skills/ dir count."""- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))claimed = _extract_count(plugin["description"], "sub-skills")actual = _count_skill_dirs()assert claimed == actual, (@@ -60,13 +60,13 @@ def test_plugin_json_skill_count_matches_disk():def test_plugin_json_description_fits_registry_limit():"""plugin.json description must stay below the Claude plugin registry limit."""- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))assert len(plugin["description"]) < 500def test_plugin_json_subagent_count_matches_disk():"""plugin.json description's 'N sub-agents' claim must equal agents/ count."""- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))claimed = _extract_count(plugin["description"], "sub-agents")actual = _count_agent_files()assert claimed == actual, (@@ -78,8 +78,8 @@ def test_plugin_json_subagent_count_matches_disk():def test_marketplace_json_skill_count_matches_plugin_json():"""marketplace.json plugin entry must claim the same skill count as plugin.json."""- plugin = json.loads(PLUGIN_JSON.read_text())- marketplace = json.loads(MARKETPLACE_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))+ marketplace = json.loads(MARKETPLACE_JSON.read_text(encoding="utf-8"))plugin_count = _extract_count(plugin["description"], "sub-skills")market_count = _extract_count(marketplace["plugins"][0]["description"], "sub-skills"@@ -93,8 +93,8 @@ def test_marketplace_json_skill_count_matches_plugin_json():def test_marketplace_json_subagent_count_matches_plugin_json():"""marketplace.json plugin entry must claim the same sub-agent count as plugin.json."""- plugin = json.loads(PLUGIN_JSON.read_text())- marketplace = json.loads(MARKETPLACE_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))+ marketplace = json.loads(MARKETPLACE_JSON.read_text(encoding="utf-8"))plugin_count = _extract_count(plugin["description"], "sub-agents")market_count = _extract_count(marketplace["plugins"][0]["description"], "sub-agents"@@ -108,12 +108,12 @@ def test_marketplace_json_subagent_count_matches_plugin_json():def test_canonical_phrasing_in_user_visible_docs():"""README, CLAUDE.md, AGENTS.md must reference the canonical sub-skills count."""- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))canonical_count = _extract_count(plugin["description"], "sub-skills")target_phrase = f"{canonical_count} sub-skills"for filename in ["README.md", "CLAUDE.md", "AGENTS.md"]:path = REPO_ROOT / filename- head = "\n".join(path.read_text().splitlines()[:120])+ head = "\n".join(path.read_text(encoding="utf-8").splitlines()[:120])assert target_phrase in head, (f"{filename} does not reference '{target_phrase}' in its first "f"120 lines. Update it to match plugin.json's canonical phrasing."@@ -122,8 +122,8 @@ def test_canonical_phrasing_in_user_visible_docs():def test_version_triangulation():"""plugin.json version must equal CITATION.cff version."""- plugin = json.loads(PLUGIN_JSON.read_text())- citation_text = CITATION_CFF.read_text()+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))+ citation_text = CITATION_CFF.read_text(encoding="utf-8")citation_match = re.search(r"^version:\s*(\S+)", citation_text, re.MULTILINE)assert citation_match, "CITATION.cff has no 'version:' line"plugin_version = plugin["version"]@@ -141,8 +141,8 @@ def test_pyproject_version_matches_plugin_json():1.9.8. The original triangulation test only covered CITATION.cff,so pyproject.toml drift slipped past CI. This guard closes that gap."""- plugin = json.loads(PLUGIN_JSON.read_text())- pyproject_text = (REPO_ROOT / "pyproject.toml").read_text()+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))+ pyproject_text = (REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")pyproject_match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject_text, re.MULTILINE)@@ -163,10 +163,10 @@ def test_install_scripts_default_tag_matches_plugin_version():Manual-install users via curl | bash got 8 versions stale. This guardforces the default tag to track plugin.json on every release."""- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))expected_tag = f"v{plugin['version']}"- sh_text = (REPO_ROOT / "install.sh").read_text()+ sh_text = (REPO_ROOT / "install.sh").read_text(encoding="utf-8")sh_match = re.search(r'REPO_TAG="\$\{CLAUDE_SEO_TAG:-([^}]+)\}"', sh_text)@@ -178,7 +178,7 @@ def test_install_scripts_default_tag_matches_plugin_version():f"Bump install.sh's CLAUDE_SEO_TAG default on every release.")- ps_text = (REPO_ROOT / "install.ps1").read_text()+ ps_text = (REPO_ROOT / "install.ps1").read_text(encoding="utf-8")ps_match = re.search(r"else\s*\{\s*'([^']+)'\s*\}", ps_text)assert ps_match, "install.ps1 has no recognizable RepoTag default"ps_tag = ps_match.group(1)@@ -204,7 +204,7 @@ def test_orchestrator_sub_skills_list_matches_disk():specialized" claims and the list included seo-firecrawl (extension-only). Thisguard closes that gap."""- text = (REPO_ROOT / "skills" / "seo" / "SKILL.md").read_text()+ text = (REPO_ROOT / "skills" / "seo" / "SKILL.md").read_text(encoding="utf-8")section = _extract_section(text, "Sub-Skills")listed_list = re.findall(r"^\d+\.\s+\*\*(seo-[a-z-]+)\*\*", section, re.MULTILINE)assert len(listed_list) == len(set(listed_list)), (@@ -234,7 +234,7 @@ def test_orchestrator_subagents_list_matches_disk():the Subagents list was missing seo-flow (file on disk) and included seo-firecrawl(no agent file on disk)."""- text = (REPO_ROOT / "skills" / "seo" / "SKILL.md").read_text()+ text = (REPO_ROOT / "skills" / "seo" / "SKILL.md").read_text(encoding="utf-8")section = _extract_section(text, "Subagents")listed_list = re.findall(r"^- `(seo-[a-z-]+)`", section, re.MULTILINE)assert len(listed_list) == len(set(listed_list)), (@@ -279,7 +279,7 @@ def test_skill_metadata_versions_match_plugin_json():# Each entry: skill name -> expected literal version string.COMMUNITY_OVERRIDES = {"seo-content-brief": "1.0.0"}- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))expected_default = plugin["version"]errors = []@@ -289,7 +289,7 @@ def test_skill_metadata_versions_match_plugin_json():for skill_md in candidates:skill_name = skill_md.parent.namerel = skill_md.relative_to(REPO_ROOT)- text = skill_md.read_text()+ text = skill_md.read_text(encoding="utf-8")frontmatter = _extract_frontmatter(text)if not frontmatter:errors.append(f"{rel} has no YAML frontmatter block")@@ -312,13 +312,12 @@ def test_skill_metadata_versions_match_plugin_json():def test_marketplace_metadata_and_author_parity():"""marketplace.json metadata.description includes both counts; plugin entry author parities plugin.json.- Background: v1.9.8 release notes claimed `author.email` was added in commit 8514999- but verification showed only owner.name existed. v1.9.9 corrects this and adds a- guard so marketplace.json metadata.description + plugin entry author stay in sync- with plugin.json.+ Author metadata is public, non-sensitive identity information. Keep the+ marketplace entry aligned with the plugin manifest without requiring an+ email address."""- plugin = json.loads(PLUGIN_JSON.read_text())- mp = json.loads(MARKETPLACE_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))+ mp = json.loads(MARKETPLACE_JSON.read_text(encoding="utf-8"))desc = mp["metadata"]["description"]desc_sub_skills = re.search(r"(\d+)\s+sub-skills", desc)@@ -351,9 +350,11 @@ def test_marketplace_metadata_and_author_parity():)p_author = plugin["author"]m_author = plugin_entry["author"]- # Exact parity for all 3 fields (name, email, url) — drift in any field- # signals a metadata sync miss- for field in ("name", "email", "url"):+ # Exact parity for the public fields. Email addresses are intentionally not+ # shipped in either manifest.+ assert "email" not in p_author+ assert "email" not in m_author+ for field in ("name", "url"):p_val = p_author.get(field)m_val = m_author.get(field)assert p_val, f"plugin.json author.{field} must be non-empty (was: {p_val!r})"@@ -365,7 +366,7 @@ def test_marketplace_metadata_and_author_parity():def test_canonical_math_adds_up():"""The canonical phrasing's parenthetical breakdown must sum to the headline count."""- plugin = json.loads(PLUGIN_JSON.read_text())+ plugin = json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))desc = plugin["description"]headline_match = re.search(r"(\d+)\s+sub-skills\s+\(([^)]+)\)", desc)assert headline_match, (@@ -415,7 +416,7 @@ def test_reference_files_have_at_least_one_link():# Reference files can cite each other (e.g. via [[wikilink]]).search_paths += ref_files- text_by_path = {p: p.read_text() for p in search_paths}+ text_by_path = {p: p.read_text(encoding="utf-8") for p in search_paths}orphans = []for ref in ref_files:diff --git a/tests/test_pyproject_metadata.py b/tests/test_pyproject_metadata.pyindex bfaa432..1bc08e0 100644--- a/tests/test_pyproject_metadata.py+++ b/tests/test_pyproject_metadata.py@@ -13,7 +13,7 @@ def test_pyproject_has_authors_and_keywords() -> None:text = (REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")assert 'authors = [' in textassert 'name = "Daniel Agrici"' in text- assert 'email = "[email protected]"' in text+ assert "email =" not in textfor keyword in ("seo", "claude-code", "schema-markup", "e-e-a-t", "geo"):assert f'"{keyword}"' in textdiff --git a/tests/test_render_page.py b/tests/test_render_page.pyindex ddeda22..a494094 100644--- a/tests/test_render_page.py+++ b/tests/test_render_page.py@@ -18,6 +18,7 @@ documents the limitation so CI shows "skipped" rather than "failed".from __future__ import annotations+import jsonimport osimport sysfrom types import SimpleNamespace@@ -85,6 +86,118 @@ def test_is_spa_negative(html: str) -> None:assert render_page._is_spa(html) is False+def test_is_spa_detects_sparse_builder_shell_with_multiple_markers() -> None:+ html = (+ '<html><head><meta content="Wix.com Website Builder">'+ '<script src="https://static.parastorage.com/app.js"></script></head>'+ '<body><script id="wix-warmup-data">{}</script><main>Loading</main></body></html>'+ )+ assert render_page._is_spa(html) is True+++def test_is_spa_does_not_render_complete_builder_page() -> None:+ html = (+ '<html data-wf-page="page" data-wf-site="site"><body><main>'+ + ("Complete server rendered product information. " * 20)+ + "</main></body></html>"+ )+ assert render_page._is_spa(html) is False+++def test_is_spa_ignores_large_inline_script_as_visible_text() -> None:+ html = (+ "<html><body><script>"+ + ("window.payload = 'large';" * 100)+ + "</script><div>Loading</div></body></html>"+ )+ assert render_page._is_spa(html) is True+++# ---------------------------------------------------------------------------+# Bounded JSON-LD extraction+# ---------------------------------------------------------------------------+++def test_extract_json_ld_parses_full_html_before_summary_truncation() -> None:+ html = (+ "<html><head>"+ "<script nonce='x' TYPE='application/ld+json'>"+ '{"@context":"https://schema.org","@graph":['+ '{"@type":"Organization"},{"@type":["WebSite","Thing"]}]}'+ "</script></head><body>ok</body></html>"+ )+ result = render_page._extract_json_ld(html)+ assert result["block_count"] == 1+ assert result["blocks"][0]["valid"] is True+ assert result["blocks"][0]["types"] == ["Organization", "Thing", "WebSite"]+ assert "data" not in result["blocks"][0]+++def test_extract_json_ld_full_data_is_explicit_opt_in() -> None:+ html = '<script type="application/ld+json">{"@type":"Caf\u00e9"}</script>'+ summary = render_page._extract_json_ld(html)+ full = render_page._extract_json_ld(html, include_full=True)+ assert "data" not in summary["blocks"][0]+ assert full["blocks"][0]["data"]["@type"] == "Caf\u00e9"+++def test_extract_json_ld_malformed_content_is_full_output_only() -> None:+ malformed = '{"private_fragment":"not valid"'+ html = f'<script type="application/ld+json">{malformed}</script>'++ summary = render_page._extract_json_ld(html)+ full = render_page._extract_json_ld(html, include_full=True)++ summary_block = summary["blocks"][0]+ assert summary_block["valid"] is False+ assert "raw" not in summary_block+ assert "preview" not in summary_block+ assert malformed not in json.dumps(summary)+ assert full["blocks"][0]["raw"] == malformed+++def test_extract_json_ld_enforces_block_and_count_limits(monkeypatch) -> None:+ monkeypatch.setattr(render_page, "JSON_LD_MAX_BLOCK_BYTES", 20)+ monkeypatch.setattr(render_page, "JSON_LD_MAX_BLOCKS", 2)+ html = (+ '<script type="application/ld+json">{"value":"' + ("x" * 30) + '"}</script>'+ '<script type="application/ld+json">{"@type":"Two"}</script>'+ '<script type="application/ld+json">{"@type":"Three"}</script>'+ )+ result = render_page._extract_json_ld(html, include_full=True)+ assert result["block_count"] == 3+ assert result["processed_count"] == 2+ assert result["truncated"] is True+ assert result["blocks"][0]["valid"] is None+ assert "data" not in result["blocks"][0]+++class _StabilityPage:+ def __init__(self, signatures):+ self.signatures = list(signatures)+ self.last = self.signatures[-1]+ self.waits = []++ def evaluate(self, _expression):+ if self.signatures:+ self.last = self.signatures.pop(0)+ return self.last++ def wait_for_timeout(self, milliseconds):+ self.waits.append(milliseconds)+++def test_wait_for_dom_stability_handles_late_hydration() -> None:+ page = _StabilityPage([(0, 5), (80, 10), (240, 20), (240, 20), (240, 20)])+ assert render_page._wait_for_dom_stability(page, 2000) is True+++def test_wait_for_dom_stability_is_bounded() -> None:+ page = _StabilityPage([(0, 5)])+ assert render_page._wait_for_dom_stability(page, 750) is False+ assert sum(page.waits) == 750++# ---------------------------------------------------------------------------# render_page — argument validation# ---------------------------------------------------------------------------@@ -158,6 +271,83 @@ def _mock_validate_strict(url: str) -> tuple[str, str]:return (url, "1.2.3.4")+class _FakeBrowserResponse:+ status = 200++ @staticmethod+ def all_headers():+ return {"content-type": "text/html"}+++class _FakeBrowserPage(_StabilityPage):+ def __init__(self, signatures, *, navigation_timeout=False):+ super().__init__(signatures)+ self.navigation_timeout = navigation_timeout+ self.goto_options = None+ self.url = "https://app.example/"+ self.accessibility = SimpleNamespace(snapshot=lambda **_kwargs: None)++ def on(self, *_args):+ return None++ def route(self, *_args):+ return None++ def goto(self, _url, **kwargs):+ self.goto_options = kwargs+ if self.navigation_timeout:+ raise render_page.PlaywrightTimeout("timeout")+ return _FakeBrowserResponse()++ @staticmethod+ def content():+ return "<html><body>" + ("hydrated content " * 20) + "</body></html>"+++class _FakePlaywrightManager:+ def __init__(self, page):+ browser = SimpleNamespace(+ new_context=lambda **_kwargs: SimpleNamespace(new_page=lambda: page),+ close=lambda: None,+ )+ self.playwright = SimpleNamespace(+ chromium=SimpleNamespace(launch=lambda **_kwargs: browser)+ )++ def __enter__(self):+ return self.playwright++ def __exit__(self, *_args):+ return False+++def _render_with_fake_browser(page):+ spa_html = '<html><body><div id="root"></div></body></html>'+ with patch.object(render_page, "validate_url_strict", side_effect=_mock_validate_strict), \+ patch.object(render_page, "safe_requests_get", return_value=_fake_response(spa_html)), \+ patch.object(render_page, "sync_playwright", lambda: _FakePlaywrightManager(page)):+ return render_page.render_page("https://app.example/", mode="auto", timeout_ms=1000)+++def test_render_uses_domcontentloaded_for_persistent_socket_pages() -> None:+ page = _FakeBrowserPage([(200, 20), (200, 20), (200, 20)])+ result = _render_with_fake_browser(page)+ assert result["error"] is None+ assert page.goto_options["wait_until"] == "domcontentloaded"+ assert result["render_diagnostics"] == []+++def test_render_navigation_timeout_returns_degraded_dom() -> None:+ page = _FakeBrowserPage(+ [(200, 20), (200, 20), (200, 20)], navigation_timeout=True+ )+ result = _render_with_fake_browser(page)+ assert result["error"] is None+ assert result["content"].startswith("<html>")+ assert result["status_code"] == 200+ assert any("DOMContentLoaded timed out" in item for item in result["render_diagnostics"])++def test_render_page_auto_stays_raw_for_static_html() -> None:"""auto mode + non-SPA raw HTML → no Playwright invocation."""rich_html = "<html><body>" + ("hello world. " * 20) + "</body></html>"@@ -268,6 +458,6 @@ def test_render_page_result_dict_has_all_documented_fields() -> None:"url", "status_code", "content", "raw_content", "is_spa","extracted_text", "publication_date", "accessibility_tree","headers", "redirect_chain", "console_errors", "render_engine",- "render_ms", "mode_used", "error",+ "render_diagnostics", "render_ms", "mode_used", "error",}assert set(result.keys()) == expected_fieldsdiff --git a/tests/test_runtime.py b/tests/test_runtime.pynew file mode 100644index 0000000..6ba0656--- /dev/null+++ b/tests/test_runtime.py@@ -0,0 +1,225 @@+"""Managed runtime and safe-dispatch regressions."""++from __future__ import annotations++import importlib.util+import json+import os+import signal+import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest++ROOT = Path(__file__).resolve().parents[1]+SPEC = importlib.util.spec_from_file_location("claude_seo_runtime", ROOT / "scripts/runtime.py")+assert SPEC and SPEC.loader+runtime = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(runtime)+++def _fixture_root(tmp_path: Path) -> Path:+ root = tmp_path / "plugin root"+ (root / "scripts").mkdir(parents=True)+ (root / "extensions" / "banana" / "scripts").mkdir(parents=True)+ (root / ".claude-plugin").mkdir()+ (root / "requirements.txt").write_text("requests>=2\n", encoding="utf-8")+ (root / ".claude-plugin" / "plugin.json").write_text('{"version":"2.2.4"}\n', encoding="utf-8")+ (root / "scripts" / "render_page.py").write_text("print('ok')\n", encoding="utf-8")+ (root / "extensions" / "banana" / "scripts" / "generate.py").write_text("print('ok')\n", encoding="utf-8")+ return root+++def test_dispatch_is_allowlisted_and_rejects_traversal(tmp_path: Path) -> None:+ root = _fixture_root(tmp_path)+ assert runtime._resolve_script(root, "render_page.py", None).name == "render_page.py"+ assert runtime._resolve_script(root, "generate.py", "banana").name == "generate.py"+ with pytest.raises(ValueError):+ runtime._resolve_script(root, "../render_page.py", None)+ with pytest.raises(ValueError):+ runtime._resolve_script(root, "runtime.py", None)+ with pytest.raises(ValueError):+ runtime._resolve_script(root, "generate.py", "../banana")+++def test_manual_extension_fallback_stays_inside_installed_skill(tmp_path: Path) -> None:+ root = tmp_path / "skills" / "seo"+ scripts = tmp_path / "skills" / "seo-image-gen" / "scripts"+ scripts.mkdir(parents=True)+ (scripts / "generate.py").write_text("print('ok')\n", encoding="utf-8")+ assert runtime._resolve_script(root, "generate.py", "banana") == (+ scripts / "generate.py"+ ).resolve()+++def test_status_uses_plugin_data_and_hash_marker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ root = _fixture_root(tmp_path)+ data = tmp_path / "persistent data"+ python = data / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ python.parent.mkdir(parents=True)+ python.write_text("", encoding="utf-8")+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(data))+ expected = runtime._expected(root)+ (data / "runtime-state.json").write_text(json.dumps({**expected, "browser_ready": True}), encoding="utf-8")+ status = runtime._status(root)+ assert status["ready"] is True+ assert status["mode"] == "plugin"+ (root / "requirements.txt").write_text("requests>=3\n", encoding="utf-8")+ assert runtime._status(root)["ready"] is False+++def test_source_checkout_uses_repository_venv_without_plugin_environment(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = _fixture_root(tmp_path)+ (root / ".git").mkdir()+ monkeypatch.delenv("CLAUDE_PLUGIN_DATA", raising=False)+ monkeypatch.delenv("CLAUDE_PLUGIN_ROOT", raising=False)+ monkeypatch.delenv("CLAUDE_SEO_DATA_DIR", raising=False)+ data_dir, mode = runtime._data_dir(root)+ assert data_dir == root+ assert mode == "manual"+++def test_doctor_json_omits_paths_and_environment_values(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ root = _fixture_root(tmp_path)+ sensitive_path = tmp_path / "person-name" / "private"+ monkeypatch.setattr(runtime, "_root", lambda: root)+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(sensitive_path))+ rc = runtime.command_doctor(SimpleNamespace(json=True))+ output = capsys.readouterr().out+ payload = json.loads(output)+ assert rc == 3+ assert str(sensitive_path) not in output+ assert set(payload) == {+ "browser_ready", "mode", "plugin_version", "python_version", "ready", "reasons"+ }+++def test_child_environment_forces_utf8_and_persistent_browser_path(tmp_path: Path) -> None:+ env = runtime._safe_env({"data_dir": tmp_path})+ assert env["PYTHONUTF8"] == "1"+ assert env["PYTHONIOENCODING"] == "utf-8"+ assert env["PLAYWRIGHT_BROWSERS_PATH"] == str(tmp_path / "ms-playwright")+++def test_configured_data_dir_rejects_filesystem_root_and_user_home(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ with pytest.raises(ValueError):+ runtime._configured_data_dir(str(Path(Path.cwd().anchor)))+ monkeypatch.setattr(runtime.Path, "home", classmethod(lambda cls: Path.cwd()))+ with pytest.raises(ValueError):+ runtime._configured_data_dir(str(Path.cwd()))+++def test_version_only_change_does_not_stale_environment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ root = _fixture_root(tmp_path)+ data = tmp_path / "data"+ python = data / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ python.parent.mkdir(parents=True)+ python.write_text("", encoding="utf-8")+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(data))+ expected = runtime._expected(root)+ expected["plugin_version"] = "2.2.2"+ (data / "runtime-state.json").write_text(json.dumps(expected), encoding="utf-8")+ assert runtime._status(root)["ready"] is True+++def test_error_redaction_hides_credentials_and_tokens() -> None:+ text = (+ f"{Path.home()}/private [email protected] "+ "https://user:[email protected]/path?token=visible token=abc123 api_key: xyz"+ )+ redacted = runtime._redact(text)+ assert str(Path.home()) not in redacted+ assert "[email protected]" not in redacted+ assert "password@example" not in redacted+ assert "visible" not in redacted+ assert "abc123" not in redacted+ assert " xyz" not in redacted+++def test_browser_marker_requires_browser_files(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ root = _fixture_root(tmp_path)+ data = tmp_path / "data"+ python = data / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ python.parent.mkdir(parents=True)+ python.write_text("", encoding="utf-8")+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(data))+ expected = runtime._expected(root)+ (data / "runtime-state.json").write_text(+ json.dumps({**expected, "browser_ready": True}), encoding="utf-8"+ )+ assert runtime._status(root)["browser_ready"] is False+ (data / "ms-playwright" / "chromium-123").mkdir(parents=True)+ assert runtime._status(root)["browser_ready"] is True+++def test_setup_restores_previous_environment_when_staged_swap_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ root = _fixture_root(tmp_path)+ data = tmp_path / "data"+ final = data / ".venv"+ old_python = final / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ old_python.parent.mkdir(parents=True)+ old_python.write_text("old", encoding="utf-8")+ (final / "old-sentinel").write_text("keep", encoding="utf-8")+ data.mkdir(parents=True, exist_ok=True)+ (data / "runtime-state.json").write_text(+ json.dumps(runtime._expected(root)), encoding="utf-8"+ )+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(data))+ monkeypatch.setattr(runtime, "_root", lambda: root)++ def fake_checked(argv: list[str], *, env: dict[str, str], stage: str) -> subprocess.CompletedProcess[str]:+ if stage == "virtual environment creation":+ staged = Path(argv[-1])+ staged_python = runtime._venv_python(staged)+ staged_python.parent.mkdir(parents=True)+ staged_python.write_text("new", encoding="utf-8")+ return subprocess.CompletedProcess(argv, 0, "", "")++ original_replace = Path.replace++ def fail_staged_replace(self: Path, target: Path) -> Path:+ if self.name.startswith(".venv.next-"):+ raise OSError("injected staged swap failure")+ return original_replace(self, target)++ monkeypatch.setattr(runtime, "_run_checked", fake_checked)+ monkeypatch.setattr(Path, "replace", fail_staged_replace)+ rc = runtime.command_setup(SimpleNamespace(skip_browser=True))+ assert rc == 1+ assert (final / "old-sentinel").read_text(encoding="utf-8") == "keep"+ assert not (data / ".venv.previous").exists()+ assert not (data / ".runtime-state.next").exists()+++def test_run_propagates_child_signal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ root = _fixture_root(tmp_path)+ managed_python = tmp_path / "python"+ managed_python.write_text("", encoding="utf-8")+ status = {+ "ready": True,+ "python_path": managed_python,+ "data_dir": tmp_path,+ }+ delivered: list[tuple[int, int]] = []+ monkeypatch.setattr(runtime, "_root", lambda: root)+ monkeypatch.setattr(runtime, "_status", lambda _: status)+ monkeypatch.setattr(+ runtime.subprocess,+ "run",+ lambda *args, **kwargs: subprocess.CompletedProcess(args[0], -signal.SIGTERM),+ )+ monkeypatch.setattr(runtime.os, "kill", lambda pid, sig: delivered.append((pid, sig)))+ rc = runtime.command_run(+ SimpleNamespace(script="render_page.py", extension=None, script_args=[])+ )+ assert rc == 128 + signal.SIGTERM+ assert delivered == [(os.getpid(), signal.SIGTERM)]diff --git a/tests/test_runtime_installers.py b/tests/test_runtime_installers.pynew file mode 100644index 0000000..1ae09de--- /dev/null+++ b/tests/test_runtime_installers.py@@ -0,0 +1,39 @@+"""Static installer/runtime contract checks that do not mutate a real home."""++from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+++def test_unix_installer_delegates_to_runtime_without_global_pip() -> None:+ text = (ROOT / "install.sh").read_text(encoding="utf-8")+ assert '"${SKILL_DIR}/bin/claude-seo" setup' in text+ assert "pip install --user" not in text+ assert "python3 -m venv" not in text+ assert "claude-seo run" in text+ assert "claude-seo setup" in text+ assert "claude-seo doctor" in text+ assert '"${runtime_status}" -ne 0 ] && [ "${runtime_status}" -ne 10' in text+ assert 'find "${HOME}/.claude/skills"' not in text+++def test_windows_installer_delegates_to_runtime_without_path_mutation() -> None:+ text = (ROOT / "install.ps1").read_text(encoding="utf-8")+ assert "scripts\\runtime.py" in text+ assert "'setup'" in text+ assert "SetEnvironmentVariable('PATH'" not in text+ assert "pip','install" not in text+ assert "UTF8Encoding($false)" in text+ assert "version_info >= (3, 10)" in text+ assert "$runtime.ExitCode -ne 0 -and $runtime.ExitCode -ne 10" in text+ assert "-Directory -Filter 'seo*'" not in text+++def test_launcher_is_executable_and_uses_safe_exec() -> None:+ launcher = ROOT / "bin/claude-seo"+ assert launcher.stat().st_mode & 0o100+ text = launcher.read_text(encoding="utf-8")+ assert 'exec py -3 "${runtime}" "$@"' in text+ assert 'exec python3 "${runtime}" "$@"' in text+ assert 'exec python "${runtime}" "$@"' in text+ assert "eval " not in textdiff --git a/tests/test_schema_hook_policy.py b/tests/test_schema_hook_policy.pyindex 34b83f1..49b45d3 100644--- a/tests/test_schema_hook_policy.py+++ b/tests/test_schema_hook_policy.py@@ -1,8 +1,8 @@"""Policy regression for the JSON-LD validation hook.-FAQPage must NOT block (FAQ rich results were retired May 2026 but the-markup still aids AI Mode), while genuinely deprecated types must still-block the edit (exit 2).+FAQPage must NOT block because it remains a valid Schema.org type, even though+Google retired its rich results in May 2026 and no AI or ranking benefit is+confirmed. Genuinely deprecated types must still block the edit (exit 2)."""from __future__ import annotationsdiff --git a/tests/test_schema_v2.py b/tests/test_schema_v2.pyindex 6030c6c..52a06cf 100644--- a/tests/test_schema_v2.py+++ b/tests/test_schema_v2.py@@ -248,8 +248,8 @@ def test_deprecated_types_reference_exists_and_lists_retired_kinds() -> None:def test_faq_rich_results_retirement_documented() -> None:"""FAQ rich results were fully retired on 2026-05-07 (supersedes the olderAug 2023 gov/health restriction). The canonical schema references must reflect- the retirement and point users to QAPage for genuine Q&A — while keeping- FAQPage as an AI/entity signal (not a Critical removal)."""+ the retirement and point users to QAPage for genuine Q&A, without claiming+ a confirmed AI or ranking benefit for FAQPage."""from pathlib import Pathroot = Path(__file__).resolve().parents[1]@@ -268,3 +268,26 @@ def test_faq_rich_results_retirement_documented() -> None:assert "QAPage" in deprecated and "QAPage" in schema_types# Google's faqpage doc cited as primary source.assert "structured-data/faqpage" in deprecated+++def test_faqpage_guidance_does_not_claim_unconfirmed_benefits() -> None:+ """Public guidance must not turn an unverified AI benefit into a claim."""+ from pathlib import Path++ root = Path(__file__).resolve().parents[1]+ targets = [+ root / "hooks" / "validate-schema.py",+ root / "pdf" / "google-seo-reference.md",+ root / "docs" / "TROUBLESHOOTING.md",+ root / "skills" / "seo-content-brief" / "references"+ / "page-type-templates.md",+ ]+ combined = "\n".join(path.read_text(encoding="utf-8") for path in targets).lower()+ forbidden = (+ "still aids ai",+ "can still aid ai",+ "valid ai/entity signal",+ "+ faqpage",+ )+ for phrase in forbidden:+ assert phrase not in combineddiff --git a/tests/test_sitemap_discovery.py b/tests/test_sitemap_discovery.pynew file mode 100644index 0000000..46018b4--- /dev/null+++ b/tests/test_sitemap_discovery.py@@ -0,0 +1,154 @@+"""Executable sitemap discovery regressions for issue #142."""++from __future__ import annotations++import sys+from pathlib import Path+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts"))++import sitemap_discovery as discovery # noqa: E402++URLSET = b'<?xml version="1.0"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'+INDEX = b'<?xml version="1.0"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></sitemapindex>'+++def response(status=200, content=b"", url="https://example.com/", error=None, too_large=False, content_type="application/xml"):+ return {+ "status_code": status,+ "content": content,+ "content_type": content_type,+ "final_url": url,+ "too_large": too_large,+ "error": error,+ }+++def test_wordpress_index_is_found_after_default_path_fails():+ def fake_fetch(url, _limit):+ if url.endswith("robots.txt"):+ return response(content=b"User-agent: *\n")+ if url.endswith("sitemap_index.xml"):+ return response(content=INDEX, url=url)+ return response(status=404, url=url)++ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):+ result = discovery.discover_sitemaps("https://example.com/page")+ assert [item["url"] for item in result["found"]] == ["https://example.com/sitemap_index.xml"]+++def test_stale_declared_sitemap_does_not_suppress_working_fallback():+ stale = "https://example.com/old.xml"++ def fake_fetch(url, _limit):+ if url.endswith("robots.txt"):+ return response(content=f"Sitemap: {stale}\n".encode())+ if url == stale:+ return response(status=404, url=url)+ if url.endswith("wp-sitemap.xml"):+ return response(content=URLSET, url=url)+ return response(status=404, url=url)++ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):+ result = discovery.discover_sitemaps("https://example.com")+ assert any(item["source"] == "robots.txt" and not item["valid"] for item in result["checked"])+ assert result["found"][0]["url"].endswith("/wp-sitemap.xml")+++def test_multiple_directives_are_deduplicated_and_cross_host_is_recorded():+ robots = (+ b"sItEmAp: https://cdn.example.net/a.xml\n"+ b"Sitemap: https://cdn.example.net/a.xml\n"+ b"Sitemap: https://example.com/b.xml\n"+ )++ def fake_fetch(url, _limit):+ if url.endswith("robots.txt"):+ return response(content=robots)+ if url.endswith(("a.xml", "b.xml")):+ return response(content=URLSET, url=url)+ return response(status=404, url=url)++ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):+ result = discovery.discover_sitemaps("https://example.com")+ assert len(result["declared"]) == 2+ assert len(result["found"]) == 2+ assert result["found"][0]["cross_host"] is True+++def test_unsafe_declared_target_is_not_treated_as_found():+ unsafe = "http://127.0.0.1/private.xml"++ def fake_fetch(url, _limit):+ if url.endswith("robots.txt"):+ return response(content=f"Sitemap: {unsafe}\n".encode())+ if url == unsafe:+ return response(error="URL safety validation failed", url=url)+ return response(status=404, url=url)++ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):+ result = discovery.discover_sitemaps("https://example.com")+ unsafe_entry = next(item for item in result["checked"] if item["url"] == unsafe)+ assert unsafe_entry["valid"] is False+ assert unsafe_entry["error"] == "URL safety validation failed"+++def test_invalid_xml_and_html_200_are_rejected():+ assert discovery._sitemap_kind(b"<urlset>", "application/xml", "https://example.com/sitemap.xml")[0] is None+ assert discovery._sitemap_kind(b"<html></html>", "text/html", "https://example.com/sitemap.xml")[0] is None+++def test_text_sitemap_entries_are_syntax_checked_without_dns_resolution():+ content = b"https://example.com/one\nhttps://example.com/two\n"+ with patch.object(discovery, "validate_url", side_effect=AssertionError("unexpected DNS validation")):+ kind, error = discovery._sitemap_kind(+ content, "text/plain", "https://example.com/sitemap.txt"+ )+ assert kind == "text"+ assert error is None+ assert discovery._valid_sitemap_url_syntax("http://[email protected]/private") is False+++def test_doctype_and_oversized_sitemap_are_rejected():+ assert discovery._sitemap_kind(b"<!DOCTYPE x><urlset/>", "application/xml", "https://example.com/sitemap.xml")[0] is None++ def fake_fetch(url, _limit):+ if url.endswith("robots.txt"):+ return response(content=b"Sitemap: https://example.com/huge.xml\n")+ if url.endswith("huge.xml"):+ return response(url=url, too_large=True)+ return response(status=404, url=url)++ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):+ result = discovery.discover_sitemaps("https://example.com")+ huge = next(item for item in result["checked"] if item["url"].endswith("huge.xml"))+ assert "50 MiB" in huge["error"]+++def test_query_values_are_never_returned_in_discovery_output():+ declared = "https://example.com/private.xml?token=not-for-output"++ def fake_fetch(url, _limit):+ if url.endswith("robots.txt"):+ return response(content=f"Sitemap: {declared}\n".encode())+ if url == declared:+ return response(content=URLSET, url=url)+ return response(status=404, url=url)++ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):+ result = discovery.discover_sitemaps("https://example.com")+ dumped = str(result)+ assert "not-for-output" not in dumped+ assert result["declared"][0]["query_redacted"] is True+++def test_private_literal_is_refused_before_network_request():+ result = discovery._bounded_fetch("http://127.0.0.1/sitemap.xml", 100)+ assert result["error"] == "URL safety validation failed"+++def test_invalid_port_is_reported_without_crashing():+ result = discovery.discover_sitemaps("https://example.com:invalid/")+ assert result["error"] == "Target URL contains an invalid port"diff --git a/tests/test_sync_flow.py b/tests/test_sync_flow.pyindex 880b545..37627e1 100644--- a/tests/test_sync_flow.py+++ b/tests/test_sync_flow.py@@ -140,6 +140,46 @@ def test_authed_headers_degrades_when_gh_missing(monkeypatch):assert "Authorization" not in headers+def test_api_get_retries_unauthenticated_429_with_cli_token(monkeypatch):+ """GitHub may return 429 instead of 403 when the anonymous pool is spent."""+ sf = _load_sync_flow_module()+ import io++ rate_limited = sf.urllib.error.HTTPError(+ "https://api.github.com/example", 429, "too many requests", {}, io.BytesIO()+ )++ class _Response:+ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ @staticmethod+ def read(_limit):+ return b'{"content":""}'++ calls = []++ def fake_urlopen(request, timeout):+ calls.append(request)+ if len(calls) == 1:+ raise rate_limited+ return _Response()++ monkeypatch.setattr(sf.urllib.request, "urlopen", fake_urlopen)+ monkeypatch.setattr(+ sf,+ "_authed_headers",+ lambda: {**sf._base_headers(), "Authorization": "Bearer test-token"},+ )++ assert sf.api_get("file.md", None, sf._base_headers()) == {"content": ""}+ assert len(calls) == 2+ assert calls[1].get_header("Authorization") == "Bearer test-token"++# ── Task 3 tests ──────────────────────────────────────────────────────────────def test_validate_github_url_blocks_non_github_host():diff --git a/tests/test_url_safety.py b/tests/test_url_safety.pyindex 67caa32..24de833 100644--- a/tests/test_url_safety.py+++ b/tests/test_url_safety.py@@ -535,6 +535,52 @@ def test_save_oauth_token_remediates_legacy_0o644(tmp_path, monkeypatch) -> Noneassert target.stat().st_mode & 0o777 == 0o600+def test_save_oauth_token_without_fchmod_closes_descriptor(tmp_path, monkeypatch) -> None:+ """Windows has no os.fchmod; persistence must still succeed and close fd."""+ import json+ import google_auth # noqa: WPS433++ target = tmp_path / "config" / "oauth-token.json"+ monkeypatch.setattr(google_auth, "TOKEN_PATH", str(target))+ monkeypatch.delattr(google_auth.os, "fchmod", raising=False)++ real_open = os.open+ opened_fds = []++ def recording_open(*args, **kwargs):+ fd = real_open(*args, **kwargs)+ opened_fds.append(fd)+ return fd++ monkeypatch.setattr(google_auth.os, "open", recording_open)+ google_auth._save_oauth_token({"access_token": "windows"})++ assert json.loads(target.read_text(encoding="utf-8")) == {+ "access_token": "windows"+ }+ assert len(opened_fds) == 1+ with pytest.raises(OSError):+ os.fstat(opened_fds[0])+++def test_save_oauth_token_ignores_fchmod_oserror(tmp_path, monkeypatch) -> None:+ """Filesystems without descriptor chmod support must still persist tokens."""+ import json+ import google_auth # noqa: WPS433++ target = tmp_path / "config" / "oauth-token.json"+ monkeypatch.setattr(google_auth, "TOKEN_PATH", str(target))++ def unsupported_fchmod(_fd, _mode):+ raise OSError("unsupported")++ monkeypatch.setattr(google_auth.os, "fchmod", unsupported_fchmod)+ google_auth._save_oauth_token({"access_token": "portable"})+ assert json.loads(target.read_text(encoding="utf-8")) == {+ "access_token": "portable"+ }++def test_load_oauth_token_remediates_legacy_0o644(tmp_path, monkeypatch) -> None:"""_load_oauth_token chmods the file before reading, so the next readby any other process sees 0o600 even without a re-save."""