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.

fix(sitemap): checkable samples, correct duplicate counts, malformed URLs never raise

Agrici Daniel8654551ef1fa
diff --git a/agents/seo-sitemap.md b/agents/seo-sitemap.md
index 4646ba4..3f54b52 100644
--- a/agents/seo-sitemap.md
+++ b/agents/seo-sitemap.md
@@ -13,7 +13,7 @@ When working with sitemaps:
1. Discover and read sitemaps with `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run sitemap_discovery.py <url> --expand --json`.
Use only validated `found` entries and retain declared failures as findings.
2. Take file facts from `expanded.files` and `expanded.totals` (table below); do not count or parse sitemap files by hand
-3. Check URL status codes on each file's `sample_urls`
+3. Check URL status codes on each file's `sample_urls` (exact URLs, query string kept). Do not status-check `redacted_url_examples` or `cross_host_url_examples`: values or query strings were removed from those
4. Check for deprecated tags (priority, changefreq: both ignored by Google)
5. Verify lastmod accuracy (reflects last *significant* change, not boilerplate)
6. Compare crawled pages vs sitemap coverage
@@ -30,7 +30,8 @@ When working with sitemaps:
| lastmod present, valid W3C Datetime | `lastmod_count` against `url_count`, `lastmod_invalid_count` |
| lastmod identical across a file | `lastmod_identical_share` near 1.0, `lastmod_most_common`, `lastmod_oldest`, `lastmod_newest` |
| URLs on another host than their sitemap | `cross_host_url_count`, `cross_host_url_examples`, `cross_host` on a child file |
-| Duplicate or malformed URLs | `duplicate_count`, `invalid_loc_count`, `totals.unique_urls`, `totals.duplicates_across_files` |
+| Duplicate or malformed URLs | `duplicate_count` (repeats inside one file), `totals.duplicates_across_files` (listed by an earlier file), `invalid_loc_count`, `totals.unique_urls` |
+| Tokens or session IDs in listed URLs | `redacted_url_count`, `redacted_url_examples` |
| Run cut short | `truncated`, `children.skipped`; rerun with a higher `--max-children` (default 50) |
## Quality Gates
diff --git a/scripts/sitemap_discovery.py b/scripts/sitemap_discovery.py
index 2c2b5ca..c1f7787 100644
--- a/scripts/sitemap_discovery.py
+++ b/scripts/sitemap_discovery.py
@@ -15,9 +15,24 @@ Usage:
--expand also reads every sitemap that was found: it follows a sitemap index
one level down to its child sitemaps and adds an "expanded" object with
-per-file statistics
-(URL count, lastmod quality, off-host entries, protocol limit findings) and
-totals across files. Every URL is counted; only a bounded sample is printed.
+per-file statistics (URL count, lastmod quality, off-host entries, protocol
+limit findings) and totals across files. Every URL is counted; only a bounded
+sample is printed.
+
+Sitemap file URLs are printed without their query string ("query_redacted").
+"sample_urls" are page URLs meant to be requested, so they keep their query;
+a page URL with a credential-like parameter (token, session, signature) is
+never sampled, and is counted and shown with the value replaced in
+"redacted_url_count" and "redacted_url_examples" instead.
+
+Duplicates are counted per entry, after normalisation. In one file, the first
+entry for a URL that an earlier file already listed is one cross-file
+duplicate ("duplicates_across_files"); every further entry for a URL the same
+file already listed is one within-file duplicate ("duplicate_count",
+"duplicates_within_files"). Each entry is counted once, so for the page
+sitemaps: URLs = unique + within-file + cross-file duplicates + invalid locs.
+
+A malformed URL in robots.txt or in a sitemap is recorded and skipped.
"""
from __future__ import annotations
@@ -74,13 +89,26 @@ _W3C_DATETIME = re.compile(
r"(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2}))?)?)?",
re.ASCII,
)
+# Query parameters whose value is a credential, not part of the page address.
+_SECRET_PARAM = re.compile(
+ r"token|secret|passw|signature|credential|session|sessid|api[-_]?key|access[-_]?key"
+ r"|^(?:key|sig|auth|pwd|sid|jwt)$"
+)
+_MALFORMED = "Malformed sitemap URL"
# Element that holds one entry, per sitemap kind.
_ENTRY_TAG = {"urlset": "url", "sitemapindex": "sitemap", "rss": "item", "feed": "entry"}
def _display_url(url: str) -> tuple[str, bool]:
- """Return a safe-to-display URL with userinfo, query, and fragment removed."""
- parsed = urlparse(url)
+ """Return a safe-to-display URL with userinfo, query, and fragment removed.
+
+ Never raises: text that does not parse as a URL is cut the same way by hand.
+ """
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ text = re.split(r"[?#]", url, maxsplit=1)[0]
+ return re.sub(r"(?<=//)[^/]*@", "", text), True
host = parsed.hostname or ""
try:
port = parsed.port
@@ -142,6 +170,9 @@ def _bounded_fetch(url: str, max_bytes: int) -> dict:
result["error"] = "Request timed out"
except requests.exceptions.RequestException:
result["error"] = "Request failed"
+ except ValueError:
+ # Text that is not a URL at all, such as an unclosed IPv6 bracket.
+ result["error"] = _MALFORMED
return result
@@ -213,7 +244,7 @@ def _classify(content: bytes, content_type: str, url: str) -> tuple[str | None,
return local, None, root, None
return None, "unsupported XML root", None, None
- if "text/plain" in content_type.lower() or urlparse(url).path.lower().endswith(".txt"):
+ if "text/plain" in content_type.lower() or _url_path(url).lower().endswith(".txt"):
# Decode the BOM-free bytes: a leading UTF-8 BOM is an encoding
# signature, not part of the first URL.
lines = [line.strip() for line in stripped.decode("utf-8", errors="replace").splitlines() if line.strip()]
@@ -281,10 +312,13 @@ def _read_body(fetched: dict) -> dict:
body["error"] = _TOO_LARGE
return body
body["decompressed_bytes"] = len(content)
- parsed = urlparse(url)
- if parsed.path.lower().endswith(".gz"):
- # sitemap.txt.gz is a text sitemap: classify it by the inner name.
- url = urlunparse(parsed._replace(path=parsed.path[:-3]))
+ try:
+ parsed = urlparse(url)
+ if parsed.path.lower().endswith(".gz"):
+ # sitemap.txt.gz is a text sitemap: classify it by the inner name.
+ url = urlunparse(parsed._replace(path=parsed.path[:-3]))
+ except ValueError:
+ pass
body["kind"], body["error"], body["root"], body["lines"] = _classify(content, fetched["content_type"], url)
return body
@@ -307,8 +341,51 @@ def _fetch_sitemap(url: str) -> tuple[dict, dict | None, str | None]:
return fetched, body, body["error"]
+def _parses(url: str) -> bool:
+ try:
+ urlparse(url)
+ except ValueError:
+ return False
+ return True
+
+
+def _url_path(url: str) -> str:
+ try:
+ return urlparse(url).path
+ except ValueError:
+ return ""
+
+
def _host(url: str) -> str:
- return (urlparse(url).hostname or "").lower().rstrip(".")
+ """Lower-case host of a URL; empty when the text does not parse."""
+ try:
+ return (urlparse(url).hostname or "").lower().rstrip(".")
+ except ValueError:
+ return ""
+
+
+def _sample_url(loc: str) -> tuple[str, bool]:
+ """Return a valid page URL as printed, and whether a value was replaced.
+
+ A sample is there to be requested, so the query is kept. The fragment is
+ dropped (it is never sent). The value of a credential-like parameter is
+ replaced, which makes that URL useless for a status check.
+ """
+ if "?" not in loc:
+ return loc.split("#", 1)[0], False
+ parsed = urlparse(loc)
+ pairs = []
+ replaced = False
+ for pair in parsed.query.split("&"):
+ key, equals, _value = pair.partition("=")
+ if equals and _SECRET_PARAM.search(unquote(key).lower()):
+ pair = f"{key}=REDACTED"
+ replaced = True
+ pairs.append(pair)
+ if not replaced:
+ return loc.split("#", 1)[0], False
+ netloc = parsed.netloc.rpartition("@")[2]
+ return urlunparse((parsed.scheme, netloc, parsed.path, parsed.params, "&".join(pairs), "")), True
def _local(element) -> str:
@@ -396,7 +473,13 @@ def _normalize_url(url: str) -> str | None:
class _Expansion:
- """Per-file statistics and cross-file totals for --expand."""
+ """Per-file statistics and cross-file totals for --expand.
+
+ Duplicates are counted per entry on the normalised URL. In one file, the
+ first entry for a URL that an earlier file listed is a cross-file
+ duplicate; any further entry for a URL that file already listed is a
+ within-file duplicate. No entry is counted both ways.
+ """
def __init__(self, sample_size: int) -> None:
self.sample_size = sample_size
@@ -407,7 +490,7 @@ class _Expansion:
self.analysed: set[str] = set()
# Top-level indexes waiting for their children: (report, final URL, child URLs).
self.pending: list[tuple[dict, str, list[str]]] = []
- # Digest of a normalised URL -> number of the first file that listed it.
+ # Digest of a normalised URL -> number of the last file that listed it.
self.seen: dict[bytes, int] = {}
self.tracking_complete = True
self.unique = 0
@@ -533,6 +616,8 @@ class _Expansion:
"lastmod_identical_share": None,
"cross_host_url_count": None,
"cross_host_url_examples": [],
+ "redacted_url_count": None,
+ "redacted_url_examples": [],
"findings": [],
"sample_urls": [],
"_cross_file_duplicates": 0,
@@ -558,11 +643,13 @@ class _Expansion:
index = kind == "sitemapindex"
file_number = len(self.files)
host = _host(final_url)
- count = invalid = with_lastmod = bad_lastmod = cross_host = repeats = cross_file = 0
+ count = invalid = with_lastmod = bad_lastmod = cross_host = repeats = cross_file = secret = 0
oldest: tuple[datetime, str] | None = None
newest: tuple[datetime, str] | None = None
lastmods: Counter[str] = Counter()
examples: list[str] = report["cross_host_url_examples"]
+ secret_examples: list[str] = report["redacted_url_examples"]
+ sampled: set[str] = set()
children: list[str] = []
child_set: set[str] = set()
for loc, lastmod in entries:
@@ -593,12 +680,18 @@ class _Expansion:
child_set.add(loc)
children.append(loc)
continue
- if len(report["sample_urls"]) < self.sample_size:
- report["sample_urls"].append(_display_url(loc)[0])
- first_file = self._track(loc, file_number)
- if first_file == file_number:
+ shown, replaced = _sample_url(loc)
+ if replaced:
+ secret += 1
+ if len(secret_examples) < MAX_EXAMPLES and shown not in secret_examples:
+ secret_examples.append(shown)
+ elif len(sampled) < self.sample_size and shown not in sampled:
+ sampled.add(shown)
+ report["sample_urls"].append(shown)
+ seen_in = self._track(loc, file_number)
+ if seen_in == "same_file":
repeats += 1
- elif first_file is not None:
+ elif seen_in == "earlier_file":
cross_file += 1
report.update({
@@ -611,6 +704,7 @@ class _Expansion:
"lastmod_oldest": oldest[1] if oldest else None,
"lastmod_newest": newest[1] if newest else None,
"cross_host_url_count": cross_host,
+ "redacted_url_count": secret,
"_cross_file_duplicates": cross_file,
})
if lastmods:
@@ -621,21 +715,31 @@ class _Expansion:
report["findings"].append("over_50000_sitemaps" if index else "over_50000_urls")
return children
- def _track(self, loc: str, file_number: int) -> int | None:
- """Remember a URL. Returns the file that listed it before, or None if new."""
+ def _track(self, loc: str, file_number: int) -> str | None:
+ """Remember one entry and say where its URL was listed before.
+
+ Returns "new", "same_file" (this file already listed it: a within-file
+ duplicate), "earlier_file" (first entry in this file for a URL that an
+ earlier file listed: a cross-file duplicate), or None when the URL
+ cannot be tracked. The table then points at this file, so a second
+ entry here is a within-file duplicate, not another cross-file one.
+ """
key = _normalize_url(loc)
if key is None:
return None
digest = hashlib.blake2b(key.encode("utf-8", "replace"), digest_size=8).digest()
- first_file = self.seen.get(digest)
- if first_file is not None:
- return first_file
- if len(self.seen) < MAX_TRACKED_URLS:
- self.seen[digest] = file_number
- self.unique += 1
- else:
+ last_file = self.seen.get(digest)
+ if last_file is None:
+ if len(self.seen) < MAX_TRACKED_URLS:
+ self.seen[digest] = file_number
+ self.unique += 1
+ return "new"
self.tracking_complete = False
- return None
+ return None
+ if last_file == file_number:
+ return "same_file"
+ self.seen[digest] = file_number
+ return "earlier_file"
def discover_sitemaps(
@@ -708,6 +812,11 @@ def discover_sitemaps(
"valid": False,
"error": None,
}
+ if not _parses(candidate):
+ # robots.txt is page-controlled text: record the line, fetch nothing.
+ entry["error"] = _MALFORMED
+ result["checked"].append(entry)
+ continue
if urlparse(candidate).hostname != target_host and candidate in declared_raw:
entry["cross_host"] = True
diff --git a/skills/seo-sitemap/SKILL.md b/skills/seo-sitemap/SKILL.md
index 48ee957..46a2083 100644
--- a/skills/seo-sitemap/SKILL.md
+++ b/skills/seo-sitemap/SKILL.md
@@ -44,17 +44,22 @@ the output; do not count or parse sitemap files by hand:
| `<lastmod>` present and valid **W3C Datetime** | `lastmod_count` against `url_count`, `lastmod_invalid_count` |
| `<lastmod>` suspiciously uniform | `lastmod_identical_share` near 1.0 on a file with many URLs, with `lastmod_most_common`, `lastmod_oldest`, `lastmod_newest` |
| URLs on another host than their sitemap | `cross_host_url_count`, `cross_host_url_examples`; a child file on another host has `cross_host` |
-| Duplicate or malformed URLs | `duplicate_count`, `invalid_loc_count`; `totals.unique_urls` against `totals.total_urls`, `totals.duplicates_across_files` |
+| Duplicate or malformed URLs | `duplicate_count` (repeats inside one file), `totals.duplicates_across_files` (URL already listed by an earlier file; each entry is counted one way only), `invalid_loc_count`, `totals.unique_urls` against `totals.total_urls` |
+| Tokens or session IDs in listed URLs | `redacted_url_count`, `redacted_url_examples` (values replaced) |
| Sitemap referenced in robots.txt | `source` is `robots.txt` (top-level `declared` lists every directive) |
| Run cut short | `truncated`, `children.skipped`; rerun with a higher `--max-children` (default 50) |
-URLs in the output have query strings removed (`query_redacted`). Every URL is
-counted, but only `--sample` URLs per file (default 20) are printed in
-`sample_urls`.
+Sitemap file URLs (`url`, `parent`) and `cross_host_url_examples` are printed
+without their query string (`query_redacted` refers to the file URL). Every
+page URL is counted, but only `--sample` distinct URLs per file (default 20) are
+printed in `sample_urls`. Those keep their query string and can be requested as
+printed. URLs in `redacted_url_examples` had a value replaced: report them, do
+not status-check them.
### Validation Checks
The script cannot judge these; check them yourself:
-- URLs return HTTP 200: spot-check `sample_urls` from each file
+- URLs return HTTP 200: spot-check `sample_urls` from each file (never
+ `redacted_url_examples` or `cross_host_url_examples`, which are not exact URLs)
- `<lastmod>` accuracy: it must reflect the **last significant content change**
(main content, structured data, links, not copyright/boilerplate edits).
Google only honours `<lastmod>` when consistently and verifiably accurate, so
diff --git a/tests/test_sitemap_expand.py b/tests/test_sitemap_expand.py
index db0d38f..5d313d8 100644
--- a/tests/test_sitemap_expand.py
+++ b/tests/test_sitemap_expand.py
@@ -527,3 +527,107 @@ def test_cli_prints_expanded_json_and_validates_flags(capsys):
with pytest.raises(SystemExit) as stop:
discovery.main()
assert stop.value.code == 2
+
+
+def test_sample_urls_keep_their_query_so_they_can_be_checked():
+ locs = [f"{SITE}/product?id={number}" for number in range(5)]
+ result, _ = run({SITE + "/sitemap.xml": urlset(*locs)})
+ item = file_for(result, "/sitemap.xml")
+ assert item["sample_urls"] == locs
+ assert (item["redacted_url_count"], item["redacted_url_examples"]) == (0, [])
+
+
+def test_sample_urls_are_unique_and_drop_only_the_fragment():
+ body = urlset(SITE + "/a?page=2#top", SITE + "/a?page=2", SITE + "/a?page=2#end", SITE + "/b", SITE + "/b")
+ result, _ = run({SITE + "/sitemap.xml": body}, sample_size=2)
+ assert file_for(result, "/sitemap.xml")["sample_urls"] == [SITE + "/a?page=2", SITE + "/b"]
+
+
+def test_urls_with_token_parameters_are_listed_apart_and_never_sampled():
+ body = urlset(
+ SITE + "/account?token=abc123SECRET&amp;id=1",
+ SITE + "/cart?PHPSESSID=deadbeefSECRET",
+ SITE + "/dl?file=a.pdf&amp;X-Amz-Signature=feedSECRET",
+ SITE + "/blog?author=jane", # "author" is not "auth"
+ SITE + "/search?keyword=shoes", # "keyword" is not "key"
+ )
+ result, _ = run({SITE + "/sitemap.xml": body})
+ item = file_for(result, "/sitemap.xml")
+ assert item["sample_urls"] == [SITE + "/blog?author=jane", SITE + "/search?keyword=shoes"]
+ assert item["redacted_url_count"] == 3
+ assert item["redacted_url_examples"] == [
+ SITE + "/account?token=REDACTED&id=1",
+ SITE + "/cart?PHPSESSID=REDACTED",
+ SITE + "/dl?file=a.pdf&X-Amz-Signature=REDACTED",
+ ]
+ assert "SECRET" not in json.dumps(result)
+ assert (item["url_count"], result["expanded"]["totals"]["unique_urls"]) == (5, 5)
+
+
+def test_a_url_repeated_in_one_file_and_listed_in_an_earlier_file_is_counted_once_each_way():
+ """The reviewer's case: c.xml lists p0 twice, and a.xml already listed p0."""
+ routes = {
+ SITE + "/sitemap.xml": index(SITE + "/a.xml", SITE + "/b.xml", SITE + "/c.xml"),
+ SITE + "/a.xml": urlset(SITE + "/p0", SITE + "/p1", SITE + "/p2"),
+ SITE + "/b.xml": urlset(SITE + "/p2", SITE + "/p3", SITE + "/p4"),
+ SITE + "/c.xml": urlset(SITE + "/p0", SITE + "/p0", SITE + "/zz", SITE + "/p2", SITE + "/zz", SITE + "/zz"),
+ }
+ result, _ = run(routes)
+ assert [file_for(result, name)["duplicate_count"] for name in ("/a.xml", "/b.xml", "/c.xml")] == [0, 0, 3]
+ totals = result["expanded"]["totals"]
+ # b repeats p2 from a; c repeats p0 and p2 from earlier files.
+ assert (totals["duplicates_within_files"], totals["duplicates_across_files"]) == (3, 3)
+ assert (totals["total_urls"], totals["unique_urls"]) == (12, 6)
+ assert totals["total_urls"] == (
+ totals["unique_urls"] + totals["duplicates_within_files"] + totals["duplicates_across_files"]
+ )
+
+
+MALFORMED = [
+ "http://[bad/sitemap.xml",
+ "http://[::1/sitemap.xml",
+ "https://exa\u2100mple.com/sitemap.xml",
+ "http://user:hunter2@[bad/sitemap.xml?token=hunter2",
+]
+
+
[email protected]("bad", MALFORMED)
[email protected]("expand", [False, True])
+def test_malformed_robots_sitemap_line_is_recorded_and_the_run_continues(bad, expand):
+ good = SITE + "/good.xml"
+ robots = f"Sitemap: {bad}\nSitemap: {good}\n".encode()
+ result, fetched = run({good: urlset(SITE + "/a")}, robots=robots, expand=expand)
+ assert bad not in fetched
+ assert [item["url"] for item in result["found"]] == [good]
+ skipped = result["checked"][0]
+ assert (skipped["source"], skipped["valid"], skipped["error"]) == ("robots.txt", False, "Malformed sitemap URL")
+ assert len(result["declared"]) == 2
+ assert "hunter2" not in json.dumps(result)
+
+
[email protected]("bad", MALFORMED)
+def test_malformed_urls_inside_sitemaps_are_counted_invalid(bad):
+ routes = {
+ SITE + "/sitemap.xml": index(bad, SITE + "/posts.xml", SITE + "/urls.txt"),
+ SITE + "/posts.xml": urlset(bad, SITE + "/a"),
+ SITE + "/urls.txt": response(f"{SITE}/b\n{bad}\n".encode(), SITE + "/urls.txt", content_type="text/plain"),
+ }
+ result, fetched = run(routes)
+ assert bad not in fetched
+ assert file_for(result, "/sitemap.xml")["invalid_loc_count"] == 1
+ assert (file_for(result, "/posts.xml")["url_count"], file_for(result, "/posts.xml")["invalid_loc_count"]) == (2, 1)
+ assert file_for(result, "/urls.txt")["error"] == "invalid text sitemap"
+ assert "hunter2" not in json.dumps(result)
+
+
[email protected]("bad", MALFORMED)
+def test_malformed_url_never_raises_from_the_helpers(bad):
+ assert discovery._bounded_fetch(bad, 100)["error"] is not None
+ shown, redacted = discovery._display_url(bad)
+ assert redacted is True and "hunter2" not in shown
+ assert discovery._host(bad) == ""
+ assert discovery.discover_sitemaps(bad)["error"] is not None
+ # A redirect target or content type check on an unparsable final URL.
+ assert discovery._sitemap_kind(b"https://example.com/a\n", "application/octet-stream", bad)[0] is None
+ body = discovery._read_body(response(gzip.compress(urlset(SITE + "/a")), bad))
+ assert body["kind"] == "urlset"