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.
fix(portability): make hooks and drift fetch cross-platform
Daniel49df04045b76
diff --git a/hooks/hooks.json b/hooks/hooks.jsonindex 6d7eb08..51d70f7 100644--- a/hooks/hooks.json+++ b/hooks/hooks.json@@ -6,7 +6,12 @@"hooks": [{"type": "command",- "command": "python \"${CLAUDE_PLUGIN_ROOT}/hooks/validate-schema.py\" \"$FILE_PATH\""+ "command": "node",+ "args": [+ "${CLAUDE_PLUGIN_ROOT}/hooks/run-python-hook.js",+ "${CLAUDE_PLUGIN_ROOT}/hooks/validate-schema.py",+ "${tool_input.file_path}"+ ]}]}diff --git a/hooks/run-python-hook.js b/hooks/run-python-hook.jsnew file mode 100644index 0000000..9eff1bc--- /dev/null+++ b/hooks/run-python-hook.js@@ -0,0 +1,68 @@+#!/usr/bin/env node+"use strict";++const { spawnSync } = require("child_process");++function stripWrappingQuotes(value) {+ return value.replace(/^["']|["']$/g, "");+}++function pythonCandidates() {+ const candidates = [];+ if (process.env.CLAUDE_SEO_PYTHON) {+ candidates.push({+ label: "CLAUDE_SEO_PYTHON",+ exe: stripWrappingQuotes(process.env.CLAUDE_SEO_PYTHON),+ args: [],+ });+ }+ candidates.push(+ { label: "py -3", exe: "py", args: ["-3"] },+ { label: "python3", exe: "python3", args: [] },+ { label: "python", exe: "python", args: [] },+ );+ return candidates;+}++function isStoreStubOutput(text) {+ return /Microsoft Store|WindowsApps|App execution alias|was not found/i.test(text);+}++function probe(candidate) {+ const script = "import sys; print(sys.executable); print(sys.version.split()[0])";+ const result = spawnSync(candidate.exe, [...candidate.args, "-c", script], {+ encoding: "utf8",+ });+ if (result.error) {+ return false;+ }+ const output = `${result.stdout || ""}\n${result.stderr || ""}`;+ return result.status === 0 && !isStoreStubOutput(output);+}++function main() {+ const [, , hookScript, ...hookArgs] = process.argv;+ if (!hookScript) {+ process.exit(0);+ }++ for (const candidate of pythonCandidates()) {+ if (!probe(candidate)) {+ continue;+ }+ const result = spawnSync(candidate.exe, [...candidate.args, hookScript, ...hookArgs], {+ stdio: "inherit",+ });+ if (result.error) {+ continue;+ }+ process.exit(result.status === null ? 1 : result.status);+ }++ console.error(+ "Claude SEO hook could not find Python. Tried CLAUDE_SEO_PYTHON, py -3, python3, python.",+ );+ process.exit(1);+}++main();diff --git a/hooks/validate-schema.py b/hooks/validate-schema.pyindex 762214d..caaa112 100755--- a/hooks/validate-schema.py+++ b/hooks/validate-schema.py@@ -13,8 +13,12 @@ Hook configuration in ~/.claude/settings.json:"hooks": [{"type": "command",- "command": "python3 ~/.claude/skills/seo/hooks/validate-schema.py \"$FILE_PATH\"",- "exitCodes": { "2": "block" }+ "command": "node",+ "args": [+ "${CLAUDE_PLUGIN_ROOT}/hooks/run-python-hook.js",+ "${CLAUDE_PLUGIN_ROOT}/hooks/validate-schema.py",+ "${tool_input.file_path}"+ ]}]}@@ -125,7 +129,7 @@ def main():# Only validate HTML-like filesvalid_extensions = (".html", ".htm", ".jsx", ".tsx", ".vue", ".svelte", ".php", ".ejs")- if not filepath.endswith(valid_extensions):+ if not filepath.lower().endswith(valid_extensions):sys.exit(0)# File-size guard: skip files >10MB to bound memory + hook latency.diff --git a/install.ps1 b/install.ps1index f8d286e..9e1836c 100644--- a/install.ps1+++ b/install.ps1@@ -10,14 +10,17 @@ Write-Host "========================================" -ForegroundColor CyanWrite-Host ""function Resolve-Python {- $pythonCmd = Get-Command -Name python -ErrorAction SilentlyContinue- if ($null -ne $pythonCmd) {- return @{ Exe = 'python'; Args = @() }- }+ $candidates = @(+ @{ Exe = 'py'; Args = @('-3') },+ @{ Exe = 'python3'; Args = @() },+ @{ Exe = 'python'; Args = @() }+ )- $pyCmd = Get-Command -Name py -ErrorAction SilentlyContinue- if ($null -ne $pyCmd) {- return @{ Exe = 'py'; Args = @('-3') }+ foreach ($candidate in $candidates) {+ $resolved = Test-PythonCandidate -Exe $candidate.Exe -Args $candidate.Args+ if ($null -ne $resolved) {+ return $resolved+ }}return $null@@ -58,10 +61,36 @@ function Invoke-External {return @{ ExitCode = $exitCode; Output = $output }}+function Test-PythonCandidate {+ param(+ [Parameter(Mandatory = $true)][string]$Exe,+ [Parameter(Mandatory = $true)][string[]]$Args+ )++ $pythonCmd = Get-Command -Name $Exe -ErrorAction SilentlyContinue+ if ($null -eq $pythonCmd) {+ return $null+ }++ $probeCode = 'import sys; print(sys.executable); print(sys.version.split()[0])'+ $probe = Invoke-External -Exe $Exe -Args @($Args + @('-c', $probeCode)) -Quiet+ $probeText = ($probe.Output -join "`n")++ if ($probe.ExitCode -ne 0) {+ return $null+ }++ if ($probeText -match 'Microsoft Store|WindowsApps|App execution alias|was not found') {+ return $null+ }++ return @{ Exe = $Exe; Args = $Args }+}+# Check prerequisites$python = Resolve-Pythonif ($null -eq $python) {- Write-Host "[x] Python is required but was not found (tried 'python' and 'py')." -ForegroundColor Red+ Write-Host "[x] Python is required but was not found (tried 'py -3', 'python3', and 'python')." -ForegroundColor Redexit 1}diff --git a/scripts/drift_baseline.py b/scripts/drift_baseline.pyindex 454c534..5b1a087 100644--- a/scripts/drift_baseline.py+++ b/scripts/drift_baseline.py@@ -20,6 +20,7 @@ import reimport sqlite3import subprocessimport sys+import tempfilefrom datetime import datetime, timezonefrom urllib.parse import parse_qs, urlparse, urlunparse, urlencode@@ -151,42 +152,58 @@ def fetch_page_data(url: str) -> dict:# Step 1: Fetch the page via fetch_page.pyfetch_script = os.path.join(SCRIPTS_DIR, "fetch_page.py")+ tmp_path = Nonetry:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ suffix=".html",+ prefix="claude-seo-drift-",+ delete=False,+ ) as tmp:+ tmp_path = tmp.name+proc = subprocess.run(- [sys.executable, fetch_script, url, "--output", "/dev/stdout"],+ [sys.executable, fetch_script, url, "--output", tmp_path],capture_output=True,text=True,+ encoding="utf-8",+ errors="replace",timeout=60,)- except subprocess.TimeoutExpired:- result["error"] = "Page fetch timed out after 60 seconds"- return result- if proc.returncode != 0:- error_msg = proc.stderr.strip() if proc.stderr else "Unknown fetch error"- result["error"] = f"Fetch failed: {error_msg}"- return result+ if proc.returncode != 0:+ error_msg = proc.stderr.strip() if proc.stderr else "Unknown fetch error"+ result["error"] = f"Fetch failed: {error_msg}"+ return result- html_content = proc.stdout+ with open(tmp_path, "r", encoding="utf-8", errors="replace") as f:+ html_content = f.read()- # Extract status code from stderr output (fetch_page.py prints "Status: NNN")- status_match = re.search(r"Status:\s*(\d+)", proc.stderr or "")- result["status_code"] = int(status_match.group(1)) if status_match else 200- result["html"] = html_content+ # Extract status code from stderr output (fetch_page.py prints "Status: NNN")+ status_match = re.search(r"Status:\s*(\d+)", proc.stderr or "")+ result["status_code"] = int(status_match.group(1)) if status_match else 200+ result["html"] = html_content- # Step 2: Parse the HTML via parse_html.py- parse_script = os.path.join(SCRIPTS_DIR, "parse_html.py")- try:+ # Step 2: Parse the HTML via parse_html.py+ parse_script = os.path.join(SCRIPTS_DIR, "parse_html.py")proc = subprocess.run(- [sys.executable, parse_script, "--url", url, "--json"],- input=html_content,+ [sys.executable, parse_script, tmp_path, "--url", url, "--json"],capture_output=True,text=True,+ encoding="utf-8",+ errors="replace",timeout=30,)except subprocess.TimeoutExpired:- result["error"] = "HTML parsing timed out after 30 seconds"+ result["error"] = "Page fetch or HTML parsing timed out"return result+ finally:+ if tmp_path and os.path.exists(tmp_path):+ try:+ os.unlink(tmp_path)+ except OSError:+ passif proc.returncode != 0:error_msg = proc.stderr.strip() if proc.stderr else "Unknown parse error"diff --git a/scripts/fetch_page.py b/scripts/fetch_page.pyindex 68d1a9b..92f9052 100755--- a/scripts/fetch_page.py+++ b/scripts/fetch_page.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport argparseimport os+import reimport sysfrom typing import Optional@@ -54,6 +55,54 @@ DEFAULT_HEADERS = {"Connection": "keep-alive",}+_CONTENT_TYPE_CHARSET_RE = re.compile(r"charset\s*=\s*['\"]?([^;,'\"\s>]+)", re.IGNORECASE)+_META_CHARSET_RE = re.compile(+ r"<meta[^>]+charset\s*=\s*['\"]?([^;,'\"\s/>]+)",+ re.IGNORECASE,+)+_BOMS = (+ (b"\xef\xbb\xbf", "utf-8-sig"),+ (b"\xff\xfe", "utf-16-le"),+ (b"\xfe\xff", "utf-16-be"),+)+++def _decode_bytes(raw: bytes, encoding: str) -> str:+ try:+ return raw.decode(encoding, errors="replace")+ except LookupError:+ return raw.decode("utf-8", errors="replace")+++def _extract_charset_from_content_type(content_type: str) -> str | None:+ match = _CONTENT_TYPE_CHARSET_RE.search(content_type or "")+ return match.group(1).strip() if match else None+++def _extract_meta_charset(raw: bytes) -> str | None:+ head = raw[:4096].decode("ascii", errors="ignore")+ match = _META_CHARSET_RE.search(head)+ return match.group(1).strip() if match else None+++def _decode_response_content(response) -> str:+ """Decode HTTP bytes deterministically for stable SEO snapshots."""+ raw = response.content or b""+ for marker, encoding in _BOMS:+ if raw.startswith(marker):+ return _decode_bytes(raw, encoding)++ content_type = response.headers.get("Content-Type", "") if response.headers else ""+ charset = _extract_charset_from_content_type(content_type)+ if charset:+ return _decode_bytes(raw, charset)++ charset = _extract_meta_charset(raw)+ if charset:+ return _decode_bytes(raw, charset)++ return raw.decode("utf-8", errors="replace")+def fetch_page(url: str,@@ -119,7 +168,7 @@ def fetch_page(result["url"] = response.urlresult["status_code"] = response.status_code- result["content"] = response.text+ result["content"] = _decode_response_content(response)result["headers"] = dict(response.headers)if response.history:diff --git a/tests/test_cross_platform_hooks.py b/tests/test_cross_platform_hooks.pynew file mode 100644index 0000000..2f6f95e--- /dev/null+++ b/tests/test_cross_platform_hooks.py@@ -0,0 +1,80 @@+"""Cross-platform hook configuration regressions."""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest+++REPO_ROOT = Path(__file__).resolve().parents[1]+HOOKS_JSON = REPO_ROOT / "hooks" / "hooks.json"+HOOK_LAUNCHER = REPO_ROOT / "hooks" / "run-python-hook.js"+INSTALL_PS1 = REPO_ROOT / "install.ps1"+++def _post_tool_handler() -> dict:+ config = json.loads(HOOKS_JSON.read_text(encoding="utf-8"))+ return config["hooks"]["PostToolUse"][0]["hooks"][0]+++def test_schema_hook_uses_exec_form_args_and_tool_input_placeholder() -> None:+ handler = _post_tool_handler()+ serialized = json.dumps(handler)++ assert handler["type"] == "command"+ assert handler["command"] == "node"+ assert "args" in handler+ assert handler["args"][0] == "${CLAUDE_PLUGIN_ROOT}/hooks/run-python-hook.js"+ assert handler["args"][1] == "${CLAUDE_PLUGIN_ROOT}/hooks/validate-schema.py"+ assert handler["args"][2] == "${tool_input.file_path}"+ assert "$FILE_PATH" not in serialized+ assert "$" not in handler["command"]+ assert handler["command"] != "sh"+++def test_hook_launcher_documents_python_probe_order() -> None:+ text = HOOK_LAUNCHER.read_text(encoding="utf-8")+ for marker in ("CLAUDE_SEO_PYTHON", "py", "-3", "python3", "python"):+ assert marker in text+++def test_hook_launcher_preserves_blocking_exit_code_two(tmp_path: Path) -> None:+ node = shutil.which("node")+ if not node:+ pytest.skip("node is not available in this test environment")++ script = tmp_path / "block.py"+ script.write_text(+ "import sys\n"+ "assert sys.argv[1] == 'payload'\n"+ "sys.exit(2)\n",+ encoding="utf-8",+ )+ env = os.environ.copy()+ env["CLAUDE_SEO_PYTHON"] = sys.executable++ proc = subprocess.run(+ [node, str(HOOK_LAUNCHER), str(script), "payload"],+ env=env,+ capture_output=True,+ text=True,+ timeout=15,+ )++ assert proc.returncode == 2+++def test_windows_installer_prefers_py_launcher_and_rejects_store_stubs() -> None:+ text = INSTALL_PS1.read_text(encoding="utf-8")+ py_pos = text.index("Exe = 'py'; Args = @('-3')")+ python3_pos = text.index("Exe = 'python3'; Args = @()")+ python_pos = text.index("Exe = 'python'; Args = @()")++ assert py_pos < python3_pos < python_pos+ assert "Microsoft Store|WindowsApps|App execution alias|was not found" in textdiff --git a/tests/test_drift_portability.py b/tests/test_drift_portability.pynew file mode 100644index 0000000..c421a85--- /dev/null+++ b/tests/test_drift_portability.py@@ -0,0 +1,56 @@+"""Portability regressions for drift baseline subprocess handoff."""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch+++REPO_ROOT = Path(__file__).resolve().parents[1]+SCRIPTS_DIR = REPO_ROOT / "scripts"+if str(SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(SCRIPTS_DIR))++import drift_baseline # noqa: E402+++def test_fetch_page_data_uses_tempfile_not_dev_stdout_or_stdin() -> None:+ calls: list[tuple[list[str], dict]] = []+ temp_paths: list[Path] = []++ def fake_run(cmd: list[str], **kwargs):+ calls.append((cmd, kwargs))+ assert kwargs["encoding"] == "utf-8"+ assert kwargs["errors"] == "replace"++ if cmd[1].endswith("fetch_page.py"):+ assert "/dev/stdout" not in cmd+ output_path = Path(cmd[cmd.index("--output") + 1])+ temp_paths.append(output_path)+ output_path.write_bytes(b"<html><title>caf\xc3\xa9 \x8f</title></html>")+ return SimpleNamespace(returncode=0, stdout="", stderr="Status: 203\n")++ if cmd[1].endswith("parse_html.py"):+ assert "input" not in kwargs+ assert Path(cmd[2]) == temp_paths[0]+ return SimpleNamespace(+ returncode=0,+ stdout=json.dumps({"title": "café �", "h1": [], "h2": [], "schema": []}),+ stderr="",+ )++ raise AssertionError(f"unexpected command: {cmd}")++ with patch.object(drift_baseline.subprocess, "run", side_effect=fake_run):+ result = drift_baseline.fetch_page_data("https://example.com/")++ assert result["error"] is None+ assert result["status_code"] == 203+ assert "café" in result["html"]+ assert result["parsed"]["title"] == "café �"+ assert all("/dev/stdout" not in cmd for cmd, _kwargs in calls)+ assert temp_paths and not os.path.exists(temp_paths[0])diff --git a/tests/test_fetch_page_decoding.py b/tests/test_fetch_page_decoding.pynew file mode 100644index 0000000..6608947--- /dev/null+++ b/tests/test_fetch_page_decoding.py@@ -0,0 +1,43 @@+"""Deterministic response decoding for fetch_page.py."""++from __future__ import annotations++import sys+from pathlib import Path+++REPO_ROOT = Path(__file__).resolve().parents[1]+SCRIPTS_DIR = REPO_ROOT / "scripts"+if str(SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(SCRIPTS_DIR))++import fetch_page # noqa: E402+++class FakeResponse:+ def __init__(self, content: bytes, content_type: str = "") -> None:+ self.content = content+ self.headers = {"Content-Type": content_type} if content_type else {}+++def test_no_charset_defaults_to_utf8_with_replacement() -> None:+ response = FakeResponse("Café".encode("utf-8"))+ assert fetch_page._decode_response_content(response) == "Café"+++def test_explicit_charset_from_content_type_wins() -> None:+ response = FakeResponse("Café".encode("iso-8859-1"), "text/html; charset=iso-8859-1")+ assert fetch_page._decode_response_content(response) == "Café"+++def test_meta_charset_is_used_when_header_has_no_charset() -> None:+ html = '<meta charset="windows-1252"><p>Smart quote: “</p>'.encode("windows-1252")+ response = FakeResponse(html, "text/html")+ assert "Smart quote: “" in fetch_page._decode_response_content(response)+++def test_invalid_bytes_are_replaced_not_dropped() -> None:+ response = FakeResponse(b"valid utf8 then invalid: \x8f")+ decoded = fetch_page._decode_response_content(response)+ assert "valid utf8" in decoded+ assert "\ufffd" in decoded