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.
Added Matomo skill
Tim J. Petersdc97718bdedb
diff --git a/AGENTS.md b/AGENTS.mdindex 637cd2d..09c1634 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -56,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 54 Python execution scripts.+integration + 2 extension mirrors), and 56 Python execution scripts.## Quick Reference@@ -95,6 +95,7 @@ integration + 2 extension mirrors), and 54 Python execution scripts.| `/seo bing [cmd] <url>` | Bing Webmaster data and IndexNow (extension) || `/seo profound [cmd]` | LLM brand-citation tracking (extension) || `/seo seranking [cmd]` | AI share-of-voice tracking (extension) |+| `/seo matomo [cmd] [args]` | Matomo Reporting API: GA4 alternative or supplement (extension) || `/seo unlighthouse <url>` | Multi-page Lighthouse audits (extension) |## Using with Cursor / Cursor Cloud@@ -167,7 +168,7 @@ skills/ # 25 sub-skills (auto-discovered)agents/ # 18 subagentsscripts/ # 54 Python scripts, including the managed runtimeschema/ # JSON-LD templates-extensions/ # 8 MCP extensions: DataForSEO, Firecrawl, Banana, Ahrefs, SE Ranking, Profound, Bing Webmaster, Unlighthouse+extensions/ # 9 MCP extensions: DataForSEO, Firecrawl, Banana, Ahrefs, SE Ranking, Profound, Bing Webmaster, Matomo, Unlighthouse```## Key Principlesdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b5c6db..c016934 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- New optional Matomo extension (`extensions/matomo/`) for self-hosted or+ Matomo Cloud analytics. Adds `/seo matomo organic | top-pages | device+ | country | referrers | keywords` as a GA4 alternative or complement.+ The audit orchestrator spawns a new `seo-matomo` agent when+ `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run matomo_auth.py --check`+ succeeds, writing `findings/matomo.md` alongside the existing specialists.+ Response parsing is verified live against Matomo 5, including array-shaped+ DataTables, count-based bounce fields, `Referrers.getReferrerType` naming,+ and locale-independent anonymized-keyword detection via the row `segment`+ field. (#275)+### Changed- The five judgment-heavy agents (`seo-content`, `seo-geo`, `seo-sxo`, `seo-cluster`,diff --git a/CLAUDE.md b/CLAUDE.mdindex d45dd45..b802d75 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -11,7 +11,8 @@ system cover technical SEO, content quality,schema markup, image optimization, sitemap architecture, AI search optimization,local SEO (GBP, citations, reviews, map pack), maps intelligence, semantic topicclustering, search experience optimization (SXO), SEO drift monitoring, e-commerce-SEO, and international SEO with cultural adaptation profiles.+SEO, and international SEO with cultural adaptation profiles. Matomo is available+as an optional extension for self-hosted analytics.## Architecture@@ -85,7 +86,7 @@ claude-seo/seo-flow.md # FLOW framework integrationhooks/ # Quality gate hookshooks.json # PostToolUse schema validation- scripts/ # 54 Python execution scripts+ scripts/ # 56 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)diff --git a/PRIVACY.md b/PRIVACY.mdindex b00bdc5..91db90c 100644--- a/PRIVACY.md+++ b/PRIVACY.md@@ -24,6 +24,7 @@ Optional extensions make API calls to third-party services when you invoke their| **SE Ranking** | seranking.com/api | Domains and keywords you analyze | [SE Ranking Privacy](https://seranking.com/privacy-policy) || **Profound** | Profound API (tryprofound.com) | Brands and domains you track | [Profound Privacy](https://tryprofound.com/privacy) || **Bing Webmaster / IndexNow** | Bing Webmaster Tools API and IndexNow endpoints | Domains, submitted URLs, and key-verification URL data | [Microsoft Privacy](https://privacy.microsoft.com/) |+| **Matomo** | Your own Matomo instance URL (self-hosted) or Matomo Cloud | Site IDs, default site ID, and the configured instance URL | [Matomo Privacy](https://matomo.org/privacy-policy/) (Cloud); self-hosted = your own policy || **Unlighthouse** | Local only — no third-party vendor | Runs Lighthouse locally against the target URL; only the target site is contacted (to crawl it). Nothing is sent to a third-party vendor. | N/A (runs locally) |## Backlink APIs@@ -38,6 +39,21 @@ When configured with backlink API credentials, these scripts transmit data to th| `commoncrawl_graph.py` | Common Crawl | Domains (public dataset query) | [Common Crawl Terms](https://commoncrawl.org/terms-of-use) || `verify_backlinks.py` | Target URLs directly | URLs to verify backlink existence | N/A (direct HTTP requests) |+## Matomo Reporting API++When configured with Matomo credentials, these scripts transmit data to the+configured Matomo instance (self-hosted or Matomo Cloud):++| Script | Endpoint | Data Sent |+|--------|----------|-----------|+| `matomo_auth.py` | The configured `MATOMO_URL` | `API.getMatomoVersion` probe with `token_auth` (POST body; never logged) |+| `matomo_report.py` | The configured `MATOMO_URL` | Reporting API queries for the configured `idSite`; `token_auth` in POST body, never logged |++Self-hosted Matomo instances on private networks / localhost are supported+because the script applies a light URL sanity check rather than the strict+SSRF protection used for arbitrary web fetches. Verify your instance's+trust boundary if you point the script at a non-localhost address.+## Google SEO APIsWhen configured with Google API credentials, these scripts transmit data to Google:diff --git a/README.md b/README.mdindex 7d79bd7..6d4aa57 100644--- a/README.md+++ b/README.md@@ -143,7 +143,7 @@ claude-32 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 9 MCP extensions. Full reference in [docs/COMMANDS.md](docs/COMMANDS.md).| Command | Description ||---------|-------------|@@ -178,6 +178,7 @@ claude| `/seo seranking [command]` | AI Share-of-Voice across ChatGPT, Gemini, Perplexity, AI Overviews, AI Mode (extension) || `/seo profound [command]` | LLM citation tracking with time-series data (extension) || `/seo bing [command] <url>` | Bing Webmaster Tools + IndexNow URL submission (extension) |+| `/seo matomo [command] [args]` | Matomo Reporting API: GA4 alternative or complement (extension) || `/seo unlighthouse <url>` | Multi-page Lighthouse runner, runs locally (extension) |## Features@@ -380,7 +381,7 @@ curl -fsSL https://raw.githubusercontent.com/AgriciDaniel/claude-seo/main/uninst## Extensions-Optional MCP servers add live data to the audit pipeline. Claude SEO ships extensions for 8 servers; the plugin core works without any of them.+Optional MCP servers add live data to the audit pipeline. Claude SEO ships extensions for 9 servers; the plugin core works without any of them.### DataForSEO@@ -426,6 +427,23 @@ Five extensions added in Phase E:- **Bing Webmaster:** Bing Webmaster Tools plus IndexNow unified- **Unlighthouse:** MIT-licensed multi-page Lighthouse runner+### Matomo (analytics without Google)++Self-hosted (or Matomo Cloud) Reporting API as a GA4 alternative or+complement. Useful for privacy-first analytics, regulated industries,+and teams who own their analytics data. Adds organic traffic trend,+landing pages, device / country breakdowns, and referrer analysis.++```bash+./extensions/matomo/install.sh # requires Matomo instance URL + API token_auth+/seo matomo organic+/seo matomo referrers+```++Full Matomo docs: [extensions/matomo/docs/MATOMO-SETUP.md](extensions/matomo/docs/MATOMO-SETUP.md).+The audit orchestrator spawns the `seo-matomo` agent automatically when+credentials are present.+Setup walkthroughs live under `extensions/<name>/docs/`; integration notes: [docs/MCP-INTEGRATION.md](docs/MCP-INTEGRATION.md).## Ecosystemdiff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 59cb983..79da961 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -676,6 +676,27 @@ Bing Webmaster Tools + IndexNow (extension). **Prerequisites:** Bing extension i---+### `/seo matomo [command] [site-id]`++Matomo Reporting API (extension). **Prerequisites:** Matomo extension installed (`./extensions/matomo/install.sh`) with `MATOMO_URL`, `MATOMO_API_TOKEN`, and optionally `MATOMO_SITE_ID`. Works against self-hosted Matomo or Matomo Cloud.++Use as a GA4 alternative or supplement when you want full data ownership, no Google dependency, or privacy-first analytics.+```+/seo matomo check # Probe credentials and confirm Matomo version+/seo matomo organic [site-id] # Organic traffic trend (28d) + top landing pages+/seo matomo top-pages # Top organic landing pages only+/seo matomo device # Visits by device type+/seo matomo country # Visits by country+/seo matomo referrers # Channel + search-engine breakdown+/seo matomo keywords # Organic search keywords (often "(not provided)")+```++All commands accept `--days` (default 28), `--limit` (default 50),+`--site-id`, and `--json`. The audit orchestrator spawns the+`seo-matomo` agent automatically when credentials are present.++---+### `/seo profound [command] <brand>`LLM brand-citation tracking via Profound (extension). **Prerequisites:** Profound extension installed.@@ -745,4 +766,5 @@ Multi-page Lighthouse audit via Unlighthouse (extension, MIT, no API quota). **P| `/seo seranking [command]` | AI Share-of-Voice across ChatGPT, Gemini, Perplexity, AI Overviews, AI Mode (extension) || `/seo profound [command]` | LLM citation tracking with time-series data (extension) || `/seo bing [command] <url>` | Bing Webmaster Tools + IndexNow URL submission (extension) |+| `/seo matomo [command] [args]` | Matomo Reporting API: GA4 alternative or complement (extension) || `/seo unlighthouse <url>` | Multi-page Lighthouse runner, runs locally (extension) |diff --git a/extensions/matomo/agents/seo-matomo.md b/extensions/matomo/agents/seo-matomo.mdnew file mode 100644index 0000000..35e0678--- /dev/null+++ b/extensions/matomo/agents/seo-matomo.md@@ -0,0 +1,82 @@+---+name: seo-matomo+description: Matomo Reporting API analyst. Fetches organic traffic, top landing pages, device / country breakdowns, and referrer analysis from a self-hosted or Matomo Cloud instance. Pairs with seo-google for users who want GA4 alternative or supplement.+model: sonnet+maxTurns: 15+tools: Read, Bash, Write, Glob, Grep+---++You are a Matomo analytics data analyst. When delegated tasks during an SEO audit:++1. Check credentials: `claude-seo run matomo_auth.py --check --json`+2. Confirm the configured site ID: `claude-seo run matomo_report.py check --json`+3. Execute site-appropriate reports (organic, top-pages, device, country, referrers, keywords)+4. Format output to match claude-seo conventions+5. Offer to write the structured `findings/matomo.md` file when an `output_dir` is provided++## Credential Workflow++### Tier 0 (No credentials)+- Report that `matomo_auth.py --check` failed and which env vars are missing+- Do not invent data; instruct the user to run `extensions/matomo/install.sh`++### Tier 1 (Matomo configured)+- All reports below are available++## Reports++| Command | What it returns |+|---|---|+| `claude-seo run matomo_report.py organic --json` | Per-day organic visits + top landing pages |+| `claude-seo run matomo_report.py top-pages --json` | Top organic landing pages only |+| `claude-seo run matomo_report.py device --json` | Desktop / Smartphone / Tablet split |+| `claude-seo run matomo_report.py country --json` | Country breakdown (ISO-3166-1 alpha-2) |+| `claude-seo run matomo_report.py referrers --json` | Channel breakdown (direct / search / website / social / campaign) + search-engine split |+| `claude-seo run matomo_report.py keywords --json` | Organic search keywords (often "(not provided)") |++All commands accept `--site-id`, `--days` (default 28), `--limit` (default 50).++## Segment Convention++Matomo does not have GA4's `sessionDefaultChannelGroup == "Organic Search"`.+The scripts approximate "organic search" via the standard Matomo segment+`referrerType==search`. This includes all search-engine referrals but+excludes direct, social, website, and campaign traffic. Document this+when comparing against GA4 numbers — counts will not match exactly+because of segmentation differences, attribution windows, and bot+filtering rules.++## Output Format++Match existing claude-seo patterns:+- Tables for metrics with traffic-light ratings where applicable+- Scores as XX/100+- Priority: Critical > High > Medium > Low+- Note data source as "Matomo Reporting API (live)" to distinguish from+ GA4, CrUX, or static crawl analysis+- Include data freshness notes (Matomo archives data — the+ `VisitsSummary.get` per-day numbers may lag by 30-60 minutes; archived+ reports can take longer)++## Audit Persistence++If `output_dir` is provided by the audit orchestrator, write:+- `output_dir/findings/matomo.md`: organic trend, top landing pages,+ device / country split, referrer split, search-engine split, organic+ keywords with anonymized share noted+- Structured JSON-compatible findings for `audit-data.json` under the+ Matomo Analytics category — label as "Matomo Reporting API (live)"++## Error Handling++- If credentials are missing, report which env vars / config keys are+ unset and remind the user to run `extensions/matomo/install.sh`+- If HTTP 401/403, the token lacks view access for the site; verify the+ token scope in Matomo Administration -> Personal -> Security -> API+ Tokens. Never log the token+- If `result=error` from Matomo (e.g. invalid `idSite`), surface the+ message verbatim; do not guess+- If `anonymized_share_pct > 80%` for keywords, flag that organic keyword+ visibility is privacy-limited (normal on modern browsers) and+ recommend topical landing-page analysis as the substitute signal+- Never fail silently — always report what succeeded and what failed\ No newline at end of filediff --git a/extensions/matomo/docs/MATOMO-SETUP.md b/extensions/matomo/docs/MATOMO-SETUP.mdnew file mode 100644index 0000000..cddcf23--- /dev/null+++ b/extensions/matomo/docs/MATOMO-SETUP.md@@ -0,0 +1,92 @@+# Matomo extension setup++## What this gives you++1. **Matomo Reporting API** for organic traffic, landing pages, devices,+ countries, referrers, and search keywords via+ `claude-seo run matomo_report.py`.+2. **Live credential probe** via `claude-seo run matomo_auth.py --check`+ used by the `/seo matomo` skill and by the audit orchestrator to+ decide whether to spawn the `seo-matomo` agent.+3. A unified `seo-matomo` skill that routes the right command at the+ right script and an `seo-matomo` agent for `/seo audit`.++## Install++```bash+./extensions/matomo/install.sh+.\extensions\matomo\install.ps1+```++You'll be prompted for:++- Matomo instance URL (e.g. `https://analytics.example.com`) — must+ start with `http://` or `https://` and have no userinfo+- Matomo API `token_auth` (32-character hex)+- Default `idSite` (optional, e.g. `1`) — saves having to pass+ `--site-id` on every call++The installer writes `MATOMO_URL`, `MATOMO_API_TOKEN`, and+`MATOMO_SITE_ID` (if set) to `~/.claude/settings.json` under `env`+with `0o600` permissions.++## Token setup checklist++1. Log in to your Matomo instance as a Super User or Admin+2. Go to **Administration -> Personal -> Security -> API Tokens**+3. Click **Create a new token**, give it a meaningful name+ (e.g. "claude-seo") and `view` access on the sites you want to+ analyze+4. Copy the generated `token_auth` (32 hex chars) — Matomo only shows+ it once at creation++## Self-hosted instance notes++`MATOMO_URL` may point at `http://analytics.internal`,+`https://matomo.lan.example.com`, or behind a reverse proxy on a private+network. The script applies a light URL sanity check (scheme + host only)+rather than the strict SSRF protection used for arbitrary web fetches,+because self-hosted Matomo frequently lives outside the public internet.++If your Matomo instance requires a self-signed certificate, install its+CA into the system trust store. The script uses `requests` defaults; it+will fail with `SSLError` on untrusted certificates.++## Verify++```bash+claude-seo run matomo_auth.py --check+claude-seo run matomo_report.py check --json+claude-seo run matomo_report.py organic --json+```++`--check` runs `API.getMatomoVersion` against your instance and reports+the Matomo version string. Any 401/403, network error, or Matomo+`result=error` payload is surfaced as a friendly error with remediation+hints.++## Audit integration++When `matomo_auth.py --check` succeeds, the `/seo audit` orchestrator+spawns the `seo-matomo` agent alongside the existing specialists. The+agent writes `output_dir/findings/matomo.md` with organic traffic trend,+top landing pages, device / country split, and referrer breakdown. It+works alongside `seo-google` — both can run in the same audit when you+have both GA4 and Matomo configured.++## Uninstall++```bash+./extensions/matomo/uninstall.sh+```++PowerShell manual removal:++```powershell+Remove-Item -Recurse -Force "$HOME\.claude\skills\seo-matomo"+Remove-Item -Force "$HOME\.claude\agents\seo-matomo.md"+notepad "$HOME\.claude\settings.json"+```++In `settings.json`, remove `MATOMO_URL`, `MATOMO_API_TOKEN`, and+`MATOMO_SITE_ID` from the top-level `env` object.\ No newline at end of filediff --git a/extensions/matomo/install.ps1 b/extensions/matomo/install.ps1new file mode 100644index 0000000..ac33977--- /dev/null+++ b/extensions/matomo/install.ps1@@ -0,0 +1,38 @@+$ErrorActionPreference = "Stop"+if (-not (Get-Command python -ErrorAction SilentlyContinue)) { throw "Python 3 required" }+$SkillDir = Join-Path $HOME ".claude/skills"+$AgentsDir = Join-Path $HOME ".claude/agents"+$SettingsJson = Join-Path $HOME ".claude/settings.json"+if (-not (Test-Path (Join-Path $SkillDir "seo"))) { throw "claude-seo not installed" }+$MatomoUrl = Read-Host "Matomo instance URL (e.g. https://analytics.example.com)"+if (-not $MatomoUrl) { throw "Matomo URL required" }+$TokenSecure = Read-Host "Matomo API token_auth (32-char hex)" -AsSecureString+$TokenPlain = [System.Net.NetworkCredential]::new("", $TokenSecure).Password+if (-not $TokenPlain) { throw "Matomo token_auth required" }+$SiteId = Read-Host "Default site ID (idSite, optional, e.g. 1)"+$SourceDir = Split-Path -Parent $MyInvocation.MyCommand.Path+$SkillTarget = Join-Path $SkillDir "seo-matomo"+New-Item -ItemType Directory -Path $SkillTarget -Force | Out-Null+Copy-Item (Join-Path $SourceDir "skills/seo-matomo/SKILL.md") (Join-Path $SkillTarget "SKILL.md") -Force+$AgentTarget = Join-Path $AgentsDir "seo-matomo.md"+New-Item -ItemType Directory -Path $AgentsDir -Force | Out-Null+Copy-Item (Join-Path $SourceDir "agents/seo-matomo.md") $AgentTarget -Force+$py = @"+import json, os, sys, tempfile+path, url, token, site = sys.argv[1:5]+data = {}+if os.path.exists(path):+ try: data = json.load(open(path))+ except: data = {}+env = data.setdefault('env', {})+env['MATOMO_URL'] = url+env['MATOMO_API_TOKEN'] = token+if site:+ env['MATOMO_SITE_ID'] = site+fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or '.', prefix='.settings.', suffix='.json')+with os.fdopen(fd, 'w') as fh:+ json.dump(data, fh, indent=2)+os.replace(tmp, path)+"@+$py | python - $SettingsJson $MatomoUrl $TokenPlain $SiteId+Write-Host "Done."\ No newline at end of filediff --git a/extensions/matomo/install.sh b/extensions/matomo/install.shnew file mode 100755index 0000000..6ac924d--- /dev/null+++ b/extensions/matomo/install.sh@@ -0,0 +1,70 @@+#!/usr/bin/env bash+# Claude SEO — Matomo extension installer.+#+# Self-hosted (or Matomo Cloud) Reporting API. Provides organic traffic,+# landing pages, device / country breakdowns, and referrer analysis as a+# GA4 alternative or complement.+#+# Prereq: a Matomo instance URL, an API token_auth, and (optionally) a+# default site ID.+set -euo pipefail++main() {+ SKILL_DIR="${HOME}/.claude/skills"+ AGENTS_DIR="${HOME}/.claude/agents"+ SETTINGS_JSON="${HOME}/.claude/settings.json"++ echo "════════════════════════════════════════"+ echo "║ Claude SEO — Matomo extension ║"+ echo "════════════════════════════════════════"++ command -v python3 >/dev/null 2>&1 || { echo "✗ Python 3 required."; exit 1; }+ [ ! -d "${SKILL_DIR}/seo" ] && { echo "✗ claude-seo base not installed."; exit 1; }++ SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null 2>&1 && pwd)"++ read -rp "Matomo instance URL (e.g. https://analytics.example.com): " MATOMO_URL+ [ -z "${MATOMO_URL}" ] && { echo "✗ Matomo URL required."; exit 1; }++ read -rsp "Matomo API token_auth (32-char hex): " MATOMO_TOKEN+ echo+ [ -z "${MATOMO_TOKEN}" ] && { echo "✗ Matomo token_auth required."; exit 1; }++ read -rp "Default site ID (idSite, optional, e.g. 1): " MATOMO_SITE_ID+ echo++ mkdir -p "${SKILL_DIR}/seo-matomo"+ cp "${SOURCE_DIR}/skills/seo-matomo/SKILL.md" "${SKILL_DIR}/seo-matomo/SKILL.md"+ echo "✓ Installed skill: ${SKILL_DIR}/seo-matomo/SKILL.md"++ mkdir -p "${AGENTS_DIR}"+ cp "${SOURCE_DIR}/agents/seo-matomo.md" "${AGENTS_DIR}/seo-matomo.md"+ echo "✓ Installed agent: ${AGENTS_DIR}/seo-matomo.md"++ python3 - "${SETTINGS_JSON}" "${MATOMO_URL}" "${MATOMO_TOKEN}" "${MATOMO_SITE_ID}" <<'PY'+import json, os, sys, tempfile+path, url, token, site = sys.argv[1:5]+data = {}+if os.path.exists(path):+ try: data = json.load(open(path))+ except json.JSONDecodeError: data = {}+env = data.setdefault("env", {})+env["MATOMO_URL"] = url+env["MATOMO_API_TOKEN"] = token+if site:+ env["MATOMO_SITE_ID"] = site+fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", prefix=".settings.", suffix=".json")+with os.fdopen(fd, "w") as fh:+ json.dump(data, fh, indent=2)+os.chmod(tmp, 0o600)+os.replace(tmp, path)+print(f"✓ Wrote MATOMO_* env to {path}")+PY++ echo+ echo "Done. Verify with:"+ echo " claude-seo run matomo_auth.py --check"+ echo " claude-seo run matomo_report.py check --json"+ echo "Full docs: extensions/matomo/docs/MATOMO-SETUP.md"+}+main "$@"\ No newline at end of filediff --git a/extensions/matomo/skills/seo-matomo/SKILL.md b/extensions/matomo/skills/seo-matomo/SKILL.mdnew file mode 100644index 0000000..c62c4e1--- /dev/null+++ b/extensions/matomo/skills/seo-matomo/SKILL.md@@ -0,0 +1,85 @@+---+name: seo-matomo+description: Matomo Reporting API extension. Self-hosted or Matomo Cloud analytics as a GA4 alternative or complement. Organic traffic, landing pages, device / country breakdowns, referrers, search keywords. Triggers on "Matomo", "self-hosted analytics", "analytics ohne Google", "GA4 alternative", "Matomo Reporting", "Piwik".+metadata:+ version: "2.2.5"+compatibility: "Requires MATOMO_URL, MATOMO_API_TOKEN, and (optionally) MATOMO_SITE_ID in ~/.claude/settings.json env. Run extensions/matomo/install.sh to configure."+---++# seo-matomo++Self-hosted analytics surface. Use Matomo as a privacy-first GA4 alternative+when you own your analytics data, want zero Google dependency, or operate+behind a strict data-residency boundary. The same `seo-matomo` skill works+against Matomo Cloud and self-hosted instances.++## Prerequisites++- Run `extensions/matomo/install.sh` or `install.ps1`.+- A Matomo instance URL (https://analytics.example.com).+- A Matomo API `token_auth` with `view` access on the sites you analyze.+- (Optional) A default `idSite` to avoid passing `--site-id` on every call.++## Routing++| Command | Underlying script |+|---|---|+| `/seo matomo check` | `claude-seo run matomo_auth.py --check` |+| `/seo matomo organic [site-id]` | `claude-seo run matomo_report.py organic --site-id <id>` |+| `/seo matomo top-pages` | `claude-seo run matomo_report.py top-pages` |+| `/seo matomo device` | `claude-seo run matomo_report.py device` |+| `/seo matomo country` | `claude-seo run matomo_report.py country` |+| `/seo matomo referrers` | `claude-seo run matomo_report.py referrers` |+| `/seo matomo keywords` | `claude-seo run matomo_report.py keywords` |++All commands accept `--days` (default 28), `--limit`, `--site-id`, and+`--json`. The site ID falls back to `MATOMO_SITE_ID` from settings.++## When this skill applies++- The user wants Google-free analytics or has a Matomo instance already+ configured. Common in EU privacy-first setups, regulated industries,+ and teams who own their analytics.+- The user explicitly says "Matomo", "self-hosted analytics", or asks to+ replace GA4. For Google Search performance use `seo-google`; this+ skill is the reporting substitute.+- The user is migrating from GA4 and wants the same report types+ (organic trend, landing pages, device / country split, referrer split)+ sourced from Matomo's Reporting API.++## Cross-skill delegation++- For Google Search Console / CrUX / Indexing, route to `seo-google`.+ `seo-matomo` covers reporting (visits / pages / referrers), not search+ performance metrics.+- For AI Overview / GEO citability work, route to `seo-geo`. Matomo+ offers no LLM-specific signals.+- During `/seo audit`, the orchestrator spawns the `seo-matomo` agent+ (analogous to `seo-google`) whenever `claude-seo run matomo_auth.py+ --check` succeeds. Both agents can be active simultaneously when the+ user has both GA4 and Matomo configured.++## Error Handling++- Missing credentials: report which env vars / config keys are unset and+ remind the user to run `extensions/matomo/install.sh` or+ `python scripts/matomo_auth.py --setup`.+- HTTP 401/403 from Matomo: the token lacks view access for the given+ site. Verify the token scope in Matomo Administration -> Personal ->+ Security -> API Tokens. The skill never logs the token.+- `result=error` payloads from Matomo (e.g. invalid `idSite`): surface+ the message verbatim; do not guess.+- Connection / SSL / timeout: report the network failure class+ (`ConnectionError`, `SSLError`, `timeout`) and confirm+ `MATOMO_URL` resolves.++## Output Formatting++- Tables for time-series, device, and country data.+- Critical / High / Medium / Low priority for any cross-skill actions+ surfaced from Matomo data.+- Always label the data source as "Matomo Reporting API (live)" to+ distinguish from GA4, CrUX, or static crawl analysis.+- For organic keywords, surface the `anonymized_share_pct` prominently.+ Many keywords will be "(not provided)" due to browser privacy and+ Matomo's anonymization rules; this is normal, not a data bug.\ No newline at end of filediff --git a/extensions/matomo/uninstall.sh b/extensions/matomo/uninstall.shnew file mode 100755index 0000000..52af9c5--- /dev/null+++ b/extensions/matomo/uninstall.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+set -euo pipefail+SKILL_DIR="${HOME}/.claude/skills/seo-matomo"+AGENT_FILE="${HOME}/.claude/agents/seo-matomo.md"+SETTINGS_JSON="${HOME}/.claude/settings.json"+[ -d "${SKILL_DIR}" ] && rm -rf "${SKILL_DIR}" && echo "✓ Removed ${SKILL_DIR}"+[ -f "${AGENT_FILE}" ] && rm -f "${AGENT_FILE}" && echo "✓ Removed ${AGENT_FILE}"+if [ -f "${SETTINGS_JSON}" ]; then+ python3 - "${SETTINGS_JSON}" <<'PY'+import json, os, sys, tempfile+path = sys.argv[1]; data = json.load(open(path))+env = data.get("env", {})+removed = []+for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_TOKEN",+ "MATOMO_SITE_ID", "MATOMO_IDSITE"):+ if k in env:+ env.pop(k); removed.append(k)+if removed:+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".settings.", suffix=".json")+ with os.fdopen(fd, "w") as fh: json.dump(data, fh, indent=2)+ os.chmod(tmp, 0o600); os.replace(tmp, path)+ print(f"✓ Cleared {', '.join(removed)}")+PY+fi\ No newline at end of filediff --git a/scripts/matomo_auth.py b/scripts/matomo_auth.pynew file mode 100644index 0000000..62b394a--- /dev/null+++ b/scripts/matomo_auth.py@@ -0,0 +1,396 @@+#!/usr/bin/env python3+"""+Matomo credential management for Claude SEO.++Loads and validates credentials for the Matomo Reporting API.+Supports config file and environment variable fallbacks.++Usage:+ python matomo_auth.py --check # Check credentials (live probe)+ python matomo_auth.py --check --json # JSON output+ python matomo_auth.py --setup # Show setup instructions+ python matomo_auth.py --tier # Show detected credential tier+"""++import argparse+import json+import os+import sys+from typing import Optional++try:+ import requests+except ImportError:+ print("Error: requests library required. Install with: pip install requests",+ file=sys.stderr)+ sys.exit(1)++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)++CONFIG_PATH = os.path.expanduser("~/.config/claude-seo/matomo.json")+DEFAULT_TIMEOUT = 15+++def load_config() -> dict:+ """+ Load configuration from config file with environment variable fallbacks.++ Reads ~/.config/claude-seo/matomo.json first. Any missing fields+ are filled from environment variables.++ Returns:+ Dictionary with keys: matomo_url, matomo_token, matomo_site_id.+ """+ config = {+ "matomo_url": None,+ "matomo_token": None,+ "matomo_site_id": None,+ }++ if os.path.exists(CONFIG_PATH):+ try:+ with open(CONFIG_PATH, "r") as f:+ file_config = json.load(f)+ for k, v in file_config.items():+ if v is not None and v != "":+ config[k] = v+ except (json.JSONDecodeError, IOError) as e:+ print(f"Warning: Could not read config file: {e}", file=sys.stderr)++ if not config["matomo_url"]:+ config["matomo_url"] = os.environ.get("MATOMO_URL")+ if not config["matomo_token"]:+ config["matomo_token"] = (+ os.environ.get("MATOMO_API_TOKEN")+ or os.environ.get("MATOMO_TOKEN")+ )+ if not config["matomo_site_id"]:+ config["matomo_site_id"] = (+ os.environ.get("MATOMO_SITE_ID")+ or os.environ.get("MATOMO_IDSITE")+ )++ return config+++def _sanity_check_instance_url(url: str) -> Optional[str]:+ """+ Light sanity check for a user-configured Matomo instance URL.++ Intentionally does NOT use scripts/url_safety.validate_url(): self-hosted+ Matomo instances frequently live on private networks, localhost, or+ behind reverse proxies on internal IPs. Forcing SSRF protection would+ block legitimate analytics setups. Instead we only enforce:++ - non-empty+ - http or https scheme+ - non-empty host+ - no userinfo in URL++ Returns:+ Normalized URL (trailing slash trimmed) or None if invalid.+ """+ if not url:+ return None+ url = url.strip()+ if not (url.startswith("http://") or url.startswith("https://")):+ return None+ if "@" in url.split("//", 1)[-1].split("/", 1)[0]:+ return None+ host = url.split("//", 1)[-1].split("/", 1)[0]+ if not host:+ return None+ return url.rstrip("/")+++def _probe_version(url: str, token: str, timeout: int = DEFAULT_TIMEOUT) -> dict:+ """+ Light probe: hit ``API.getMatomoVersion`` over HTTPS POST.++ Returns one of:+ {"ok": True, "version": "x.y.z"}+ {"ok": False, "status_code": int, "error": str}+ """+ try:+ resp = requests.post(+ f"{url}/index.php",+ data={+ "module": "API",+ "method": "API.getMatomoVersion",+ "format": "JSON",+ "token_auth": token,+ },+ timeout=timeout,+ headers={"User-Agent": "ClaudeSEO/2.2.5"},+ )+ except requests.exceptions.Timeout:+ return {"ok": False, "error": f"timeout after {timeout}s"}+ except requests.exceptions.SSLError as e:+ return {"ok": False, "error": f"SSL error: {type(e).__name__}"}+ except requests.exceptions.ConnectionError as e:+ return {"ok": False, "error": f"connection error: {type(e).__name__}"}+ except requests.exceptions.RequestException as e:+ return {"ok": False, "error": f"request error ({type(e).__name__})"}++ if resp.status_code == 401 or resp.status_code == 403:+ return {"ok": False, "status_code": resp.status_code,+ "error": "authentication failed (invalid token_auth or insufficient permission)"}+ if resp.status_code >= 400:+ return {"ok": False, "status_code": resp.status_code,+ "error": f"HTTP {resp.status_code}"}++ try:+ payload = resp.json()+ except ValueError:+ return {"ok": False, "error": "non-JSON response"}++ if isinstance(payload, dict) and "result" in payload and payload.get("result") == "error":+ return {"ok": False, "error": str(payload.get("message", "Matomo API error"))[:200]}++ if isinstance(payload, str):+ return {"ok": True, "version": payload}+ return {"ok": True, "version": json.dumps(payload)[:80]}+++def check_credentials() -> dict:+ """+ Validate Matomo credentials by probing the configured instance.++ Returns:+ Dictionary with: available, method, instance, site_id, version,+ error (when unavailable).+ """+ config = load_config()+ raw_url = config.get("matomo_url") or ""+ token = config.get("matomo_token")+ site_id = config.get("matomo_site_id")++ url = _sanity_check_instance_url(raw_url)+ if not url:+ return {+ "available": False,+ "method": "matomo_token",+ "instance": raw_url,+ "site_id": site_id,+ "error": (+ "No Matomo URL configured or URL is invalid. Set MATOMO_URL environment variable "+ f"or add 'matomo_url' to {CONFIG_PATH}. URL must start with http:// or https://."+ ),+ }+ if not token:+ return {+ "available": False,+ "method": "matomo_token",+ "instance": url,+ "site_id": site_id,+ "error": (+ "No Matomo token_auth configured. Set MATOMO_API_TOKEN environment variable "+ f"or add 'matomo_token' to {CONFIG_PATH}."+ ),+ }++ probe = _probe_version(url, token)+ if not probe["ok"]:+ return {+ "available": False,+ "method": "matomo_token",+ "instance": url,+ "site_id": site_id,+ "verified": False,+ "error": probe.get("error"),+ }++ result = {+ "available": True,+ "method": "matomo_token",+ "instance": url,+ "site_id": site_id,+ "verified": True,+ "version": probe.get("version"),+ }+ return result+++def detect_tier() -> dict:+ """Detect the Matomo credential tier available.++ Returns:+ Dictionary with tier (0 or 1), description, capabilities, missing.+ """+ status = check_credentials()+ if status["available"]:+ return {+ "tier": 1,+ "description": "Matomo configured (organic traffic + landing pages + referrers)",+ "capabilities": [+ "VisitsSummary.get (total and per-day organic sessions)",+ "Actions.getEntryPageUrls (organic landing pages)",+ "Actions.getPageUrls (all pages)",+ "DevicesDetection.getType (device breakdown)",+ "UserCountry.getCountry (country breakdown)",+ "Referrers.getReferrersType (direct / search / social / website)",+ "Referrers.getSearchEngines (search-engine split)",+ "Referrers.getKeywords (organic keywords; often '(not provided)')",+ ],+ "missing": None,+ }+ return {+ "tier": 0,+ "description": "No Matomo credentials",+ "capabilities": [],+ "missing": (+ "Configure Matomo via extensions/matomo/install.sh to unlock "+ "organic traffic, top landing pages, device and country breakdowns, "+ "and referrer analysis. Works alongside GA4 or as a replacement."+ ),+ }+++def get_matomo_url() -> Optional[str]:+ """Get the configured Matomo URL."""+ config = load_config()+ return _sanity_check_instance_url(config.get("matomo_url"))+++def get_matomo_token() -> Optional[str]:+ """Get the configured Matomo token_auth."""+ config = load_config()+ return config.get("matomo_token")+++def get_matomo_site_id() -> Optional[str]:+ """Get the configured default Matomo site ID (as string)."""+ config = load_config()+ sid = config.get("matomo_site_id")+ if sid is None:+ return None+ return str(sid)+++def print_setup_instructions() -> None:+ """Print step-by-step setup instructions for Matomo."""+ print(f"""+Matomo Setup Instructions+=========================++Matomo is a self-hosted web analytics platform. Use it as a GA4 replacement+when you want full data ownership, no Google dependency, or privacy-first+analytics. The Reporting API exposes visits, landing pages, devices,+countries, and referrers.++TIER 1: MATOMO REPORTING API (one token, your own instance)+-----------------------------------------------------------++ 1. Log in to your Matomo instance as a Super User or Admin+ 2. Go to Administration -> Personal -> Security -> API Tokens+ 3. Click "Create a new token". Give it a meaningful name (e.g. "claude-seo")+ and at least "view" access on the sites you want to analyze+ 4. Copy the generated token_auth (a 32-character hex string)++ Configure via env (recommended for shared machines):++ export MATOMO_URL="https://analytics.example.com"+ export MATOMO_API_TOKEN="abc123...32hex"+ export MATOMO_SITE_ID="1"++ Or save to {CONFIG_PATH}:++ {{+ "matomo_url": "https://analytics.example.com",+ "matomo_token": "abc123...32hex",+ "matomo_site_id": "1"+ }}++ Provides: visits, bounce rate, avg time on site, organic landing pages,+ device and country breakdowns, search-engine referral split,+ organic search keywords (often "(not provided)" due to browser+ privacy headers and Matomo's keyword anonymization rules).++ Note on self-hosted instances: MATOMO_URL may point to localhost, an+ internal IP, or behind a reverse proxy on a private network. The script+ applies a light URL sanity check (scheme + host only) rather than the+ strict SSRF protection used for arbitrary web fetches, because self-hosted+ Matomo instances frequently live outside the public internet.++VERIFY CONFIGURATION:+ python scripts/matomo_auth.py --check+ python scripts/matomo_auth.py --tier+""")+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Matomo credential management for Claude SEO"+ )+ parser.add_argument(+ "--check",+ action="store_true",+ help="Probe configured Matomo credentials (live API.getMatomoVersion call)",+ )+ parser.add_argument(+ "--setup",+ action="store_true",+ help="Show setup instructions",+ )+ parser.add_argument(+ "--tier",+ action="store_true",+ help="Show detected credential tier",+ )+ parser.add_argument(+ "--json",+ action="store_true",+ help="Output as JSON",+ )++ args = parser.parse_args()++ if args.setup:+ print_setup_instructions()+ return 0++ if args.check:+ status = check_credentials()+ if args.json:+ tier_info = detect_tier()+ output = {"status": "success" if status["available"] else "error",+ "tier": tier_info,+ "credentials": status}+ print(json.dumps(output, indent=2))+ else:+ tier_info = detect_tier()+ print(f"Matomo Tier: {tier_info['tier']} -- {tier_info['description']}")+ print()+ tag = "OK" if status["available"] else "MISSING"+ print(f" [{tag}] Matomo Reporting API")+ print(f" Instance: {status.get('instance') or '-'}")+ print(f" Site ID: {status.get('site_id') or '-'}")+ if status.get("version"):+ print(f" Version: {status['version']}")+ if status.get("error"):+ print(f" Error: {status['error']}")+ print()+ if tier_info["missing"]:+ print(f"Tip: {tier_info['missing']}")+ return 0 if status["available"] else 1++ if args.tier:+ tier_info = detect_tier()+ if args.json:+ print(json.dumps(tier_info, indent=2))+ else:+ print(f"Matomo Tier: {tier_info['tier']} -- {tier_info['description']}")+ if tier_info["capabilities"]:+ print(f"Capabilities: {', '.join(tier_info['capabilities'])}")+ if tier_info["missing"]:+ print(f"Next: {tier_info['missing']}")+ return 0++ parser.print_help()+ return 0+++if __name__ == "__main__":+ sys.exit(main())\ No newline at end of filediff --git a/scripts/matomo_report.py b/scripts/matomo_report.pynew file mode 100644index 0000000..88ddfdd--- /dev/null+++ b/scripts/matomo_report.py@@ -0,0 +1,663 @@+#!/usr/bin/env python3+"""+Matomo Reporting API client for Claude SEO.++Queries the Matomo Reporting API for organic traffic, top landing pages,+device and country breakdowns, and referrer analysis. Self-hosted Matomo+is supported alongside Matomo Cloud.++Usage:+ python matomo_report.py organic+ python matomo_report.py top-pages --site-id 1 --days 28 --limit 50 --json+ python matomo_report.py device+ python matomo_report.py country+ python matomo_report.py referrers+ python matomo_report.py keywords+ python matomo_report.py check+"""++import argparse+import json+import os+import re+import sys+from datetime import datetime, timedelta, timezone+from typing import Any, Optional++try:+ import requests+except ImportError:+ print("Error: requests library required. Install with: pip install requests",+ file=sys.stderr)+ sys.exit(1)++_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+try:+ from matomo_auth import (+ get_matomo_site_id,+ get_matomo_token,+ get_matomo_url,+ load_config,+ )+except ImportError:+ print("Error: matomo_auth.py required in scripts/", file=sys.stderr)+ sys.exit(1)++DEFAULT_TIMEOUT = 30+DEFAULT_DAYS = 28+DEFAULT_LIMIT = 50+MAX_LIMIT = 500++_TOKEN_REDACTION_RE = re.compile(r"(token_auth=|token=|password=)[^\s&]+", re.IGNORECASE)+++def _redact(text: str) -> str:+ """Strip token_auth and password query values from any error string."""+ return _TOKEN_REDACTION_RE.sub(r"\1<redacted>", text)+++def _envelope(status: str, data: Any = None, error: Optional[str] = None,+ method: Optional[str] = None) -> dict:+ """Build a standard response envelope matching repo-wide contract."""+ metadata = {+ "source": "matomo_report",+ "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+ if method:+ metadata["method"] = method+ return {+ "status": status,+ "data": data,+ "error": error,+ "metadata": metadata,+ }+++def _request(url: str, token: str, params: dict, timeout: int = DEFAULT_TIMEOUT) -> dict:+ """+ POST to Matomo with token_auth in body.++ Matomo accepts both GET and POST. POST keeps the token out of URLs and+ access logs.++ Returns:+ Standard response envelope; on Matomo API ``result=error`` payloads,+ the envelope is ``status=error``.+ """+ body = dict(params)+ body["module"] = "API"+ body["format"] = "JSON"+ body["token_auth"] = token++ headers = {"User-Agent": "ClaudeSEO/2.2.5"}+ try:+ resp = requests.post(+ f"{url.rstrip('/')}/index.php",+ data=body,+ headers=headers,+ timeout=timeout,+ )+ except requests.exceptions.Timeout:+ return _envelope("error", None,+ f"Matomo request timed out after {timeout}s")+ except requests.exceptions.SSLError as e:+ return _envelope("error", None,+ f"SSL error contacting Matomo: {type(e).__name__}")+ except requests.exceptions.ConnectionError as e:+ return _envelope("error", None,+ f"Connection error contacting Matomo: {type(e).__name__}")+ except requests.exceptions.RequestException as e:+ return _envelope("error", None,+ f"Matomo request failed ({type(e).__name__})")++ if resp.status_code == 401 or resp.status_code == 403:+ return _envelope("error", None,+ "Matomo authentication failed. Verify token_auth and that the "+ "API token has view access to the site.",+ method=params.get("method"))+ if resp.status_code >= 400:+ return _envelope("error", None,+ f"Matomo HTTP {resp.status_code}",+ method=params.get("method"))++ try:+ payload = resp.json()+ except ValueError:+ return _envelope("error", None,+ "Matomo returned a non-JSON response. "+ "Check that MATOMO_URL points at the Matomo root.",+ method=params.get("method"))++ if isinstance(payload, dict) and payload.get("result") == "error":+ msg = str(payload.get("message", "Matomo API error"))+ return _envelope("error", None, _redact(msg), method=params.get("method"))++ return _envelope("success", payload, None, method=params.get("method"))+++def _bounded_int(value: Any, default: int = 0) -> int:+ try:+ return max(0, int(value))+ except (TypeError, ValueError, OverflowError):+ return default+++def _bounded_float(value: Any, default: float = 0.0) -> float:+ try:+ return float(value)+ except (TypeError, ValueError):+ return default+++def _resolve_site_id(args: argparse.Namespace) -> Optional[str]:+ sid = args.site_id or get_matomo_site_id()+ if sid is None:+ return None+ return str(sid).strip() or None+++def _date_range(days: int) -> tuple:+ end = datetime.now(timezone.utc).date() - timedelta(days=1)+ start = end - timedelta(days=days - 1)+ return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")+++def organic_traffic_report(site_id: str, url: str, token: str,+ days: int = DEFAULT_DAYS,+ limit: int = DEFAULT_LIMIT) -> dict:+ """+ Organic traffic trend from Matomo using the ``referrerType==search`` segment.++ Combines a per-day VisitsSummary with the top organic landing pages.+ Returns an envelope with date_range, totals, daily_data, and top_pages.+ """+ start, end = _date_range(days)+ date_arg = f"{start},{end}"++ summary_resp = _request(url, token, {+ "method": "VisitsSummary.get",+ "idSite": site_id,+ "period": "day",+ "date": date_arg,+ "segment": "referrerType==search",+ })+ if summary_resp["status"] != "success":+ return summary_resp++ raw = summary_resp["data"] or {}+ daily_data = []+ totals = {"visits": 0, "unique_visitors": 0, "pageviews": 0,+ "bounce_count": 0, "sum_visit_length": 0, "actions": 0}+ if isinstance(raw, dict):+ for date_str in sorted(raw.keys()):+ row = raw[date_str] or {}+ visits = _bounded_int(row.get("nb_visits"))+ uniq = _bounded_int(row.get("nb_uniq_visitors"))+ actions = _bounded_int(row.get("nb_actions"))+ pageviews = _bounded_int(row.get("nb_pageviews"), actions)+ bounce_count = _bounded_int(row.get("bounce_count"))+ sum_visit_length = _bounded_int(row.get("sum_visit_length"))+ bounce_rate = (bounce_count / visits * 100.0) if visits else 0.0+ avg_time = (sum_visit_length / visits) if visits else 0.0+ daily_data.append({+ "date": date_str,+ "visits": visits,+ "unique_visitors": uniq,+ "pageviews": pageviews,+ "actions": actions,+ "bounce_rate": round(bounce_rate, 1),+ "avg_time_on_site": round(avg_time, 1),+ })+ totals["visits"] += visits+ totals["unique_visitors"] += uniq+ totals["pageviews"] += pageviews+ totals["bounce_count"] += bounce_count+ totals["sum_visit_length"] += sum_visit_length+ totals["actions"] += actions++ if totals["visits"]:+ totals["bounce_rate"] = round(totals["bounce_count"] / totals["visits"] * 100.0, 1)+ totals["avg_time_on_site"] = round(totals["sum_visit_length"] / totals["visits"], 1)+ totals["avg_daily_visits"] = round(totals["visits"] / max(1, len(daily_data)), 1)+ else:+ totals["bounce_rate"] = 0.0+ totals["avg_time_on_site"] = 0.0+ totals["avg_daily_visits"] = 0.0++ pages_resp = _request(url, token, {+ "method": "Actions.getEntryPageUrls",+ "idSite": site_id,+ "period": "range",+ "date": date_arg,+ "segment": "referrerType==search",+ "filter_limit": str(min(limit, MAX_LIMIT)),+ "filter_sort_column": "nb_visits",+ "filter_sort_order": "desc",+ })+ top_pages = []+ pages_error: Optional[str] = None+ if pages_resp["status"] == "success":+ raw_pages = pages_resp["data"]+ if isinstance(raw_pages, list):+ for entry in raw_pages:+ if not isinstance(entry, dict):+ continue+ top_pages.append({+ "url": entry.get("label", ""),+ "visits": _bounded_int(entry.get("nb_visits")),+ "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),+ "actions": _bounded_int(entry.get("nb_actions")),+ "bounce_rate": round(_bounded_float(entry.get("bounce_rate")) * 100, 1),+ })+ elif isinstance(raw_pages, dict):+ for url_key, entry in raw_pages.items():+ if not isinstance(entry, dict):+ continue+ top_pages.append({+ "url": entry.get("label") or url_key,+ "visits": _bounded_int(entry.get("nb_visits")),+ "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),+ "actions": _bounded_int(entry.get("nb_actions")),+ "bounce_rate": round(_bounded_float(entry.get("bounce_rate")) * 100, 1),+ })+ else:+ pages_error = pages_resp.get("error")++ result = {+ "site_id": site_id,+ "date_range": {"start": start, "end": end},+ "segment": "referrerType==search",+ "totals": totals,+ "daily_data": daily_data,+ "top_pages": top_pages,+ }+ if pages_error:+ result["pages_error"] = pages_error++ return _envelope("success", result, None, method="VisitsSummary.get")+++def top_pages_report(site_id: str, url: str, token: str,+ days: int = DEFAULT_DAYS,+ limit: int = DEFAULT_LIMIT) -> dict:+ """Top organic landing pages only."""+ full = organic_traffic_report(site_id, url, token, days=days, limit=limit)+ if full["status"] != "success":+ return full+ return _envelope("success", {+ "site_id": site_id,+ "date_range": full["data"]["date_range"],+ "segment": full["data"]["segment"],+ "total_organic_visits": full["data"]["totals"]["visits"],+ "pages": full["data"]["top_pages"],+ }, None, method="Actions.getEntryPageUrls")+++def device_breakdown(site_id: str, url: str, token: str,+ days: int = DEFAULT_DAYS) -> dict:+ """Visits by device type (Desktop / Smartphone / Tablet / ...)."""+ start, end = _date_range(days)+ date_arg = f"{start},{end}"++ resp = _request(url, token, {+ "method": "DevicesDetection.getType",+ "idSite": site_id,+ "period": "range",+ "date": date_arg,+ "segment": "referrerType==search",+ })+ if resp["status"] != "success":+ return resp++ raw = resp["data"]+ devices = []+ if isinstance(raw, dict):+ for device_type, entry in raw.items():+ if not isinstance(entry, dict):+ continue+ visits = _bounded_int(entry.get("nb_visits"))+ devices.append({+ "device_type": entry.get("label") or device_type,+ "visits": visits,+ "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),+ "bounce_rate": round(_bounded_float(entry.get("bounce_rate")) * 100, 1),+ })+ devices.sort(key=lambda d: d["visits"], reverse=True)++ return _envelope("success", {+ "site_id": site_id,+ "date_range": {"start": start, "end": end},+ "segment": "referrerType==search",+ "devices": devices,+ }, None, method="DevicesDetection.getType")+++def country_breakdown(site_id: str, url: str, token: str,+ days: int = DEFAULT_DAYS,+ limit: int = 20) -> dict:+ """Visits by country (ISO-3166-1 alpha-2)."""+ start, end = _date_range(days)+ date_arg = f"{start},{end}"++ resp = _request(url, token, {+ "method": "UserCountry.getCountry",+ "idSite": site_id,+ "period": "range",+ "date": date_arg,+ "segment": "referrerType==search",+ "filter_limit": str(min(limit, MAX_LIMIT)),+ })+ if resp["status"] != "success":+ return resp++ raw = resp["data"]+ countries = []+ if isinstance(raw, dict):+ for code, entry in raw.items():+ if not isinstance(entry, dict):+ continue+ countries.append({+ "country_code": code,+ "country": entry.get("label", code),+ "visits": _bounded_int(entry.get("nb_visits")),+ "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),+ })+ countries.sort(key=lambda c: c["visits"], reverse=True)++ return _envelope("success", {+ "site_id": site_id,+ "date_range": {"start": start, "end": end},+ "segment": "referrerType==search",+ "countries": countries[:limit],+ }, None, method="UserCountry.getCountry")+++def referrers_report(site_id: str, url: str, token: str,+ days: int = DEFAULT_DAYS) -> dict:+ """+ Channel breakdown: direct, search, websites, social, campaigns.+ Plus top search engines for the search channel.+ """+ start, end = _date_range(days)+ date_arg = f"{start},{end}"++ types_resp = _request(url, token, {+ "method": "Referrers.getReferrersType",+ "idSite": site_id,+ "period": "range",+ "date": date_arg,+ })+ if types_resp["status"] != "success":+ return types_resp++ raw = types_resp["data"]+ channels = []+ if isinstance(raw, dict):+ for key, entry in raw.items():+ if not isinstance(entry, dict):+ continue+ channels.append({+ "channel": entry.get("label") or key,+ "visits": _bounded_int(entry.get("nb_visits")),+ "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),+ "actions": _bounded_int(entry.get("nb_actions")),+ })+ channels.sort(key=lambda c: c["visits"], reverse=True)++ engines_resp = _request(url, token, {+ "method": "Referrers.getSearchEngines",+ "idSite": site_id,+ "period": "range",+ "date": date_arg,+ })+ engines: list = []+ engines_error: Optional[str] = None+ if engines_resp["status"] == "success":+ raw_engines = engines_resp["data"]+ if isinstance(raw_engines, dict):+ for key, entry in raw_engines.items():+ if not isinstance(entry, dict):+ continue+ engines.append({+ "search_engine": entry.get("label") or key,+ "visits": _bounded_int(entry.get("nb_visits")),+ })+ engines.sort(key=lambda e: e["visits"], reverse=True)+ else:+ engines_error = engines_resp.get("error")++ return _envelope("success", {+ "site_id": site_id,+ "date_range": {"start": start, "end": end},+ "channels": channels,+ "search_engines": engines,+ }, engines_error, method="Referrers.getReferrersType")+++def keywords_report(site_id: str, url: str, token: str,+ days: int = DEFAULT_DAYS,+ limit: int = 50) -> dict:+ """+ Organic search keywords. Many entries will be '(not provided)' or+ '(no keyword)' due to browser privacy and Matomo's keyword anonymization.+ The report surfaces the raw distribution and flags when >50% of entries+ are anonymized, which is the norm on modern browsers.+ """+ start, end = _date_range(days)+ date_arg = f"{start},{end}"++ resp = _request(url, token, {+ "method": "Referrers.getKeywords",+ "idSite": site_id,+ "period": "range",+ "date": date_arg,+ "segment": "referrerType==search",+ "filter_limit": str(min(limit, MAX_LIMIT)),+ })+ if resp["status"] != "success":+ return resp++ raw = resp["data"]+ keywords_by_label: dict[str, dict] = {}+ anonymized_count = 0+ if isinstance(raw, dict):+ for kw, entry in raw.items():+ if not isinstance(entry, dict):+ continue+ visits = _bounded_int(entry.get("nb_visits"))+ label = entry.get("label") or kw+ if label in ("", "(not provided)", "(no keyword)"):+ anonymized_count += visits or 0+ label = "(not provided)"+ bucket = keywords_by_label.setdefault(label, {"keyword": label, "visits": 0})+ bucket["visits"] += visits+ keywords = list(keywords_by_label.values())+ keywords.sort(key=lambda k: k["visits"], reverse=True)+ total_visits = sum(k["visits"] for k in keywords)+ anonymized_share = (+ round(anonymized_count / total_visits * 100, 1) if total_visits else 0.0+ )++ return _envelope("success", {+ "site_id": site_id,+ "date_range": {"start": start, "end": end},+ "segment": "referrerType==search",+ "keywords": keywords,+ "anonymized_share_pct": anonymized_share,+ "note": (+ "Many keywords surface as '(not provided)' due to browser and "+ "Matomo privacy anonymization. High anonymized_share_pct is normal."+ ),+ }, None, method="Referrers.getKeywords")+++def check_command() -> dict:+ """Lightweight probe: who am I + version, used by --check subcommand."""+ from matomo_auth import _probe_version, _sanity_check_instance_url++ config = load_config()+ url = _sanity_check_instance_url(config.get("matomo_url") or "")+ token = config.get("matomo_token")+ site_id = config.get("matomo_site_id")++ if not url or not token:+ return _envelope("error", None,+ "Matomo credentials incomplete. Run python matomo_auth.py --setup.")++ probe = _probe_version(url, token)+ if not probe["ok"]:+ return _envelope("error", None, probe.get("error"), method="API.getMatomoVersion")+ return _envelope("success", {+ "instance": url,+ "site_id": site_id,+ "version": probe.get("version"),+ }, None, method="API.getMatomoVersion")+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Matomo Reporting API - traffic reports (GA4 alternative)"+ )+ sub = parser.add_subparsers(dest="command", required=True)++ common = argparse.ArgumentParser(add_help=False)+ common.add_argument("--site-id", "-s",+ help="Matomo idSite (overrides config default)")+ common.add_argument("--days", "-d", type=int, default=DEFAULT_DAYS,+ help=f"Number of days (default: {DEFAULT_DAYS})")+ common.add_argument("--limit", type=int, default=DEFAULT_LIMIT,+ help=f"Max rows (default: {DEFAULT_LIMIT})")+ common.add_argument("--json", "-j", action="store_true",+ help="Output as JSON")++ sub.add_parser("check", parents=[common],+ help="Verify Matomo credentials and connectivity")+ sub.add_parser("organic", parents=[common],+ help="Organic traffic trend + top landing pages")+ sub.add_parser("top-pages", parents=[common],+ help="Top organic landing pages only")+ sub.add_parser("device", parents=[common],+ help="Visits broken down by device type")+ sub.add_parser("country", parents=[common],+ help="Visits broken down by country")+ sub.add_parser("referrers", parents=[common],+ help="Channel breakdown (direct / search / website / social) + search engines")+ sub.add_parser("keywords", parents=[common],+ help="Organic search keywords (often '(not provided)')")++ args = parser.parse_args()++ if args.command == "check":+ result = check_command()+ else:+ url = get_matomo_url()+ token = get_matomo_token()+ site_id = _resolve_site_id(args)++ if not url:+ print("Error: MATOMO_URL is not configured. "+ "Set MATOMO_URL env or add 'matomo_url' to "+ f"{_SCRIPTS_DIR}/../../scripts/matomo_auth.py config.",+ file=sys.stderr)+ return 1+ if not token:+ print("Error: MATOMO_API_TOKEN (or MATOMO_TOKEN) is not configured.",+ file=sys.stderr)+ return 1+ if not site_id:+ print("Error: --site-id or MATOMO_SITE_ID is required.", file=sys.stderr)+ return 1++ if args.command == "organic":+ result = organic_traffic_report(site_id, url, token,+ days=args.days, limit=args.limit)+ elif args.command == "top-pages":+ result = top_pages_report(site_id, url, token,+ days=args.days, limit=args.limit)+ elif args.command == "device":+ result = device_breakdown(site_id, url, token, days=args.days)+ elif args.command == "country":+ result = country_breakdown(site_id, url, token,+ days=args.days, limit=args.limit)+ elif args.command == "referrers":+ result = referrers_report(site_id, url, token, days=args.days)+ elif args.command == "keywords":+ result = keywords_report(site_id, url, token,+ days=args.days, limit=args.limit)+ else:+ parser.error(f"Unknown command: {args.command}")+ return 2++ if result.get("error") and not args.json:+ print(f"Error: {result['error']}", file=sys.stderr)+ return 1++ if args.json:+ print(json.dumps(result, indent=2, default=str))+ else:+ _print_human(result, args.command)++ return 0 if result.get("status") == "success" else 1+++def _print_human(result: dict, command: str) -> None:+ data = result.get("data") or {}+ if command == "check":+ print("=== Matomo Connectivity Check ===")+ print(f"Instance: {data.get('instance')}")+ print(f"Site ID: {data.get('site_id')}")+ print(f"Version: {data.get('version')}")+ return++ dr = data.get("date_range", {})+ print(f"=== Matomo {command} Report ===")+ if "site_id" in data:+ print(f"Site ID: {data['site_id']}")+ if dr:+ print(f"Period: {dr.get('start')} to {dr.get('end')}")++ if command == "organic":+ totals = data.get("totals", {})+ print(f"\nVisits: {totals.get('visits', 0):,} | "+ f"Unique Visitors: {totals.get('unique_visitors', 0):,}")+ print(f"Avg Daily Visits: {totals.get('avg_daily_visits', 0):,.0f} | "+ f"Bounce: {totals.get('bounce_rate', 0)}%")+ print(f"Avg Time on Site: {totals.get('avg_time_on_site', 0):.1f}s")+ pages = data.get("top_pages", [])+ if pages:+ print(f"\nTop {min(10, len(pages))} Organic Landing Pages:")+ for i, p in enumerate(pages[:10], 1):+ print(f" {i:2d}. {p['url']} ({p['visits']:,} visits)")+ elif command == "top-pages":+ print(f"Total organic visits: {data.get('total_organic_visits', 0):,}")+ for i, p in enumerate(data.get("pages", [])[:20], 1):+ print(f" {i:2d}. {p['url']} ({p['visits']:,})")+ elif command == "device":+ for d in data.get("devices", []):+ print(f" {d['device_type']}: {d['visits']:,} visits "+ f"(bounce {d['bounce_rate']}%)")+ elif command == "country":+ for c in data.get("countries", [])[:20]:+ print(f" {c['country']} ({c['country_code']}): {c['visits']:,}")+ elif command == "referrers":+ for ch in data.get("channels", []):+ print(f" {ch['channel']}: {ch['visits']:,} visits")+ engines = data.get("search_engines", [])+ if engines:+ print("\nSearch Engines:")+ for e in engines[:10]:+ print(f" {e['search_engine']}: {e['visits']:,}")+ elif command == "keywords":+ note = data.get("note")+ share = data.get("anonymized_share_pct", 0)+ print(f"\nAnonymized share: {share}%")+ if note:+ print(f"Note: {note}")+ for k in data.get("keywords", [])[:20]:+ print(f" {k['keyword']}: {k['visits']:,}")+++if __name__ == "__main__":+ sys.exit(main())\ No newline at end of filediff --git a/scripts/runtime.py b/scripts/runtime.pyindex 0db15bc..dc25f32 100755--- a/scripts/runtime.py+++ b/scripts/runtime.py@@ -39,7 +39,8 @@ ALLOWED_CORE_SCRIPTS = frozenset("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",+ "lcp_subparts.py", "matomo_auth.py", "matomo_report.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",diff --git a/skills/seo-audit/SKILL.md b/skills/seo-audit/SKILL.mdindex 4be3d95..7e5bb54 100644--- a/skills/seo-audit/SKILL.md+++ b/skills/seo-audit/SKILL.md@@ -28,6 +28,7 @@ metadata:- `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 `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run google_auth.py --check`)+ - `seo-matomo` -- Matomo Reporting API: organic traffic, landing pages, device / country splits, referrer analysis (spawn when Matomo credentials detected via `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run matomo_auth.py --check`; runs alongside `seo-google` when both are configured, or as a GA4 alternative when GA4 is not)- `seo-backlinks` -- Backlink profile data: DA/PA, referring domains, anchor text, toxic links (spawn when Moz or Bing API credentials detected via `"${CLAUDE_PLUGIN_ROOT}/scripts/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)@@ -172,6 +173,10 @@ If DataForSEO MCP tools are available, spawn the `seo-dataforseo` agent alongsidIf Google API credentials are configured (`"${CLAUDE_PLUGIN_ROOT}/scripts/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.+## Matomo Integration (Optional)++If Matomo credentials are configured (`claude-seo run matomo_auth.py --check`), spawn the `seo-matomo` agent to enrich the audit with self-hosted analytics: organic visits trend, top landing pages, device and country breakdowns, channel / search-engine split, and organic keywords. Works as a GA4 alternative (when only Matomo is configured) or as a complement (when both GA4 and Matomo are present). Matomo numbers will not match GA4 exactly because of segmentation differences (`referrerType==search` vs `sessionDefaultChannelGroup == "Organic Search"`) and attribution-window rules.+## Error Handling| Scenario | Action |diff --git a/skills/seo/SKILL.md b/skills/seo/SKILL.mdindex b0fa819..635d928 100644--- a/skills/seo/SKILL.md+++ b/skills/seo/SKILL.md@@ -56,6 +56,7 @@ extension is also installable (see "Optional Extensions" below).| `/seo drift compare <url>` | Compare current state to stored baseline || `/seo drift history <url>` | Show drift history over time || `/seo ecommerce <url>` | E-commerce SEO: product schema, marketplace intelligence |+| `/seo matomo [command] [args]` | Matomo Reporting API: GA4 alternative or supplement (extension) || `/seo firecrawl [command] <url>` | Full-site crawling and site mapping (extension) || `/seo dataforseo [command]` | Live SEO data via DataForSEO (extension) || `/seo image-gen [use-case] <description>` | AI image generation for SEO assets (extension) |@@ -81,18 +82,19 @@ When 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-geo3. If Google API credentials detected (`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run google_auth.py --check`), also spawn seo-google agent-4. If local business detected, also spawn seo-local agent-5. If local business detected AND DataForSEO MCP available, also spawn seo-maps agent-6. If backlink APIs detected (`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run backlinks_auth.py --check`), also spawn seo-backlinks agent-7. If Firecrawl MCP available, use `firecrawl_map` to discover all site URLs before analysis-8. If content strategy signals detected (blog, pillar pages, topic clusters), also spawn seo-cluster agent-9. If e-commerce detected, also spawn seo-ecommerce agent-10. If drift baseline exists for this URL (`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run drift_history.py <url>`), also spawn seo-drift agent-11. 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 / Low-14. Create prioritized action plan with dependency sequencing + falsifiability per recommendation-15. **Offer PDF report**: "Generate a professional PDF report? Use `/seo google report full`"+4. If Matomo credentials detected (`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run matomo_auth.py --check`), also spawn seo-matomo agent (alternative or complement to seo-google's GA4 reports)+5. If local business detected, also spawn seo-local agent+6. If local business detected AND DataForSEO MCP available, also spawn seo-maps agent+7. If backlink APIs detected (`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run backlinks_auth.py --check`), also spawn seo-backlinks agent+8. If Firecrawl MCP available, use `firecrawl_map` to discover all site URLs before analysis+9. If content strategy signals detected (blog, pillar pages, topic clusters), also spawn seo-cluster agent+10. If e-commerce detected, also spawn seo-ecommerce agent+11. If drift baseline exists for this URL (`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run drift_history.py <url>`), also spawn seo-drift agent+12. Always include seo-sxo in full audits (search experience applies to all sites)+13. Collect results and generate unified report with SEO Health Score (0-100)+14. **Synthesize via the 10-principle framework** (see "Synthesis Methodology" below), walk PERCEIVE → ANALYZE → VALIDATE → ACT before bucketing findings into Critical / High / Medium / Low+15. Create prioritized action plan with dependency sequencing + falsifiability per recommendation+16. **Offer PDF report**: "Generate a professional PDF report? Use `/seo google report full`"For individual commands, load the relevant sub-skill directly.After any analysis command completes, offer to generate a PDF report via `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run google_report.py`.@@ -254,13 +256,19 @@ installer to activate (see each extension's `install.sh`/`install.ps1`):All optional extensions are reachable through `/seo` subcommands onceinstalled: firecrawl, dataforseo, and image-gen, plus `/seo ahrefs`,-`/seo bing`, `/seo profound`, `/seo seranking`, and `/seo unlighthouse`.-Each installs as its own sub-skill, so the model also auto-routes to their-descriptions without the `/seo` prefix.+`/seo bing`, `/seo matomo`, `/seo profound`, `/seo seranking`, and+`/seo unlighthouse`. Each installs as its own sub-skill, so the model also+auto-routes to their descriptions without the `/seo` prefix.- **seo-firecrawl** -- Full-site crawling and site mapping via Firecrawl MCP. Installvia `extensions/firecrawl/install.sh` (Unix) or `extensions/firecrawl/install.ps1`(Windows). Once installed, invoke via `/seo firecrawl <command>`.+- **seo-matomo** -- Self-hosted or Matomo Cloud Reporting API as a GA4+ alternative or complement. Install via+ `extensions/matomo/install.sh` (Unix) or `extensions/matomo/install.ps1`+ (Windows). Once installed, invoke via `/seo matomo <command>` or rely+ on the audit orchestrator to spawn the seo-matomo agent automatically+ when credentials are present.## Subagentsdiff --git a/tests/test_matomo_report.py b/tests/test_matomo_report.pynew file mode 100644index 0000000..feb0e50--- /dev/null+++ b/tests/test_matomo_report.py@@ -0,0 +1,388 @@+"""Tests for the Matomo extension (scripts/matomo_auth.py, scripts/matomo_report.py).++Covers:+- Envelope shape (status / data / error / metadata)+- Auth probe (HTTP error classes mapped to friendly error messages)+- Token never appears in output / URL parameters+- URL sanity check (allows self-hosted, rejects malformed)+- Env-var and config-file credential loading (env wins over file when both set)+- Args / CLI error paths surface a structured error envelope+- Token redaction of incoming Matomo ``result=error`` messages+"""++from __future__ import annotations++import json+import os+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 matomo_auth # noqa: E402+import matomo_report # noqa: E402+++SECRET_TOKEN = "abcdef0123456789abcdef0123456789"++[email protected](autouse=True)+def _clear_env(monkeypatch):+ """Ensure Matomo env vars do not leak between tests."""+ for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_TOKEN",+ "MATOMO_SITE_ID", "MATOMO_IDSITE"):+ monkeypatch.delenv(k, raising=False)+++def _mock_response(status_code: int, body) -> Mock:+ resp = Mock(status_code=status_code, text=json.dumps(body))+ resp.json.return_value = body+ return resp+++def _ok_envelope(data=None, method=None):+ return {+ "status": "success",+ "data": data if data is not None else {},+ "error": None,+ "metadata": {"source": "matomo_report",+ "timestamp": matomo_report.datetime.now(+ matomo_report.timezone.utc+ ).strftime("%Y-%m-%dT%H:%M:%SZ"),+ **({"method": method} if method else {})},+ }+++def test_envelope_shape_and_metadata_source():+ """Every result envelope is {status, data, error, metadata:{source, ...}}."""+ env = matomo_report._envelope("success", {"x": 1}, None, method="API.getX")+ assert env["status"] == "success"+ assert env["data"] == {"x": 1}+ assert env["error"] is None+ assert env["metadata"]["source"] == "matomo_report"+ assert env["metadata"]["method"] == "API.getX"+ assert "timestamp" in env["metadata"]+++def test_url_sanity_allows_self_hosted_https():+ assert matomo_auth._sanity_check_instance_url("https://analytics.example.com") \+ == "https://analytics.example.com"+ assert matomo_auth._sanity_check_instance_url("http://localhost:8080/") \+ == "http://localhost:8080"+ assert matomo_auth._sanity_check_instance_url("https://10.0.0.5/matomo/") \+ == "https://10.0.0.5/matomo"+++def test_url_sanity_rejects_malformed():+ assert matomo_auth._sanity_check_instance_url("") is None+ assert matomo_auth._sanity_check_instance_url("not-a-url") is None+ assert matomo_auth._sanity_check_instance_url("ftp://example.com") is None+ # Userinfo in URL would leak credentials if accidentally configured.+ assert matomo_auth._sanity_check_instance_url(+ "https://user:[email protected]") is None+++def test_load_config_falls_back_to_env(monkeypatch, tmp_path):+ monkeypatch.setenv("MATOMO_URL", "https://env.example.com")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)+ monkeypatch.setenv("MATOMO_SITE_ID", "7")+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ cfg = matomo_auth.load_config()+ assert cfg["matomo_url"] == "https://env.example.com"+ assert cfg["matomo_token"] == SECRET_TOKEN+ assert cfg["matomo_site_id"] == "7"+++def test_load_config_falls_back_to_file(monkeypatch, tmp_path):+ config_file = tmp_path / "matomo.json"+ config_file.write_text(json.dumps({+ "matomo_url": "https://file.example.com",+ "matomo_token": "file_token_" + "a" * 22,+ "matomo_site_id": "3",+ }))+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(config_file))+ for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_SITE_ID"):+ monkeypatch.delenv(k, raising=False)+ cfg = matomo_auth.load_config()+ assert cfg["matomo_url"] == "https://file.example.com"+ assert cfg["matomo_token"].startswith("file_token_")+ assert cfg["matomo_site_id"] == "3"+++def test_check_credentials_unavailable_when_no_url(monkeypatch, tmp_path):+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ status = matomo_auth.check_credentials()+ assert status["available"] is False+ assert "URL" in status["error"] or "url" in status["error"].lower()+++def test_check_credentials_unavailable_when_no_token(monkeypatch, tmp_path):+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")+ status = matomo_auth.check_credentials()+ assert status["available"] is False+ assert "token_auth" in status["error"] or "token" in status["error"].lower()+++def test_check_credentials_probes_version(monkeypatch, tmp_path):+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)+ monkeypatch.setenv("MATOMO_SITE_ID", "1")++ resp = _mock_response(200, "5.1.2")+ with patch.object(matomo_auth.requests, "post", return_value=resp) as post:+ status = matomo_auth.check_credentials()++ assert status["available"] is True+ assert status["instance"] == "https://analytics.example.com"+ assert status["site_id"] == "1"+ assert status["verified"] is True+ assert status["version"] == "5.1.2"+ # Token must be in POST body, never in URL.+ call = post.call_args+ assert call.kwargs["data"]["token_auth"] == SECRET_TOKEN+ assert "token_auth" not in call.kwargs.get("params", {})+++def test_check_credentials_surfaces_auth_failure(monkeypatch, tmp_path):+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)+ resp = _mock_response(401, {"result": "error", "message": "no access"})+ with patch.object(matomo_auth.requests, "post", return_value=resp):+ status = matomo_auth.check_credentials()+ assert status["available"] is False+ assert "authentication" in status["error"].lower() or "auth" in status["error"].lower()+ # Token must not appear in the error message.+ assert SECRET_TOKEN not in status["error"]+++def test_check_credentials_surfaces_connection_error(monkeypatch, tmp_path):+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)+ with patch.object(+ matomo_auth.requests, "post",+ side_effect=matomo_auth.requests.exceptions.ConnectionError("refused"),+ ):+ status = matomo_auth.check_credentials()+ assert status["available"] is False+ assert "connection" in status["error"].lower()+++def test_token_redaction_strips_query_params():+ """Incoming Matomo error messages with token_auth=... get redacted."""+ raw = "API error: token_auth=" + SECRET_TOKEN + "&other=value"+ redacted = matomo_report._redact(raw)+ assert SECRET_TOKEN not in redacted+ assert "<redacted>" in redacted+ assert "other=value" in redacted+++def test_request_maps_matomo_result_error_to_envelope():+ resp = _mock_response(200, {"result": "error",+ "message": "No data available"})+ with patch.object(matomo_report.requests, "post", return_value=resp):+ env = matomo_report._request("https://m.test", "tok", {"method": "X"})+ assert env["status"] == "error"+ assert "No data available" in env["error"]+ assert env["metadata"]["method"] == "X"+++def test_request_redacts_token_in_matomo_error():+ leaked = "Bad token_auth=" + SECRET_TOKEN + " for site"+ resp = _mock_response(200, {"result": "error", "message": leaked})+ with patch.object(matomo_report.requests, "post", return_value=resp):+ env = matomo_report._request("https://m.test", "tok", {"method": "X"})+ assert SECRET_TOKEN not in (env.get("error") or "")+++def test_request_maps_401_to_friendly_error():+ resp = _mock_response(401, {})+ with patch.object(matomo_report.requests, "post", return_value=resp):+ env = matomo_report._request("https://m.test", "tok", {"method": "X"})+ assert env["status"] == "error"+ assert "authentication" in env["error"].lower() or "token" in env["error"].lower()+++def test_request_maps_timeout_to_friendly_error():+ with patch.object(+ matomo_report.requests, "post",+ side_effect=matomo_report.requests.exceptions.Timeout("read timeout"),+ ):+ env = matomo_report._request("https://m.test", "tok", {"method": "X"})+ assert env["status"] == "error"+ assert "timed out" in env["error"].lower() or "timeout" in env["error"].lower()+++def test_request_does_not_echo_token_in_call_args():+ resp = _mock_response(200, "5.1.2")+ with patch.object(matomo_report.requests, "post", return_value=resp) as post:+ matomo_report._request("https://m.test", SECRET_TOKEN, {"method": "X"})+ call = post.call_args+ assert call.kwargs["data"]["token_auth"] == SECRET_TOKEN+ # No query params; token is POST body only.+ assert "params" not in call.kwargs or not call.kwargs["params"]+++def test_cli_errors_when_url_missing(monkeypatch):+ """`--check` with no configured URL returns a friendly error envelope."""+ for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_SITE_ID",+ "MATOMO_TOKEN", "MATOMO_IDSITE"):+ monkeypatch.delenv(k, raising=False)+ with patch.object(matomo_auth.requests, "post") as post:+ env = matomo_auth.check_credentials()+ assert env["available"] is False+ assert "url" in env["error"].lower()+ post.assert_not_called()+++def test_organic_report_builds_daily_and_pages(monkeypatch):+ """organic_traffic_report rolls daily VisitsSummary into totals + pages."""+ daily = {+ "2026-01-01": {"nb_visits": 100, "nb_uniq_visitors": 80,+ "nb_actions": 150, "nb_pageviews": 200,+ "bounce_count": 30, "sum_visit_length": 6000},+ "2026-01-02": {"nb_visits": 50, "nb_uniq_visitors": 40,+ "nb_actions": 80, "nb_pageviews": 100,+ "bounce_count": 10, "sum_visit_length": 3000},+ }+ pages = [+ {"label": "https://m.test/", "nb_visits": 80, "nb_uniq_visitors": 70,+ "nb_actions": 120, "bounce_rate": 0.3},+ {"label": "https://m.test/blog/x", "nb_visits": 40, "nb_uniq_visitors": 30,+ "nb_actions": 60, "bounce_rate": 0.5},+ ]+ responses = [+ _mock_response(200, daily),+ _mock_response(200, pages),+ ]+ with patch.object(matomo_report.requests, "post",+ side_effect=responses):+ env = matomo_report.organic_traffic_report("1", "https://m.test",+ SECRET_TOKEN, days=2)+ assert env["status"] == "success"+ data = env["data"]+ assert data["site_id"] == "1"+ assert data["totals"]["visits"] == 150+ assert data["totals"]["unique_visitors"] == 120+ assert len(data["daily_data"]) == 2+ assert len(data["top_pages"]) == 2+ assert data["top_pages"][0]["url"] == "https://m.test/"+++def test_device_breakdown_sorts_by_visits(monkeypatch):+ raw = {+ "desktop": {"label": "Desktop", "nb_visits": 100,+ "nb_uniq_visitors": 80, "bounce_rate": 0.4},+ "smartphone": {"label": "Smartphone", "nb_visits": 200,+ "nb_uniq_visitors": 170, "bounce_rate": 0.5},+ "tablet": {"label": "Tablet", "nb_visits": 20,+ "nb_uniq_visitors": 18, "bounce_rate": 0.3},+ }+ with patch.object(matomo_report.requests, "post",+ return_value=_mock_response(200, raw)):+ env = matomo_report.device_breakdown("1", "https://m.test",+ SECRET_TOKEN, days=7)+ assert env["status"] == "success"+ devices = env["data"]["devices"]+ assert [d["device_type"] for d in devices] == ["Smartphone", "Desktop", "Tablet"]+++def test_country_breakdown_caps_limit(monkeypatch):+ raw = {f"C{i}": {"label": f"Country {i}", "nb_visits": 100 - i,+ "nb_uniq_visitors": 50} for i in range(30)}+ with patch.object(matomo_report.requests, "post",+ return_value=_mock_response(200, raw)):+ env = matomo_report.country_breakdown("1", "https://m.test",+ SECRET_TOKEN, days=7, limit=5)+ assert env["status"] == "success"+ assert len(env["data"]["countries"]) == 5+ assert env["data"]["countries"][0]["country_code"] == "C0"+++def test_keywords_report_flags_anonymized_share(monkeypatch):+ raw = {+ "kw1": {"label": "kw1", "nb_visits": 10},+ "kw2": {"label": "kw2", "nb_visits": 5},+ "(not provided)": {"label": "(not provided)", "nb_visits": 80},+ "(no keyword)": {"label": "(no keyword)", "nb_visits": 5},+ }+ with patch.object(matomo_report.requests, "post",+ return_value=_mock_response(200, raw)):+ env = matomo_report.keywords_report("1", "https://m.test",+ SECRET_TOKEN, days=7, limit=10)+ assert env["status"] == "success"+ data = env["data"]+ assert data["anonymized_share_pct"] > 80.0+ assert "anonymization" in data["note"].lower()+ # Anonymized entries collapse to "(not provided)" but their visits are summed.+ anonymized = [k for k in data["keywords"] if k["keyword"] == "(not provided)"]+ assert anonymized and anonymized[0]["visits"] == 85+++def test_referrers_report_includes_search_engines(monkeypatch):+ types = {+ "direct": {"label": "Direct Entry", "nb_visits": 30, "nb_uniq_visitors": 25,+ "nb_actions": 40},+ "search": {"label": "Search Engines", "nb_visits": 70, "nb_uniq_visitors": 60,+ "nb_actions": 100},+ "social": {"label": "Social Networks", "nb_visits": 20, "nb_uniq_visitors": 18,+ "nb_actions": 25},+ }+ engines = {+ "Google": {"label": "Google", "nb_visits": 50},+ "Bing": {"label": "Bing", "nb_visits": 20},+ }+ with patch.object(matomo_report.requests, "post",+ side_effect=[_mock_response(200, types),+ _mock_response(200, engines)]):+ env = matomo_report.referrers_report("1", "https://m.test",+ SECRET_TOKEN, days=7)+ assert env["status"] == "success"+ channels = env["data"]["channels"]+ assert [c["channel"] for c in channels] == [+ "Search Engines", "Direct Entry", "Social Networks"]+ engines_out = env["data"]["search_engines"]+ assert [e["search_engine"] for e in engines_out] == ["Google", "Bing"]+++def test_main_returns_nonzero_on_envelope_error(monkeypatch, capsys):+ """Missing creds -> error envelope -> exit 1."""+ for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_SITE_ID",+ "MATOMO_TOKEN", "MATOMO_IDSITE"):+ monkeypatch.delenv(k, raising=False)+ with patch("sys.argv", ["matomo_report.py", "organic", "--json"]):+ rc = matomo_report.main()+ assert rc == 1+ captured = capsys.readouterr()+ assert "MATOMO_URL" in captured.err or "MATOMO_API_TOKEN" in captured.err+++def test_main_json_emits_envelope(monkeypatch):+ monkeypatch.setenv("MATOMO_URL", "https://m.test")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)+ monkeypatch.setenv("MATOMO_SITE_ID", "1")+ with patch.object(+ matomo_auth.requests, "post",+ return_value=_mock_response(200, "5.1.2"),+ ), patch("sys.argv",+ ["matomo_report.py", "check", "--json"]):+ rc = matomo_report.main()+ assert rc == 0+++def test_main_missing_site_id_exits_one(monkeypatch, capsys):+ monkeypatch.setenv("MATOMO_URL", "https://m.test")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)+ monkeypatch.delenv("MATOMO_SITE_ID", raising=False)+ with patch("sys.argv", ["matomo_report.py", "organic", "--json"]):+ rc = matomo_report.main()+ assert rc == 1+ captured = capsys.readouterr()+ assert "--site-id" in captured.err or "MATOMO_SITE_ID" in captured.err\ No newline at end of filediff --git a/tests/test_parasite_risk_and_extensions.py b/tests/test_parasite_risk_and_extensions.pyindex 2b97654..124bb54 100644--- a/tests/test_parasite_risk_and_extensions.py+++ b/tests/test_parasite_risk_and_extensions.py@@ -105,6 +105,7 @@ def test_audit_page_counts_pattern_hits() -> None:("seranking", "seo-seranking"),("profound", "seo-profound"),("bing-webmaster", "seo-bing"),+ ("matomo", "seo-matomo"),("unlighthouse", "seo-unlighthouse"),],)@@ -131,7 +132,8 @@ _POSIX_ONLY = pytest.mark.skipif(@_POSIX_ONLY@pytest.mark.parametrize(- "name", ["ahrefs", "seranking", "profound", "bing-webmaster", "unlighthouse"],+ "name", ["ahrefs", "seranking", "profound", "bing-webmaster", "matomo",+ "unlighthouse"],)def test_extension_install_script_is_executable(name: str) -> None:install = _REPO_ROOT / "extensions" / name / "install.sh"@@ -165,6 +167,7 @@ def test_every_extension_install_and_uninstall_is_executable() -> None:("seranking", "seo-seranking"),("profound", "seo-profound"),("bing-webmaster", "seo-bing"),+ ("matomo", "seo-matomo"),("unlighthouse", "seo-unlighthouse"),],)