Skip to content

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.

feat(content): detect templated title/description metadata

Suleman Khan270e247a67d8
diff --git a/AGENTS.md b/AGENTS.md
index e1e19f1..637cd2d 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 53 Python execution scripts.
+integration + 2 extension mirrors), and 54 Python execution scripts.
## Quick Reference
@@ -165,7 +165,7 @@ skills/ # 25 sub-skills (auto-discovered)
seo-dataforseo/ # DataForSEO (extension)
seo-image-gen/ # AI images (extension)
agents/ # 18 subagents
-scripts/ # 53 Python scripts, including the managed runtime
+scripts/ # 54 Python scripts, including the managed runtime
schema/ # JSON-LD templates
extensions/ # 8 MCP extensions: DataForSEO, Firecrawl, Banana, Ahrefs, SE Ranking, Profound, Bing Webmaster, Unlighthouse
```
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 284875b..286bd5e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
word boundaries. Emoji sequences (ZWJ, variation selectors) are preserved. The
`seo-content` skill documents the new triggers and the scope limits (statistical
watermarks are untouched; intended for the user's own drafts).
+- Templated-metadata detector (`scripts/metadata_template.py`): flags meta descriptions that
+ restate their own title tag verbatim and then close with a stock call to action, the shape bulk
+ metadata jobs produce site-wide. Deterministic string comparison, no model, `method: heuristic`
+ in its output. Exposes a site-level roll-up (`templated_ratio`, `shared_cta_phrases`, `site_risk`)
+ because duplicated/templated metadata is a site-scale signal, not a per-page one. Wired into
+ `seo-page`, the `seo-content` agent, the quality-gates meta description table, and the
+ `seo-programmatic` uniqueness gate, which measures body copy only and therefore cannot see this.
## [2.2.6] - 2026-09-10
diff --git a/CLAUDE.md b/CLAUDE.md
index 165a725..542e972 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -85,7 +85,7 @@ claude-seo/
seo-flow.md # FLOW framework integration
hooks/ # Quality gate hooks
hooks.json # PostToolUse schema validation
- scripts/ # 53 Python execution scripts
+ scripts/ # 54 Python execution scripts
google_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)
@@ -120,6 +120,7 @@ claude-seo/
preload_check.py # Speculation Rules / bfcache / prerender / preload detector
agent_ux_check.py # Agent-friendly page auditor
content_quality.py # QRG-aligned content quality detector
+ metadata_template.py # Templated title/description detector (title echo + stock CTA)
content_humanize.py # AI-pattern remover (rewrites AI-typical phrasing)
content_verify.py # Claim extractor + citation-gap detector
schema_generate.py # JSON-LD generators for high-leverage v2 schema types
diff --git a/agents/seo-content.md b/agents/seo-content.md
index 2c4434d..8e3c26a 100644
--- a/agents/seo-content.md
+++ b/agents/seo-content.md
@@ -17,6 +17,32 @@ When given content to analyze:
5. Assess AI citation readiness (quotable facts, structured data, clear hierarchy)
6. Check content freshness and update signals
7. Flag potential AI-generated content quality issues per Sept 2025 QRG criteria
+8. Check title/description pairs for templating (see below)
+
+## Templated Metadata
+
+Body-copy uniqueness does not clear a site of scaled content abuse. Metadata is
+generated in bulk far more often than body copy is, and a description that
+restates its own title and then appends a stock CTA is the shape those jobs
+produce on every URL at once.
+
+Single page:
+
+```
+claude-seo run metadata_template.py --title "<title>" --description "<desc>" --json
+```
+
+Site-wide, which is the unit that matters, pass a JSON list of
+`{url, title, description}` objects collected while crawling:
+
+```
+claude-seo run metadata_template.py --pairs-file metadata.json --json
+```
+
+Report `site_risk`, `templated_ratio`, and any `shared_cta_phrases`: the same
+closing CTA on many pages is the strongest single indicator of a bulk metadata
+job. `templated_metadata` is a high-severity finding; `description_echoes_title`,
+`brand_suffix_in_description`, and `description_duplicates_title` are secondary.
## E-E-A-T Scoring
diff --git a/scripts/metadata_template.py b/scripts/metadata_template.py
new file mode 100644
index 0000000..431a4e3
--- /dev/null
+++ b/scripts/metadata_template.py
@@ -0,0 +1,387 @@
+#!/usr/bin/env python3
+"""
+Templated-metadata detector.
+
+Finds machine-generated ``<title>`` / ``<meta name="description">`` pairs.
+The signature is narrow and deterministic: a description that opens by
+restating its own title verbatim and then closes with a stock call to
+action ("Try it free now.", "Start free!", "Learn more now!").
+
+Why this matters
+================
+Bulk metadata jobs (a CSV column piped into a template, an LLM asked for
+"a description for each of these titles") emit that exact shape across
+every page of a site at once. Under Google's spam policies and QRG
+§4.6.5, site-wide templated metadata reads as scaled content abuse, and
+it does so **independently of body-copy quality** — a site whose article
+text is entirely original can still be demoted on the metadata alone.
+
+Existing content checks do not catch this. ``content_quality.py`` scores
+body text; the ``seo-programmatic`` uniqueness gate measures unique body
+words per page. A site with fully unique body copy passes both while
+carrying an identical templated description shape on every URL.
+
+Detection
+=========
+Four deterministic string comparisons, no model and no inference about
+authorship:
+
+ 1. ``templated_metadata`` (high)
+ Description opens with the title, then ends in a stock CTA.
+ 2. ``description_echoes_title`` (medium)
+ Description opens with the title but adds real information.
+ 3. ``brand_suffix_in_description`` (low)
+ The title's brand suffix was concatenated into the description
+ body — a generation artefact, not a written sentence.
+ 4. ``description_duplicates_title`` (medium)
+ Description and title are the same string.
+
+Only titles of a reasonable length are compared, so short titles that a
+sentence can legitimately open with ("Word Counter" beginning a sentence
+about a word counter) are never flagged.
+
+Output (JSON when ``--json`` is set)::
+
+ {
+ "pages": [
+ {
+ "url": "https://example.com/tool",
+ "title": "...",
+ "description": "...",
+ "templated": true,
+ "severity": "high",
+ "cta_phrase": "try it free now",
+ "flags": ["templated-metadata"],
+ "signals": [{"id", "severity", "message", "recommendation"}]
+ }
+ ],
+ "pages_checked": int,
+ "templated_count": int,
+ "templated_ratio": 0.0..1.0,
+ "shared_cta_phrases": {"try it free now": 26},
+ "site_flags": ["site-wide-templated-metadata", ...],
+ "site_risk": "high" | "medium" | "low"
+ }
+
+A single pair scores as one page; ``--pairs-file`` scores a whole site,
+which is the unit the spam signal actually operates on.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Iterable
+
+# Stock closers that bulk metadata jobs append. Each entry must match at
+# the very end of the description remainder (after the echoed title has
+# been removed), so a page that genuinely ends on a call to action
+# without echoing its title is never flagged. Adding to this list should
+# require seeing the phrase in real generated metadata, not intuition.
+_CTA_TAIL_PATTERNS = (
+ # "Try it free now.", "Try free!", "Try it today."
+ r"try (?:it )?(?:free|now)(?: now)?",
+ r"try (?:it )?today",
+ # "Start free.", "Start now.", "Start your free scan now.", "Start your audit now!"
+ r"start (?:your |the )?(?:\w+ ){0,3}(?:free|now)",
+ # "Learn more now.", "Read more now.", "Find out now."
+ r"(?:learn|read|find out|see) (?:more )?now",
+ # "Get started.", "Get started now.", "Get started free."
+ r"get started(?: (?:now|free|today))?",
+ # "Check it out now.", "Check your score now."
+ r"check (?:it out|your \w+) now",
+ # "Boost your rankings now.", "Improve your writing score now."
+ r"(?:boost|improve|upgrade) (?:your )?(?:\w+ ){0,3}now",
+ # "Sign up free.", "Sign up today."
+ r"sign up (?:free|now|today)",
+)
+_CTA_TAIL_RE = re.compile(
+ r"(" + "|".join(_CTA_TAIL_PATTERNS) + r")[.!]*\s*$", re.IGNORECASE
+)
+
+# "Page Title | Brand", "Page Title - Brand", en/em dash variants.
+_BRAND_SEPARATOR_RE = re.compile(r"\s[|–—-]\s")
+
+_NON_ALNUM_RE = re.compile(r"[^a-z0-9 ]+")
+
+# A title shorter than this (normalised) is too generic to treat an echo
+# as evidence of templating.
+_MIN_TITLE_CHARS = 25
+# Compare at most this many leading characters, so a long title whose
+# tail was truncated in the description still matches.
+_ECHO_PREFIX_CHARS = 60
+# Brand suffixes outside this range are almost certainly a mis-split.
+_BRAND_MIN_CHARS = 2
+_BRAND_MAX_CHARS = 30
+
+# Site-level gates. The signal is scaled content abuse, so it needs both
+# an absolute count (one templated page is an oversight) and a share of
+# the sampled pages (three out of three hundred is not a pattern).
+_SITE_MIN_TEMPLATED_PAGES = 3
+_SITE_HIGH_RATIO = 0.30
+_SITE_MEDIUM_RATIO = 0.10
+
+
+def _normalise(text: str) -> str:
+ """Lowercase, drop punctuation, collapse whitespace.
+
+ Two strings that differ only in casing or separators compare equal.
+ """
+ return " ".join(_NON_ALNUM_RE.sub(" ", text.lower()).split())
+
+
+def _title_core(title: str) -> str:
+ """The claim the title makes, without its brand suffix.
+
+ "Keyword Density Checker | Credify" -> "Keyword Density Checker".
+ """
+ return _BRAND_SEPARATOR_RE.split(title)[0].strip()
+
+
+def _finding(signal_id: str, severity: str, message: str, recommendation: str) -> dict:
+ return {
+ "id": signal_id,
+ "severity": severity,
+ "message": message,
+ "recommendation": recommendation,
+ }
+
+
+def _echo_remainder(core: str, description: str) -> str:
+ """What the description says after it finishes restating the title."""
+ return description[len(core):].strip(" -–—:|.")
+
+
+def analyse(title: str, description: str, url: str | None = None) -> dict:
+ """Score one title/description pair for templating signals."""
+ title = (title or "").strip()
+ description = (description or "").strip()
+
+ result: dict = {
+ "url": url,
+ "title": title,
+ "description": description,
+ "templated": False,
+ "severity": "none",
+ "cta_phrase": None,
+ "flags": [],
+ "signals": [],
+ }
+ if not title or not description:
+ result["flags"].append("missing-metadata")
+ return result
+
+ core = _title_core(title)
+ core_n = _normalise(core)
+ title_n = _normalise(title)
+ description_n = _normalise(description)
+ signals: list[dict] = result["signals"]
+
+ # 1. Description opens by restating the title.
+ echoes_title = (
+ len(core_n) >= _MIN_TITLE_CHARS
+ and description_n.startswith(core_n[:_ECHO_PREFIX_CHARS])
+ )
+ if echoes_title:
+ cta_match = _CTA_TAIL_RE.search(_echo_remainder(core, description))
+ if cta_match:
+ result["templated"] = True
+ result["cta_phrase"] = _normalise(cta_match.group(1))
+ result["flags"].append("templated-metadata")
+ signals.append(_finding(
+ "templated_metadata", "high",
+ "Meta description repeats the title verbatim and then closes with a "
+ "stock call to action. Bulk metadata jobs emit this shape on every "
+ "page at once, and site-wide templated metadata reads as scaled "
+ "content abuse even when the body copy is original.",
+ "Rewrite the description to say what the title does not: what the page "
+ "does, for whom, and what makes it different. 150-160 characters, no "
+ "stock CTA.",
+ ))
+ else:
+ result["flags"].append("description-echoes-title")
+ signals.append(_finding(
+ "description_echoes_title", "medium",
+ "Meta description opens with the exact text of the title, so the SERP "
+ "snippet says the same thing twice.",
+ "Open the description with information the title does not already "
+ "carry.",
+ ))
+
+ # 2. Brand suffix concatenated into the description body.
+ parts = _BRAND_SEPARATOR_RE.split(title)
+ if len(parts) > 1:
+ brand = parts[-1].strip()
+ brand_n = _normalise(brand)
+ if (
+ _BRAND_MIN_CHARS <= len(brand) <= _BRAND_MAX_CHARS
+ and brand_n
+ and brand_n in description_n
+ and not description.startswith(brand)
+ ):
+ result["flags"].append("brand-suffix-in-description")
+ signals.append(_finding(
+ "brand_suffix_in_description", "low",
+ f"The title's brand suffix {brand!r} was concatenated into the meta "
+ "description body. That is a generation artefact rather than a "
+ "written sentence, and it spends SERP characters on your own name.",
+ f"Remove {brand!r} from the description body; the title already "
+ "carries it.",
+ ))
+
+ # 3. Description and title are the same string.
+ if len(title_n) >= _MIN_TITLE_CHARS and description_n == title_n:
+ result["flags"].append("description-duplicates-title")
+ signals.append(_finding(
+ "description_duplicates_title", "medium",
+ "Meta description is identical to the title tag. Google has two SERP "
+ "slots and both currently say the same thing.",
+ "Write a description that expands on the title instead of repeating it.",
+ ))
+
+ order = {"high": 3, "medium": 2, "low": 1}
+ if signals:
+ result["severity"] = max((s["severity"] for s in signals), key=lambda s: order[s])
+ return result
+
+
+def analyse_pairs(pairs: Iterable[dict]) -> dict:
+ """Roll single-page results up to the site level.
+
+ ``pairs`` yields mappings with ``title`` and ``description`` keys and
+ an optional ``url``. The site view is the operational unit: one
+ templated description is an oversight, the same shape on a third of
+ the site is the pattern Google's spam systems act on.
+ """
+ pages = [
+ analyse(p.get("title", ""), p.get("description", ""), p.get("url"))
+ for p in pairs
+ ]
+ templated = [p for p in pages if p["templated"]]
+ checked = len(pages)
+ ratio = len(templated) / checked if checked else 0.0
+
+ shared: dict[str, int] = {}
+ for page in templated:
+ phrase = page["cta_phrase"]
+ if phrase:
+ shared[phrase] = shared.get(phrase, 0) + 1
+ shared = dict(sorted(shared.items(), key=lambda kv: (-kv[1], kv[0])))
+
+ site_flags: list[str] = []
+ site_risk = "low"
+ if len(templated) >= _SITE_MIN_TEMPLATED_PAGES and ratio >= _SITE_HIGH_RATIO:
+ site_flags.append("site-wide-templated-metadata")
+ site_risk = "high"
+ elif len(templated) >= _SITE_MIN_TEMPLATED_PAGES and ratio >= _SITE_MEDIUM_RATIO:
+ site_flags.append("templated-metadata-cluster")
+ site_risk = "medium"
+ elif templated:
+ site_flags.append("templated-metadata-isolated")
+ if any(count >= _SITE_MIN_TEMPLATED_PAGES for count in shared.values()):
+ site_flags.append("shared-cta-tail")
+
+ return {
+ "pages": pages,
+ "pages_checked": checked,
+ "templated_count": len(templated),
+ "templated_ratio": round(ratio, 3),
+ "shared_cta_phrases": shared,
+ "site_flags": site_flags,
+ "site_risk": site_risk,
+ }
+
+
+def _load_pairs(path: str) -> list[dict]:
+ """Read a JSON list of {url, title, description} objects.
+
+ Also accepts ``parse_html.py`` output shape, where the description
+ key is ``meta_description``.
+ """
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ if isinstance(data, dict):
+ data = data.get("pages", [data])
+ pairs = []
+ for row in data:
+ pairs.append({
+ "url": row.get("url"),
+ "title": row.get("title") or "",
+ "description": row.get("description") or row.get("meta_description") or "",
+ })
+ return pairs
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description="Templated-metadata detector (title echo + stock CTA)."
+ )
+ parser.add_argument("--title", help="Title tag of a single page.")
+ parser.add_argument("--description", help="Meta description of a single page.")
+ parser.add_argument("--url", help="URL to label the single-page result with.")
+ parser.add_argument(
+ "--pairs-file",
+ help="JSON list of {url, title, description} objects (parse_html.py "
+ "output with meta_description is also accepted).",
+ )
+ parser.add_argument("--json", action="store_true", help="Emit JSON to stdout.")
+ parser.add_argument(
+ "--fail-on",
+ choices=("none", "any", "site"),
+ default="none",
+ help="Exit non-zero on any templated page ('any'), on a site-level "
+ "flag ('site'), or never (default 'none').",
+ )
+ args = parser.parse_args()
+
+ if args.pairs_file:
+ pairs = _load_pairs(args.pairs_file)
+ elif args.title is not None or args.description is not None:
+ pairs = [{
+ "url": args.url,
+ "title": args.title or "",
+ "description": args.description or "",
+ }]
+ else:
+ print(
+ "Error: pass --title/--description for one page, or --pairs-file "
+ "for a site.",
+ file=sys.stderr,
+ )
+ return 2
+
+ result = analyse_pairs(pairs)
+
+ if args.json:
+ json.dump(result, sys.stdout, indent=2)
+ sys.stdout.write("\n")
+ else:
+ print(f"Pages checked: {result['pages_checked']}")
+ print(f"Templated pages: {result['templated_count']} "
+ f"({result['templated_ratio']:.0%})")
+ print(f"Site risk: {result['site_risk']}")
+ if result["site_flags"]:
+ print(f"Site flags: {', '.join(result['site_flags'])}")
+ for phrase, count in result["shared_cta_phrases"].items():
+ print(f" shared CTA tail: {phrase!r} on {count} page(s)")
+ print()
+ for page in result["pages"]:
+ if not page["signals"]:
+ continue
+ label = page["url"] or page["title"][:60]
+ print(f" {label} [{page['severity']}]")
+ for signal in page["signals"]:
+ print(f" {signal['severity']:<6} {signal['id']}")
+ print(f" {signal['message']}")
+
+ if args.fail_on == "any" and result["templated_count"]:
+ return 1
+ if args.fail_on == "site" and result["site_risk"] in ("high", "medium"):
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/seo-page/SKILL.md b/skills/seo-page/SKILL.md
index 2fce3aa..3ab1f32 100644
--- a/skills/seo-page/SKILL.md
+++ b/skills/seo-page/SKILL.md
@@ -21,6 +21,12 @@ metadata:
### On-Page SEO
- Title tag: 50-60 characters, includes primary keyword, unique
- Meta description: 150-160 characters, compelling, includes keyword
+- Meta description is not a restatement of the title: run
+ `claude-seo run metadata_template.py --title "<title>" --description "<desc>" --json`.
+ A description that opens by repeating its own title and closes on a stock CTA
+ ("Try it free now.", "Start free!") is templated metadata, the shape bulk
+ generation jobs produce site-wide, and it reads as scaled content abuse
+ regardless of how original the body copy is
- H1: exactly one, matches page intent, includes keyword
- H2-H6: logical hierarchy (no skipped levels), descriptive
- URL: short, descriptive, hyphenated, no parameters
diff --git a/skills/seo-programmatic/SKILL.md b/skills/seo-programmatic/SKILL.md
index 63a8e60..7ccc4e7 100644
--- a/skills/seo-programmatic/SKILL.md
+++ b/skills/seo-programmatic/SKILL.md
@@ -116,6 +116,8 @@ Unique content % = (words unique to this page) / (total words on page) × 100
Measure against all other pages in the programmatic set. Shared headers, footers, and navigation are excluded from the calculation. Template boilerplate text IS included.
+**Metadata is scored separately.** This calculation covers body copy only, so a set that passes it can still carry one generated title/description shape on every URL. Run `claude-seo run metadata_template.py --pairs-file <file> --json` over the whole set and treat a `site_risk` of `high` as a gate failure regardless of body uniqueness.
+
## Canonical Strategy
- Every programmatic page must have a self-referencing canonical tag
diff --git a/skills/seo/references/quality-gates.md b/skills/seo/references/quality-gates.md
index 0086529..9be76b0 100644
--- a/skills/seo/references/quality-gates.md
+++ b/skills/seo/references/quality-gates.md
@@ -94,9 +94,20 @@ Google's doorway page algorithm penalizes programmatic location pages with thin/
|--------|-------------|
| Minimum length | 120 characters |
| Maximum length | 160 characters (Google truncates ~155-160) |
-| Call-to-action | Include compelling CTA |
+| Call-to-action | Include compelling CTA, written for this page |
| Primary keyword | Include naturally |
| Uniqueness | Each page must have unique description |
+| Not a title restatement | Must not open by repeating the title tag verbatim |
+
+> **Templated metadata gate.** "Unique per page" is necessary but not
+> sufficient: 26 descriptions can each be unique strings while all sharing one
+> generated shape. Opening with the page title and closing on a stock CTA
+> ("Try it free now.", "Start free!") is that shape, and site-wide it reads as
+> scaled content abuse under Google's spam policies even when the body copy is
+> entirely original. Check with
+> `claude-seo run metadata_template.py --pairs-file <file> --json`. The CTA
+> requirement above means a CTA written for this page, not one appended to every
+> page by a template.
---
diff --git a/tests/test_metadata_template.py b/tests/test_metadata_template.py
new file mode 100644
index 0000000..52d9913
--- /dev/null
+++ b/tests/test_metadata_template.py
@@ -0,0 +1,361 @@
+"""
+Tests for scripts/metadata_template.py — the templated-metadata detector.
+
+The true-positive corpus is the real metadata that got a live site demoted
+by the June 2026 spam update for scaled content abuse: a bulk CSV metadata
+job wrote a description for every page that restates the page title and
+then appends a stock CTA.
+
+The false-positive corpus is the harder half. Every entry is legitimate
+metadata that a naive "description contains the title" rule would flag —
+pages that open with their own topic phrase because that is how a sentence
+about that topic starts, plus one page that ends on a genuine call to
+action without echoing its title.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
+if _SCRIPTS not in sys.path:
+ sys.path.insert(0, _SCRIPTS)
+
+import metadata_template # noqa: E402
+
+
+# ---------------------------------------------------------------------------
+# True positives: templated title + description pairs
+# ---------------------------------------------------------------------------
+
+_TEMPLATED_PAIRS = [
+ (
+ "Readability Checker Tool: Improve Writing Score Fast",
+ "Readability Checker Tool: Improve Writing Score Fast analyzes readability, "
+ "boosts writing clarity & improves content score. Try it free now.",
+ ),
+ (
+ "Text Summarizer Tool: Complete AI Summary Generator",
+ "Text Summarizer Tool: Complete AI Summary Generator creates instant, accurate "
+ "summaries and saves reading time. Try it free now.",
+ ),
+ (
+ "Google Penalty Risk Scanner: Best SEO Audit Tool",
+ "Google Penalty Risk Scanner: Best SEO Audit Tool detects SEO risks, penalties "
+ "& ranking issues. Start your free scan now.",
+ ),
+ (
+ "Keyword Density Checker: Free SEO Optimization Tool",
+ "Keyword Density Checker: Free SEO Optimization Tool analyzes keyword usage, "
+ "improves SEO balance & boosts rankings. Try it free now.",
+ ),
+ (
+ "Online Notepad: Free Auto-Save Writing Editor Tool",
+ "Online Notepad: Free Auto-Save Writing Editor Tool lets you write, edit & save "
+ "notes instantly with auto-save. Try it free now.",
+ ),
+ (
+ "E-E-A-T Audit Guide: Complete Website Quality Review System",
+ "E-E-A-T Audit Guide: Complete Website Quality Review System | Acme Improve SEO "
+ "quality, trust & rankings fast. Start your audit now!",
+ ),
+]
+
+
[email protected]("title,description", _TEMPLATED_PAIRS)
+def test_templated_pairs_are_flagged_high(title: str, description: str) -> None:
+ result = metadata_template.analyse(title, description)
+ assert result["templated"] is True, result
+ assert result["severity"] == "high"
+ assert "templated-metadata" in result["flags"]
+ assert [s["id"] for s in result["signals"]][0] == "templated_metadata"
+
+
[email protected]("title,description", _TEMPLATED_PAIRS)
+def test_templated_pairs_report_the_matched_cta(title: str, description: str) -> None:
+ result = metadata_template.analyse(title, description)
+ assert result["cta_phrase"], result
+ assert result["cta_phrase"] == result["cta_phrase"].lower()
+
+
+# ---------------------------------------------------------------------------
+# False positives: legitimate metadata that must stay clean
+# ---------------------------------------------------------------------------
+
+_LEGITIMATE_PAIRS = [
+ # Description covers the same topic but opens with new information.
+ (
+ "Readability Checker: Flesch Reading Ease & Grade Level Score",
+ "Free readability checker: get a Flesch Reading Ease score, Flesch-Kincaid grade "
+ "level, Gunning Fog index, passive voice share, and sentence-length distribution.",
+ ),
+ (
+ "Citation Generator: Free APA, MLA & Chicago Citations",
+ "Free citation generator for APA 7th, MLA 9th, and Chicago 17th edition. Cite "
+ "websites by URL or enter books and journals manually. No signup required.",
+ ),
+ # Opens with its own topic phrase, but adds substance and no stock CTA.
+ (
+ "Helpful Content Update Survival Guide: How to Recover & Stay Safe",
+ "Helpful content update survival guide: how to tell if you were hit, the "
+ "people-first content checklist, and how to recover from the update in 2026.",
+ ),
+ # Short title a sentence can legitimately open with.
+ (
+ "Word Counter",
+ "Word counter that gives instant word, character, sentence and paragraph counts, "
+ "with Common App and IELTS presets built in.",
+ ),
+ # The brand name is genuinely the subject of the page.
+ (
+ "About Acme | Our Story",
+ "Acme was built by two brothers after a client site lost its rankings overnight. "
+ "Here is what we learned and why we made the tools free.",
+ ),
+ # Genuine call to action, but the description never echoes the title.
+ (
+ "Free Grammar Checker Online: Fix Errors in Any Language",
+ "Catch grammar, spelling, punctuation and style mistakes across 20+ languages "
+ "with no word limit and no account. Try it free now.",
+ ),
+ # Echoes the title (editorially fine) and happens to end on the word
+ # "now" in its ordinary sense, not as a CTA.
+ (
+ "Core Web Vitals Thresholds: The Numbers Google Uses Today",
+ "Core Web Vitals thresholds: the numbers Google uses today, including the INP "
+ "cutoff that replaced FID and what a passing score actually means now.",
+ ),
+ # Echoes the title and closes on the word "free" as a pricing fact, not as
+ # an instruction to start a free trial.
+ (
+ "Schema Markup Validator: Test JSON-LD Against Google's Rules",
+ "Schema Markup Validator: Test JSON-LD Against Google's Rules for Product, "
+ "Article and Event, see every required property, and check 200 URLs for free.",
+ ),
+]
+
+
[email protected]("title,description", _LEGITIMATE_PAIRS)
+def test_legitimate_pairs_are_not_flagged_templated(title: str, description: str) -> None:
+ result = metadata_template.analyse(title, description)
+ assert result["templated"] is False, result
+ assert "templated-metadata" not in result["flags"]
+ assert result["severity"] != "high"
+
+
+def test_cta_alone_is_not_enough_to_flag() -> None:
+ """A stock CTA is only evidence when the description also echoes the title."""
+ title = "Free Grammar Checker Online: Fix Errors in Any Language"
+ description = (
+ "Catch grammar, spelling, punctuation and style mistakes across 20+ languages "
+ "with no word limit and no account. Try it free now."
+ )
+ assert (title, description) in _LEGITIMATE_PAIRS
+ assert metadata_template._CTA_TAIL_RE.search(description) is not None
+ assert metadata_template.analyse(title, description)["templated"] is False
+
+
+def test_short_title_echo_is_not_flagged() -> None:
+ """Titles under the length floor can be echoed by a normal sentence."""
+ result = metadata_template.analyse(
+ "Word Counter",
+ "Word counter that counts words, characters and sentences. Try it free now.",
+ )
+ assert result["signals"] == []
+
+
+# ---------------------------------------------------------------------------
+# The secondary signals
+# ---------------------------------------------------------------------------
+
+
+def test_brand_suffix_leaked_into_description() -> None:
+ result = metadata_template.analyse(
+ "Word to HTML Converter | Acme",
+ "Word to HTML Converter | Acme Generate clean, fast HTML from any Word document.",
+ )
+ ids = [s["id"] for s in result["signals"]]
+ assert "brand_suffix_in_description" in ids
+
+
+def test_brand_named_first_in_description_is_not_a_leak() -> None:
+ result = metadata_template.analyse(
+ "Acme Pricing | Acme",
+ "Acme costs nothing for the free tier and $9/month for Pro, billed annually.",
+ )
+ assert "brand_suffix_in_description" not in [s["id"] for s in result["signals"]]
+
+
+def test_description_identical_to_title() -> None:
+ title = "Complete Guide to Structured Data for Ecommerce Sites"
+ result = metadata_template.analyse(title, title)
+ ids = [s["id"] for s in result["signals"]]
+ assert "description_duplicates_title" in ids
+ assert result["severity"] == "medium"
+
+
+def test_title_echo_without_cta_is_medium_not_high() -> None:
+ result = metadata_template.analyse(
+ "Complete Guide to Structured Data for Ecommerce Sites",
+ "Complete Guide to Structured Data for Ecommerce Sites covering Product, Offer "
+ "and AggregateRating, with validator output for each type.",
+ )
+ assert result["templated"] is False
+ assert result["severity"] == "medium"
+ assert "description-echoes-title" in result["flags"]
+
+
+# ---------------------------------------------------------------------------
+# Edge cases: nothing here may raise
+# ---------------------------------------------------------------------------
+
+_EDGE_CASES = [
+ ("", ""),
+ ("", "Some description"),
+ ("A title", ""),
+ ("x", "x"),
+ ("|", "|"),
+ ("Title | Brand", "Title | Brand"),
+ ("A" * 500, "A" * 500),
+ (
+ "Title <script>alert(1)</script>",
+ "Title <script>alert(1)</script> and more text here to pad it out nicely",
+ ),
+ ("Café Niño — Über Guide", "Café Niño — Über Guide teaches you everything. Learn more now!"),
+ ("Title: Sub — Part | Brand", "Title: Sub — Part | Brand does the thing you need. Start free!"),
+]
+
+
[email protected]("title,description", _EDGE_CASES)
+def test_edge_cases_return_a_well_formed_result(title: str, description: str) -> None:
+ result = metadata_template.analyse(title, description)
+ assert set(result) >= {"templated", "severity", "flags", "signals"}
+ assert isinstance(result["signals"], list)
+ assert result["severity"] in ("none", "low", "medium", "high")
+
+
+def test_missing_metadata_is_reported_not_flagged() -> None:
+ result = metadata_template.analyse("", "")
+ assert result["flags"] == ["missing-metadata"]
+ assert result["templated"] is False
+
+
+def test_none_inputs_are_tolerated() -> None:
+ assert metadata_template.analyse(None, None)["templated"] is False
+
+
+# ---------------------------------------------------------------------------
+# Site-level roll-up (the unit the spam signal actually operates on)
+# ---------------------------------------------------------------------------
+
+
+def _pairs(templated: int, clean: int) -> list[dict]:
+ rows = []
+ for i in range(templated):
+ title, description = _TEMPLATED_PAIRS[i % len(_TEMPLATED_PAIRS)]
+ rows.append({"url": f"https://example.com/t{i}", "title": title,
+ "description": description})
+ for i in range(clean):
+ title, description = _LEGITIMATE_PAIRS[i % len(_LEGITIMATE_PAIRS)]
+ rows.append({"url": f"https://example.com/c{i}", "title": title,
+ "description": description})
+ return rows
+
+
+def test_site_wide_templating_is_high_risk() -> None:
+ result = metadata_template.analyse_pairs(_pairs(templated=6, clean=6))
+ assert result["templated_count"] == 6
+ assert result["templated_ratio"] == 0.5
+ assert result["site_risk"] == "high"
+ assert "site-wide-templated-metadata" in result["site_flags"]
+
+
+def test_one_templated_page_is_not_a_site_pattern() -> None:
+ result = metadata_template.analyse_pairs(_pairs(templated=1, clean=20))
+ assert result["templated_count"] == 1
+ assert result["site_risk"] == "low"
+ assert result["site_flags"] == ["templated-metadata-isolated"]
+
+
+def test_clean_site_has_no_flags() -> None:
+ result = metadata_template.analyse_pairs(_pairs(templated=0, clean=6))
+ assert result["templated_count"] == 0
+ assert result["site_flags"] == []
+ assert result["site_risk"] == "low"
+
+
+def test_shared_cta_tail_is_counted_across_pages() -> None:
+ result = metadata_template.analyse_pairs(_pairs(templated=6, clean=0))
+ assert "shared-cta-tail" in result["site_flags"]
+ assert sum(result["shared_cta_phrases"].values()) == 6
+ assert max(result["shared_cta_phrases"].values()) >= 3
+
+
+def test_empty_site_does_not_divide_by_zero() -> None:
+ result = metadata_template.analyse_pairs([])
+ assert result["pages_checked"] == 0
+ assert result["templated_ratio"] == 0.0
+ assert result["site_risk"] == "low"
+
+
+# ---------------------------------------------------------------------------
+# CLI contract
+# ---------------------------------------------------------------------------
+
+
+def _run_cli(*args: str) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ [sys.executable, os.path.join(_SCRIPTS, "metadata_template.py"), *args],
+ capture_output=True, text=True,
+ )
+
+
+def test_cli_emits_valid_json() -> None:
+ title, description = _TEMPLATED_PAIRS[0]
+ proc = _run_cli("--title", title, "--description", description, "--json")
+ assert proc.returncode == 0, proc.stderr
+ payload = json.loads(proc.stdout)
+ assert payload["templated_count"] == 1
+ assert payload["pages"][0]["signals"][0]["id"] == "templated_metadata"
+
+
+def test_cli_fail_on_any_exits_nonzero() -> None:
+ title, description = _TEMPLATED_PAIRS[0]
+ proc = _run_cli("--title", title, "--description", description,
+ "--json", "--fail-on", "any")
+ assert proc.returncode == 1, proc.stdout
+
+
+def test_cli_without_input_returns_usage_error() -> None:
+ proc = _run_cli("--json")
+ assert proc.returncode == 2
+ assert "Error:" in proc.stderr
+
+
+def test_cli_reads_a_pairs_file(tmp_path) -> None:
+ path = tmp_path / "pairs.json"
+ path.write_text(json.dumps(_pairs(templated=4, clean=4)), encoding="utf-8")
+ proc = _run_cli("--pairs-file", str(path), "--json")
+ assert proc.returncode == 0, proc.stderr
+ payload = json.loads(proc.stdout)
+ assert payload["pages_checked"] == 8
+ assert payload["templated_count"] == 4
+ assert payload["site_risk"] == "high"
+
+
+def test_pairs_file_accepts_parse_html_meta_description_key(tmp_path) -> None:
+ title, description = _TEMPLATED_PAIRS[0]
+ path = tmp_path / "parsed.json"
+ path.write_text(
+ json.dumps({"url": "https://example.com/", "title": title,
+ "meta_description": description}),
+ encoding="utf-8",
+ )
+ proc = _run_cli("--pairs-file", str(path), "--json")
+ assert proc.returncode == 0, proc.stderr
+ assert json.loads(proc.stdout)["templated_count"] == 1