Skip to content

Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.

feat: 4 Phase-2 features (AI-citation scoring, style learning, content decay, quality gate)

Agrici Daniel283ee1fac7a7
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..b603f47
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,9 @@
+repos:
+ - repo: local
+ hooks:
+ - id: blog-quality-gate
+ name: Blog quality gate (score >= 70)
+ entry: python3 scripts/quality_gate.py
+ language: system
+ files: \.(md|mdx)$
+ pass_filenames: true
diff --git a/scripts/ai_citation_score.py b/scripts/ai_citation_score.py
new file mode 100644
index 0000000..eece607
--- /dev/null
+++ b/scripts/ai_citation_score.py
@@ -0,0 +1,579 @@
+#!/usr/bin/env python3
+"""
+AI Citation Probability Scoring.
+
+Usage:
+ python ai_citation_score.py FILE
+ python ai_citation_score.py FILE with format json or markdown
+ python ai_citation_score.py FILE with engine all, ai_overview, perplexity, or chatgpt
+ python ai_citation_score.py DIR in batch mode
+
+Scoring model:
+ Each engine receives a 0-100 probability score from signals produced by
+ analyze_blog.analyze_file. Google AI Overview weights passage extractability,
+ answer-first structure, entity clarity, schema, freshness, and clean headings.
+ Perplexity weights source citations, tier 1 and tier 2 authority, sourced
+ statistics, freshness, and citation diversity. ChatGPT weights clean structure,
+ TLDR, Q&A pairs, entity definitions, extractable lists or tables, and
+ readability. Overall score is a weighted blend: ai_overview 40 percent,
+ perplexity 35 percent, and chatgpt 25 percent.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+import sys; sys.path.insert(0, str(Path(__file__).resolve().parent)); import analyze_blog
+
+
+ENGINE_WEIGHTS: dict[str, float] = {
+ "ai_overview": 0.40,
+ "perplexity": 0.35,
+ "chatgpt": 0.25,
+}
+
+ENGINE_LABELS: dict[str, str] = {
+ "ai_overview": "AI Overview",
+ "perplexity": "Perplexity",
+ "chatgpt": "ChatGPT",
+}
+
+ALL_ENGINES = tuple(ENGINE_WEIGHTS.keys())
+LONG_FLAG = "-" * 2
+
+
+def _to_int(value: Any) -> int:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _to_float(value: Any) -> float:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return 0.0
+
+
+def _clamp_score(value: float) -> int:
+ return max(0, min(100, int(round(value))))
+
+
+def _tier_count(tier_counts: dict[Any, Any], tier: int) -> int:
+ return _to_int(tier_counts.get(tier, tier_counts.get(str(tier), 0)))
+
+
+def _factor(points: int, max_points: int, signal: Any) -> dict[str, Any]:
+ points = max(0, min(max_points, int(points)))
+ return {
+ "points": points,
+ "max_points": max_points,
+ "signal": signal,
+ }
+
+
+def _count_points(count: int, bands: list[tuple[int, int]]) -> int:
+ score = 0
+ for threshold, points in bands:
+ if count >= threshold:
+ score = points
+ return score
+
+
+def _score_ai_overview(analysis: dict[str, Any]) -> dict[str, Any]:
+ ai_ready = analysis.get("ai_citation_readiness", {})
+ headings = analysis.get("headings", {})
+ schema = analysis.get("schema", {})
+ freshness = analysis.get("freshness", {})
+ paragraphs = analysis.get("paragraphs", {})
+
+ citable_passages = _to_int(ai_ready.get("citable_passages"))
+ passage_points = _count_points(citable_passages, [(1, 12), (2, 20), (3, 26), (4, 30)])
+
+ qa_pairs = _to_int(ai_ready.get("qa_pairs"))
+ question_ratio = _to_float(headings.get("h2_question_ratio"))
+ answer_points = min(12, qa_pairs * 4)
+ answer_points += min(5, int(round(question_ratio * 5)))
+ if ai_ready.get("has_tldr"):
+ answer_points += 3
+ answer_points = min(20, answer_points)
+
+ entity_definitions = _to_int(ai_ready.get("entity_definitions"))
+ entity_points = _count_points(entity_definitions, [(1, 7), (2, 12), (3, 15)])
+
+ schema_points = 0
+ if schema.get("has_blogposting"):
+ schema_points += 12
+ elif _to_int(schema.get("schema_count")) > 0:
+ schema_points += 5
+ if schema.get("has_person"):
+ schema_points += 2
+ if schema.get("has_faqpage"):
+ schema_points += 1
+ schema_points = min(15, schema_points)
+
+ freshness_points = 0
+ if freshness.get("has_last_updated"):
+ freshness_points += 7
+ if freshness.get("has_date"):
+ freshness_points += 3
+
+ h2_count = _to_int(headings.get("h2_count"))
+ heading_points = 0
+ if headings.get("hierarchy_clean"):
+ heading_points += 4
+ heading_points += _count_points(h2_count, [(1, 2), (3, 4)])
+ if _to_int(paragraphs.get("max_word_count")) <= 180 and _to_int(paragraphs.get("total_paragraphs")) > 0:
+ heading_points += 2
+ heading_points = min(10, heading_points)
+
+ factors = {
+ "passage_extractability": _factor(
+ passage_points,
+ 30,
+ {
+ "citable_passages_120_to_180_words": citable_passages,
+ "target": "self-contained 130-170 word passages",
+ },
+ ),
+ "answer_first_structure": _factor(
+ answer_points,
+ 20,
+ {
+ "qa_pairs": qa_pairs,
+ "h2_question_ratio": question_ratio,
+ "has_tldr": bool(ai_ready.get("has_tldr")),
+ },
+ ),
+ "entity_clarity": _factor(
+ entity_points,
+ 15,
+ {"entity_definitions": entity_definitions},
+ ),
+ "article_schema": _factor(
+ schema_points,
+ 15,
+ {
+ "has_blogposting_or_article": bool(schema.get("has_blogposting")),
+ "has_person": bool(schema.get("has_person")),
+ "has_faqpage": bool(schema.get("has_faqpage")),
+ },
+ ),
+ "freshness": _factor(
+ freshness_points,
+ 10,
+ {
+ "has_date": bool(freshness.get("has_date")),
+ "has_last_updated": bool(freshness.get("has_last_updated")),
+ },
+ ),
+ "clean_headings": _factor(
+ heading_points,
+ 10,
+ {
+ "h2_count": h2_count,
+ "hierarchy_clean": bool(headings.get("hierarchy_clean")),
+ "max_paragraph_words": _to_int(paragraphs.get("max_word_count")),
+ },
+ ),
+ }
+
+ score = sum(factor["points"] for factor in factors.values())
+ return {"score": _clamp_score(score), "factors": factors}
+
+
+def _score_perplexity(analysis: dict[str, Any]) -> dict[str, Any]:
+ citations = analysis.get("citations", {})
+ freshness = analysis.get("freshness", {})
+
+ inline_citations = _to_int(citations.get("inline_citations"))
+ parenthetical_citations = _to_int(citations.get("paren_citations"))
+ total_citations = inline_citations + parenthetical_citations
+ citation_points = _count_points(total_citations, [(1, 8), (2, 15), (3, 22), (5, 30)])
+
+ tier_counts = citations.get("tier_counts", {})
+ tier_1 = _tier_count(tier_counts, 1)
+ tier_2 = _tier_count(tier_counts, 2)
+ authority_points = 0
+ if tier_1 >= 2:
+ authority_points += 18
+ elif tier_1 == 1:
+ authority_points += 14
+ if tier_2 >= 2:
+ authority_points += 7
+ elif tier_2 == 1:
+ authority_points += 4
+ authority_points = min(25, authority_points)
+
+ sourced_statistics = _to_int(citations.get("sourced_statistics"))
+ unsourced_statistics = _to_int(citations.get("unsourced_statistics"))
+ statistic_points = _count_points(sourced_statistics, [(1, 7), (2, 12), (3, 16), (4, 20)])
+ statistic_points = max(0, statistic_points - min(6, unsourced_statistics * 2))
+
+ freshness_points = 0
+ if freshness.get("has_last_updated"):
+ freshness_points += 10
+ if freshness.get("has_date"):
+ freshness_points += 5
+
+ unique_sources = _to_int(citations.get("unique_sources"))
+ diversity_points = _count_points(unique_sources, [(1, 3), (2, 6), (3, 10)])
+
+ factors = {
+ "source_citations": _factor(
+ citation_points,
+ 30,
+ {
+ "inline_citations": inline_citations,
+ "parenthetical_citations": parenthetical_citations,
+ "total_citations": total_citations,
+ },
+ ),
+ "source_authority": _factor(
+ authority_points,
+ 25,
+ {"tier_1_sources": tier_1, "tier_2_sources": tier_2},
+ ),
+ "sourced_statistics": _factor(
+ statistic_points,
+ 20,
+ {
+ "sourced_statistics": sourced_statistics,
+ "unsourced_statistics": unsourced_statistics,
+ },
+ ),
+ "recency_freshness": _factor(
+ freshness_points,
+ 15,
+ {
+ "has_date": bool(freshness.get("has_date")),
+ "has_last_updated": bool(freshness.get("has_last_updated")),
+ },
+ ),
+ "citation_diversity": _factor(
+ diversity_points,
+ 10,
+ {"unique_sources": unique_sources},
+ ),
+ }
+
+ score = sum(factor["points"] for factor in factors.values())
+ return {"score": _clamp_score(score), "factors": factors}
+
+
+def _score_chatgpt(analysis: dict[str, Any]) -> dict[str, Any]:
+ ai_ready = analysis.get("ai_citation_readiness", {})
+ headings = analysis.get("headings", {})
+ paragraphs = analysis.get("paragraphs", {})
+ structured_data = analysis.get("structured_data", {})
+ readability = analysis.get("readability", {})
+ sentences = analysis.get("sentences", {})
+ faq = analysis.get("faq", {})
+
+ h2_count = _to_int(headings.get("h2_count"))
+ clean_points = _count_points(h2_count, [(1, 3), (3, 8)])
+ if headings.get("hierarchy_clean"):
+ clean_points += 6
+ if _to_int(paragraphs.get("max_word_count")) <= 140 and _to_int(paragraphs.get("total_paragraphs")) > 0:
+ clean_points += 5
+ if _to_float(paragraphs.get("in_range_ratio")) >= 0.35:
+ clean_points += 3
+ if _to_int(paragraphs.get("total_word_count")) >= 600:
+ clean_points += 3
+ clean_points = min(25, clean_points)
+
+ tldr_points = 15 if ai_ready.get("has_tldr") else 0
+
+ qa_pairs = _to_int(ai_ready.get("qa_pairs"))
+ faq_items = _to_int(faq.get("faq_item_count"))
+ qa_points = min(20, qa_pairs * 5 + faq_items * 2 + (4 if faq.get("has_faq_section") else 0))
+
+ entity_definitions = _to_int(ai_ready.get("entity_definitions"))
+ entity_points = _count_points(entity_definitions, [(1, 7), (2, 12), (3, 15)])
+
+ table_count = max(_to_int(ai_ready.get("table_count")), _to_int(structured_data.get("table_count")))
+ list_items = (
+ _to_int(ai_ready.get("list_count"))
+ + _to_int(structured_data.get("unordered_list_items"))
+ + _to_int(structured_data.get("ordered_list_items"))
+ )
+ extract_points = min(15, table_count * 5 + _count_points(list_items, [(3, 4), (6, 7), (10, 10)]))
+
+ flesch = _to_float(readability.get("flesch_reading_ease"))
+ avg_sentence = _to_float(sentences.get("avg_length"))
+ over_20_pct = _to_float(sentences.get("over_20_pct"))
+ readability_points = 0
+ if 45 <= flesch <= 80:
+ readability_points += 4
+ if 10 <= avg_sentence <= 24:
+ readability_points += 3
+ if over_20_pct <= 25:
+ readability_points += 2
+ if _to_int(sentences.get("very_long_count")) == 0:
+ readability_points += 1
+
+ factors = {
+ "clean_structure": _factor(
+ clean_points,
+ 25,
+ {
+ "h2_count": h2_count,
+ "hierarchy_clean": bool(headings.get("hierarchy_clean")),
+ "max_paragraph_words": _to_int(paragraphs.get("max_word_count")),
+ "word_count": _to_int(paragraphs.get("total_word_count")),
+ },
+ ),
+ "tldr_presence": _factor(
+ tldr_points,
+ 15,
+ {"has_tldr": bool(ai_ready.get("has_tldr"))},
+ ),
+ "qa_pairs": _factor(
+ qa_points,
+ 20,
+ {
+ "qa_pairs": qa_pairs,
+ "faq_item_count": faq_items,
+ "has_faq_section": bool(faq.get("has_faq_section")),
+ },
+ ),
+ "entity_definitions": _factor(
+ entity_points,
+ 15,
+ {"entity_definitions": entity_definitions},
+ ),
+ "extractable_lists_tables": _factor(
+ extract_points,
+ 15,
+ {"table_count": table_count, "list_items": list_items},
+ ),
+ "readability": _factor(
+ readability_points,
+ 10,
+ {
+ "flesch_reading_ease": flesch,
+ "avg_sentence_length": avg_sentence,
+ "sentences_over_20_pct": over_20_pct,
+ },
+ ),
+ }
+
+ score = sum(factor["points"] for factor in factors.values())
+ return {"score": _clamp_score(score), "factors": factors}
+
+
+def _engine_results(analysis: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ scored = {
+ "ai_overview": _score_ai_overview(analysis),
+ "perplexity": _score_perplexity(analysis),
+ "chatgpt": _score_chatgpt(analysis),
+ }
+ for engine, result in scored.items():
+ result["weight"] = ENGINE_WEIGHTS[engine]
+ result["probability"] = result["score"]
+ return scored
+
+
+def _overall_score(engine_results: dict[str, dict[str, Any]]) -> int:
+ weighted = sum(engine_results[engine]["score"] * ENGINE_WEIGHTS[engine] for engine in ALL_ENGINES)
+ return _clamp_score(weighted)
+
+
+def _gap(engine_results: dict[str, dict[str, Any]], engine: str, factor: str) -> int:
+ item = engine_results.get(engine, {}).get("factors", {}).get(factor, {})
+ return max(0, _to_int(item.get("max_points")) - _to_int(item.get("points")))
+
+
+def _build_recommendations(
+ engine_results: dict[str, dict[str, Any]],
+ selected_engines: tuple[str, ...],
+) -> list[dict[str, Any]]:
+ single_engine = len(selected_engines) == 1
+
+ candidates = [
+ (
+ "Create three self-contained 130-170 word passages with a 40-60 word direct answer after question H2s.",
+ [("ai_overview", "passage_extractability"), ("ai_overview", "answer_first_structure")],
+ ),
+ (
+ "Add BlogPosting or Article JSON-LD with author and dateModified fields.",
+ [("ai_overview", "article_schema")],
+ ),
+ (
+ "Source every statistic and add at least three unique tier 1 or tier 2 citations.",
+ [
+ ("perplexity", "source_citations"),
+ ("perplexity", "source_authority"),
+ ("perplexity", "sourced_statistics"),
+ ("perplexity", "citation_diversity"),
+ ],
+ ),
+ (
+ "Refresh the post metadata with date and lastUpdated fields.",
+ [("ai_overview", "freshness"), ("perplexity", "recency_freshness")],
+ ),
+ (
+ "Add a TLDR block, Q&A headings, and bold term definitions near the top.",
+ [
+ ("chatgpt", "tldr_presence"),
+ ("chatgpt", "qa_pairs"),
+ ("chatgpt", "entity_definitions"),
+ ],
+ ),
+ (
+ "Add tables or lists that summarize methods, numbers, and decisions.",
+ [("chatgpt", "extractable_lists_tables")],
+ ),
+ (
+ "Tighten headings and paragraph length so sections are easy to scan.",
+ [("ai_overview", "clean_headings"), ("chatgpt", "clean_structure")],
+ ),
+ ]
+
+ ranked: list[dict[str, Any]] = []
+ for text, factor_refs in candidates:
+ impact = 0.0
+ for engine, factor in factor_refs:
+ if engine not in selected_engines:
+ continue
+ weight = 1.0 if single_engine else ENGINE_WEIGHTS[engine]
+ impact += _gap(engine_results, engine, factor) * weight
+ if impact > 0:
+ ranked.append({"recommendation": text, "estimated_impact": int(round(impact))})
+
+ ranked.sort(key=lambda item: (-item["estimated_impact"], item["recommendation"]))
+ return ranked[:3]
+
+
+def score_analysis(analysis: dict[str, Any], engine: str = "all") -> dict[str, Any]:
+ if "error" in analysis:
+ return {"error": analysis["error"]}
+ if engine != "all" and engine not in ALL_ENGINES:
+ return {"error": f"Unknown engine: {engine}"}
+
+ all_results = _engine_results(analysis)
+ selected_engines = ALL_ENGINES if engine == "all" else (engine,)
+ visible_results = {name: all_results[name] for name in selected_engines}
+ overall = _overall_score(all_results)
+
+ return {
+ "file": analysis.get("file", ""),
+ "overall": overall,
+ "overall_probability": overall,
+ "model_weights": ENGINE_WEIGHTS,
+ "engine_filter": engine,
+ "engines": visible_results,
+ "factors": {name: visible_results[name]["factors"] for name in selected_engines},
+ "recommendations": _build_recommendations(all_results, selected_engines),
+ }
+
+
+def score_file(file_path: str | Path, engine: str = "all") -> dict[str, Any]:
+ analysis = analyze_blog.analyze_file(str(file_path))
+ return score_analysis(analysis, engine=engine)
+
+
+def _process_batch(directory: Path, engine: str) -> dict[str, Any]:
+ files: list[Path] = []
+ for pattern in ("*.md", "*.mdx", "*.html"):
+ files.extend(sorted(directory.glob(pattern)))
+
+ results = [score_file(path, engine=engine) for path in sorted(files)]
+ return {
+ "batch": True,
+ "count": len(results),
+ "engine_filter": engine,
+ "model_weights": ENGINE_WEIGHTS,
+ "results": results,
+ }
+
+
+def _format_markdown(result: dict[str, Any]) -> str:
+ if "error" in result:
+ return f"## Error\n\n{result['error']}"
+ if result.get("batch"):
+ parts = [_format_markdown(item) for item in result.get("results", [])]
+ return "\n\n".join(parts)
+
+ file_name = Path(str(result.get("file", ""))).name
+ lines = [
+ f"## AI Citation Probability: {file_name}",
+ "",
+ f"Overall probability: {result.get('overall', 0)}/100",
+ "",
+ "### Engine Scores",
+ ]
+
+ for engine, details in result.get("engines", {}).items():
+ lines.append(f"- {ENGINE_LABELS.get(engine, engine)}: {details.get('score', 0)}/100")
+
+ for engine, details in result.get("engines", {}).items():
+ lines.extend(["", f"### {ENGINE_LABELS.get(engine, engine)} Factors"])
+ for name, factor in details.get("factors", {}).items():
+ label = name.replace("_", " ").title()
+ lines.append(f"- {label}: {factor.get('points', 0)}/{factor.get('max_points', 0)}")
+
+ lines.extend(["", "### Recommendations"])
+ recommendations = result.get("recommendations", [])
+ if recommendations:
+ for item in recommendations:
+ lines.append(f"- {item['recommendation']} Impact {item['estimated_impact']}")
+ else:
+ lines.append("- No score-lifting recommendations found.")
+
+ return "\n".join(lines)
+
+
+def _write_or_print(output: str, output_path: str | None) -> None:
+ if output_path:
+ Path(output_path).write_text(output, encoding="utf-8")
+ print(f"Wrote report to {output_path}", file=sys.stderr)
+ else:
+ print(output)
+
+
+def _json_error(message: str) -> str:
+ return json.dumps({"error": message}, sort_keys=True)
+
+
+def main(argv: list[str] | None = None) -> None:
+ parser = argparse.ArgumentParser(description="AI citation probability scorer")
+ parser.add_argument("input", help="Blog file path or directory")
+ parser.add_argument(f"{LONG_FLAG}format", choices=["json", "markdown"], default="json", help="Output format")
+ parser.add_argument(f"{LONG_FLAG}engine", choices=["all", *ALL_ENGINES], default="all", help="Engine view")
+ parser.add_argument(f"{LONG_FLAG}output", help="Output file path")
+ parser.add_argument(f"{LONG_FLAG}batch", action="store_true", help="Score every markdown or html file in a directory")
+ args = parser.parse_args(argv)
+
+ path = Path(args.input)
+ if not path.exists():
+ print(_json_error(f"File not found: {args.input}"))
+ sys.exit(1)
+
+ if path.is_dir():
+ if not args.batch:
+ print(_json_error(f"Directory input requires batch mode: {args.input}"))
+ sys.exit(1)
+ result = _process_batch(path, args.engine)
+ elif path.is_file():
+ result = score_file(path, engine=args.engine)
+ else:
+ print(_json_error(f"File not found: {args.input}"))
+ sys.exit(1)
+
+ if "error" in result:
+ print(json.dumps(result, sort_keys=True))
+ sys.exit(1)
+
+ if args.format == "markdown":
+ _write_or_print(_format_markdown(result), args.output)
+ else:
+ _write_or_print(json.dumps(result, indent=2, sort_keys=True), args.output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/content_decay.py b/scripts/content_decay.py
new file mode 100644
index 0000000..17a7e53
--- /dev/null
+++ b/scripts/content_decay.py
@@ -0,0 +1,375 @@
+#!/usr/bin/env python3
+"""Detect content decay from two Google Search Console page exports.
+
+The default path is offline: pass a current-period JSON export and a matching
+previous-period JSON export. Each export may be either a JSON list of rows or a
+GSC helper result with a top-level ``rows`` list. Rows should include a page or
+url field plus clicks and impressions.
+
+Optional live export path:
+ python3 skills/blog-google/scripts/run.py gsc_query --property sc-domain:example.com --dimensions page --json
+
+Usage:
+ python content_decay.py current.json previous.json
+ python content_decay.py current.json previous.json --threshold 0.20 --metric clicks
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+SEVERITY_RANK = {
+ "critical": 3,
+ "high": 2,
+ "warning": 1,
+}
+
+
+class ContentDecayError(ValueError):
+ """Raised when an export cannot be used for content decay analysis."""
+
+
+def _as_number(value: Any) -> float:
+ """Return value as a nonnegative float, using 0 for missing values."""
+ if value is None:
+ return 0.0
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return 0.0
+ return max(number, 0.0)
+
+
+def _row_page(row: dict[str, Any]) -> str | None:
+ """Extract a page URL from common GSC row shapes."""
+ for key in ("page", "url", "URL", "landingPage", "landing_page"):
+ value = row.get(key)
+ if value:
+ return str(value)
+
+ keys = row.get("keys")
+ if isinstance(keys, list):
+ for value in keys:
+ if not value:
+ continue
+ text = str(value)
+ if text.startswith(("http://", "https://", "/")):
+ return text
+ return None
+
+
+def load_export(path: str | Path) -> list[dict[str, Any]]:
+ """Load a GSC export from a JSON file and return its row list."""
+ export_path = Path(path)
+ try:
+ raw = export_path.read_text(encoding="utf-8")
+ except OSError as exc:
+ raise ContentDecayError(f"Could not read {export_path}: {exc}") from exc
+
+ if not raw.strip():
+ raise ContentDecayError(f"{export_path} is empty.")
+
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ContentDecayError(f"{export_path} is not valid JSON: {exc.msg}") from exc
+
+ if isinstance(data, list):
+ rows = data
+ elif isinstance(data, dict) and isinstance(data.get("rows"), list):
+ rows = data["rows"]
+ else:
+ raise ContentDecayError(
+ f"{export_path} must be a JSON list or an object with a rows list."
+ )
+
+ if not rows:
+ raise ContentDecayError(f"{export_path} contains no rows.")
+
+ if not all(isinstance(row, dict) for row in rows):
+ raise ContentDecayError(f"{export_path} rows must be JSON objects.")
+
+ return rows
+
+
+def aggregate_pages(rows: list[dict[str, Any]]) -> dict[str, dict[str, float]]:
+ """Aggregate GSC rows by page and sum clicks and impressions."""
+ pages: dict[str, dict[str, float]] = {}
+ for row in rows:
+ page = _row_page(row)
+ if not page:
+ continue
+ if page not in pages:
+ pages[page] = {"clicks": 0.0, "impressions": 0.0}
+ pages[page]["clicks"] += _as_number(row.get("clicks"))
+ pages[page]["impressions"] += _as_number(row.get("impressions"))
+ return pages
+
+
+def classify_severity(decline: float) -> str:
+ """Classify decline severity using fixed content decay thresholds."""
+ if decline >= 0.60:
+ return "critical"
+ if decline >= 0.40:
+ return "high"
+ return "warning"
+
+
+def _decline(previous: float, current: float) -> float:
+ if previous <= 0:
+ return 0.0
+ return max((previous - current) / previous, 0.0)
+
+
+def recommend_action(
+ *,
+ metric: str,
+ threshold: float,
+ severity: str,
+ dropped_out: bool,
+ current: dict[str, float],
+ previous: dict[str, float],
+) -> tuple[str, str]:
+ """Return a recommended action and a short reason."""
+ previous_clicks = previous.get("clicks", 0.0)
+ previous_impressions = previous.get("impressions", 0.0)
+ current_metric = current.get(metric, 0.0)
+ previous_metric = previous.get(metric, 0.0)
+
+ if previous_clicks <= 3 and previous_impressions <= 100:
+ return (
+ "prune",
+ "The page had low prior demand, so pruning may be better than a rewrite.",
+ )
+
+ if dropped_out:
+ return (
+ "consolidate/redirect",
+ "The page disappeared from the current export, so merge or redirect it if a stronger page exists.",
+ )
+
+ if metric == "clicks" and previous_impressions > 0:
+ impression_decline = _decline(
+ previous_impressions, current.get("impressions", 0.0)
+ )
+ if impression_decline < threshold:
+ return (
+ "investigate query shift",
+ "Clicks fell while impressions held up, which can point to ranking, CTR, or query mix changes.",
+ )
+
+ if severity == "critical" and current_metric <= max(1.0, previous_metric * 0.10):
+ return (
+ "consolidate/redirect",
+ "The loss is severe enough that consolidation may recover value faster than a light refresh.",
+ )
+
+ return (
+ "refresh/update content",
+ "The page still has measurable demand, so update the content, title, internal links, and freshness signals.",
+ )
+
+
+def analyze_decay(
+ current_rows: list[dict[str, Any]],
+ previous_rows: list[dict[str, Any]],
+ *,
+ threshold: float = 0.20,
+ metric: str = "clicks",
+) -> dict[str, Any]:
+ """Compare two GSC exports and return a structured content decay report."""
+ if metric not in {"clicks", "impressions"}:
+ raise ContentDecayError("Metric must be clicks or impressions.")
+ if threshold < 0 or threshold > 1:
+ raise ContentDecayError("Threshold must be between 0 and 1.")
+
+ current_pages = aggregate_pages(current_rows)
+ previous_pages = aggregate_pages(previous_rows)
+
+ if not current_pages:
+ raise ContentDecayError("Current export has no usable page rows.")
+ if not previous_pages:
+ raise ContentDecayError("Previous export has no usable page rows.")
+
+ decays: list[dict[str, Any]] = []
+
+ for page, previous in previous_pages.items():
+ current = current_pages.get(page, {"clicks": 0.0, "impressions": 0.0})
+ previous_metric = previous.get(metric, 0.0)
+ current_metric = current.get(metric, 0.0)
+ dropped_out = page not in current_pages
+
+ if previous_metric <= 0:
+ continue
+
+ decline = _decline(previous_metric, current_metric)
+ if decline < threshold and not dropped_out:
+ continue
+
+ severity = classify_severity(decline)
+ action, reason = recommend_action(
+ metric=metric,
+ threshold=threshold,
+ severity=severity,
+ dropped_out=dropped_out,
+ current=current,
+ previous=previous,
+ )
+ decays.append(
+ {
+ "page": page,
+ "severity": severity,
+ "decline": round(decline, 4),
+ "decline_percent": round(decline * 100, 1),
+ "metric": metric,
+ "current_metric": round(current_metric, 2),
+ "previous_metric": round(previous_metric, 2),
+ "current_clicks": round(current.get("clicks", 0.0), 2),
+ "previous_clicks": round(previous.get("clicks", 0.0), 2),
+ "current_impressions": round(current.get("impressions", 0.0), 2),
+ "previous_impressions": round(previous.get("impressions", 0.0), 2),
+ "dropped_out": dropped_out,
+ "recommended_action": action,
+ "action_reason": reason,
+ }
+ )
+
+ decays.sort(
+ key=lambda row: (
+ SEVERITY_RANK[row["severity"]],
+ row["decline"],
+ row["previous_metric"],
+ ),
+ reverse=True,
+ )
+
+ return {
+ "metric": metric,
+ "threshold": threshold,
+ "summary": {
+ "current_pages": len(current_pages),
+ "previous_pages": len(previous_pages),
+ "flagged_pages": len(decays),
+ "dropped_out_pages": sum(1 for row in decays if row["dropped_out"]),
+ "total_current_metric": round(
+ sum(page.get(metric, 0.0) for page in current_pages.values()), 2
+ ),
+ "total_previous_metric": round(
+ sum(page.get(metric, 0.0) for page in previous_pages.values()), 2
+ ),
+ },
+ "decays": decays,
+ }
+
+
+def format_markdown(report: dict[str, Any]) -> str:
+ """Render a content decay report as markdown."""
+ summary = report["summary"]
+ metric = report["metric"]
+ threshold = report["threshold"] * 100
+ lines = [
+ "# Content Decay Report",
+ "",
+ f"Metric: `{metric}`",
+ f"Threshold: {threshold:.0f}%",
+ f"Flagged pages: {summary['flagged_pages']}",
+ f"Dropped out pages: {summary['dropped_out_pages']}",
+ "",
+ ]
+
+ if not report["decays"]:
+ lines.append("No pages met the decay threshold.")
+ return "\n".join(lines) + "\n"
+
+ lines.extend(
+ [
+ "| Severity | Page | Previous | Current | Decline | Dropped out | Recommendation |",
+ "| --- | --- | ---: | ---: | ---: | --- | --- |",
+ ]
+ )
+ for row in report["decays"]:
+ dropped = "yes" if row["dropped_out"] else "no"
+ lines.append(
+ "| {severity} | {page} | {previous:g} | {current:g} | {decline:.1f}% | {dropped} | {action} |".format(
+ severity=row["severity"],
+ page=row["page"],
+ previous=row["previous_metric"],
+ current=row["current_metric"],
+ decline=row["decline_percent"],
+ dropped=dropped,
+ action=row["recommended_action"],
+ )
+ )
+
+ return "\n".join(lines) + "\n"
+
+
+def write_output(text: str, output_path: str | None) -> None:
+ """Write text to a path or stdout."""
+ if output_path:
+ Path(output_path).write_text(text, encoding="utf-8")
+ else:
+ print(text, end="")
+
+
+def build_parser() -> argparse.ArgumentParser:
+ """Build the command line parser."""
+ parser = argparse.ArgumentParser(
+ description="Detect quarter-over-quarter content decay from GSC exports."
+ )
+ parser.add_argument("current", help="Current-period GSC performance export")
+ parser.add_argument("previous", help="Previous-period GSC performance export")
+ parser.add_argument(
+ "--threshold",
+ type=float,
+ default=0.20,
+ help="Minimum decline ratio to flag, default 0.20",
+ )
+ parser.add_argument(
+ "--metric",
+ choices=["clicks", "impressions"],
+ default="clicks",
+ help="Metric to compare, default clicks",
+ )
+ parser.add_argument(
+ "--format",
+ choices=["json", "markdown"],
+ default="json",
+ help="Output format, default json",
+ )
+ parser.add_argument("--output", help="Write report to this path")
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Run the content decay CLI."""
+ parser = build_parser()
+ args = parser.parse_args(argv)
+
+ try:
+ current_rows = load_export(args.current)
+ previous_rows = load_export(args.previous)
+ report = analyze_decay(
+ current_rows,
+ previous_rows,
+ threshold=args.threshold,
+ metric=args.metric,
+ )
+ except ContentDecayError as exc:
+ print(json.dumps({"error": str(exc)}, indent=2))
+ return 1
+
+ if args.format == "markdown":
+ output = format_markdown(report)
+ else:
+ output = json.dumps(report, indent=2) + "\n"
+ write_output(output, args.output)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/quality_gate.py b/scripts/quality_gate.py
new file mode 100644
index 0000000..b71257a
--- /dev/null
+++ b/scripts/quality_gate.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python3
+"""Pre-commit quality gate for blog posts.
+
+The gate filters incoming Markdown and MDX paths to likely blog posts, analyzes
+those posts with the existing analyzer, and fails when a score is below the
+configured threshold.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+SCRIPTS_DIR = Path(__file__).resolve().parent
+sys.path.insert(0, str(SCRIPTS_DIR))
+
+import analyze_blog # noqa: E402
+
+DEFAULT_THRESHOLD = 70
+EXCLUDED_DIRS = {"skills", "docs", "references", "templates", "tests"}
+BLOG_SUFFIXES = {".md", ".mdx"}
+
+
+def _path_for_policy(path: Path, root: Path | None = None) -> Path:
+ """Return a path relative to root when possible for directory checks."""
+ root = (root or Path.cwd()).resolve()
+ try:
+ return path.resolve(strict=False).relative_to(root)
+ except ValueError:
+ return path
+
+
+def is_excluded_path(file_path: str | Path, root: Path | None = None) -> bool:
+ """Return True when the path is inside a non-post content tree."""
+ policy_path = _path_for_policy(Path(file_path), root)
+ parent_parts = {part.lower() for part in policy_path.parts[:-1]}
+ return bool(parent_parts & EXCLUDED_DIRS)
+
+
+def has_blog_frontmatter(file_path: str | Path) -> bool:
+ """Return True when a Markdown file has blog post frontmatter keys."""
+ path = Path(file_path)
+ try:
+ content = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return False
+
+ frontmatter = analyze_blog.extract_frontmatter(content)
+ normalized = {key.lower(): value for key, value in frontmatter.items()}
+ return bool(
+ normalized.get("title")
+ and (normalized.get("description") or normalized.get("date"))
+ )
+
+
+def is_blog_post(file_path: str | Path, root: Path | None = None) -> bool:
+ """Return True when a path should be gated as a blog post."""
+ path = Path(file_path)
+ if path.suffix.lower() not in BLOG_SUFFIXES:
+ return False
+ if is_excluded_path(path, root):
+ return False
+ if not path.is_file():
+ return False
+ return has_blog_frontmatter(path)
+
+
+def _staged_files() -> list[str]:
+ """Read staged file names from Git."""
+ result = subprocess.run(
+ ["git", "diff", "--cached", "--name-only"],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ message = result.stderr.strip() or "Unable to read staged files"
+ raise RuntimeError(message)
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
+
+
+def _dedupe(paths: list[str]) -> list[str]:
+ """Preserve the first occurrence of each path."""
+ seen: set[str] = set()
+ deduped: list[str] = []
+ for path in paths:
+ key = str(Path(path).resolve(strict=False))
+ if key not in seen:
+ seen.add(key)
+ deduped.append(path)
+ return deduped
+
+
+def _top_high_severity_issues(
+ issues: list[dict[str, Any]], limit: int = 3
+) -> list[dict[str, Any]]:
+ return [issue for issue in issues if issue.get("severity") == "high"][:limit]
+
+
+def analyze_post(file_path: str | Path, threshold: int) -> dict[str, Any]:
+ """Analyze a selected post and return gate-oriented result data."""
+ path = Path(file_path)
+ result = analyze_blog.analyze_file(str(path))
+ if "error" in result:
+ score = 0
+ issues = [
+ {
+ "category": "analyzer",
+ "severity": "high",
+ "issue": result["error"],
+ }
+ ]
+ else:
+ score = result["score"]["total"]
+ issues = result["score"].get("issues", [])
+
+ return {
+ "file": str(path),
+ "score": score,
+ "passed": score >= threshold,
+ "issues": _top_high_severity_issues(issues),
+ }
+
+
+def _format_text(results: list[dict[str, Any]], failures: list[dict[str, Any]], threshold: int) -> str:
+ if not failures:
+ if results:
+ return f"Blog quality gate passed: {len(results)} post(s) checked."
+ return "Blog quality gate passed: no blog posts to check."
+
+ lines = [
+ f"Blog quality gate failed: {len(failures)} post(s) below score {threshold}.",
+ ]
+ for failure in failures:
+ lines.append(f"{failure['file']}: score {failure['score']}/100")
+ if failure["issues"]:
+ for issue in failure["issues"]:
+ lines.append(
+ f" [{issue.get('severity', 'high')}] "
+ f"{issue.get('category', 'general')}: {issue.get('issue', '')}"
+ )
+ else:
+ lines.append(" No high severity issues reported.")
+ return "\n".join(lines)
+
+
+def _format_json(
+ results: list[dict[str, Any]], failures: list[dict[str, Any]], threshold: int
+) -> str:
+ payload = {
+ "threshold": threshold,
+ "checked": results,
+ "failures": failures,
+ }
+ return json.dumps(payload, indent=2, sort_keys=True)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ """Build the command line parser."""
+ parser = argparse.ArgumentParser(
+ description="Block commits when selected blog posts score below threshold."
+ )
+ parser.add_argument("files", nargs="*", help="Markdown or MDX files to check")
+ parser.add_argument(
+ "--threshold",
+ type=int,
+ default=DEFAULT_THRESHOLD,
+ help="Minimum accepted analyzer score",
+ )
+ parser.add_argument(
+ "--format",
+ choices=("text", "json"),
+ default="text",
+ help="Output format",
+ )
+ parser.add_argument(
+ "--staged",
+ action="store_true",
+ help="Also check Markdown and MDX files staged in Git",
+ )
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Run the quality gate and return a process exit code."""
+ parser = build_parser()
+ args = parser.parse_args(argv)
+
+ paths = list(args.files)
+ if args.staged:
+ try:
+ paths.extend(_staged_files())
+ except RuntimeError as exc:
+ print(f"Blog quality gate error: {exc}", file=sys.stderr)
+ return 2
+
+ selected = [
+ path
+ for path in _dedupe(paths)
+ if is_blog_post(path, root=Path.cwd())
+ ]
+ results = [analyze_post(path, args.threshold) for path in selected]
+ failures = [result for result in results if not result["passed"]]
+
+ if args.format == "json":
+ print(_format_json(results, failures, args.threshold))
+ else:
+ print(_format_text(results, failures, args.threshold))
+
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/style_learn.py b/scripts/style_learn.py
new file mode 100644
index 0000000..5bfcbc5
--- /dev/null
+++ b/scripts/style_learn.py
@@ -0,0 +1,606 @@
+#!/usr/bin/env python3
+"""Learn an author voice profile from existing blog posts.
+
+Usage:
+ python style_learn.py <files-or-dir...> [--min 5] [--output PATH] [--format json|markdown]
+
+The profiler reuses scripts/analyze_blog.py for per-post style signals, then
+aggregates them into a deterministic JSON profile or a VOICE.md-ready markdown
+block.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import statistics
+import sys
+from collections import Counter
+from pathlib import Path
+from typing import Any, Sequence
+
+SCRIPT_DIR = Path(__file__).resolve().parent
+sys.path.insert(0, str(SCRIPT_DIR))
+
+import analyze_blog # noqa: E402
+
+SUPPORTED_EXTENSIONS = {".md", ".mdx", ".markdown", ".txt"}
+
+STOPWORDS = {
+ "a",
+ "about",
+ "above",
+ "after",
+ "again",
+ "against",
+ "all",
+ "also",
+ "am",
+ "an",
+ "and",
+ "any",
+ "are",
+ "as",
+ "at",
+ "be",
+ "because",
+ "been",
+ "before",
+ "being",
+ "below",
+ "between",
+ "both",
+ "but",
+ "by",
+ "can",
+ "could",
+ "did",
+ "do",
+ "does",
+ "doing",
+ "down",
+ "during",
+ "each",
+ "few",
+ "for",
+ "from",
+ "further",
+ "had",
+ "has",
+ "have",
+ "having",
+ "he",
+ "her",
+ "here",
+ "hers",
+ "him",
+ "his",
+ "how",
+ "i",
+ "if",
+ "in",
+ "into",
+ "is",
+ "it",
+ "its",
+ "itself",
+ "just",
+ "me",
+ "more",
+ "most",
+ "my",
+ "no",
+ "nor",
+ "not",
+ "now",
+ "of",
+ "off",
+ "on",
+ "once",
+ "only",
+ "or",
+ "other",
+ "our",
+ "ours",
+ "out",
+ "over",
+ "own",
+ "same",
+ "she",
+ "should",
+ "so",
+ "some",
+ "such",
+ "than",
+ "that",
+ "the",
+ "their",
+ "theirs",
+ "them",
+ "then",
+ "there",
+ "these",
+ "they",
+ "this",
+ "those",
+ "through",
+ "to",
+ "too",
+ "under",
+ "until",
+ "up",
+ "very",
+ "was",
+ "we",
+ "were",
+ "what",
+ "when",
+ "where",
+ "which",
+ "while",
+ "who",
+ "why",
+ "will",
+ "with",
+ "would",
+ "you",
+ "your",
+ "yours",
+}
+
+FIRST_PERSON_TERMS = {
+ "i",
+ "i'd",
+ "i'll",
+ "i'm",
+ "i've",
+ "me",
+ "mine",
+ "my",
+ "myself",
+ "our",
+ "ours",
+ "ourselves",
+ "us",
+ "we",
+ "we'd",
+ "we'll",
+ "we're",
+ "we've",
+}
+
+
+def collect_post_paths(inputs: Sequence[str | Path]) -> tuple[list[Path], list[str]]:
+ """Collect blog post files from files or directories in stable order."""
+ warnings: list[str] = []
+ found: list[Path] = []
+
+ for item in inputs:
+ path = Path(item)
+ if path.is_dir():
+ found.extend(
+ p
+ for p in sorted(path.rglob("*"), key=lambda p: str(p))
+ if p.is_file() and p.suffix.lower() in SUPPORTED_EXTENSIONS
+ )
+ elif path.is_file():
+ if path.suffix.lower() in SUPPORTED_EXTENSIONS:
+ found.append(path)
+ else:
+ warnings.append(f"Skipped unsupported file type: {path}")
+ else:
+ warnings.append(f"Skipped missing path: {path}")
+
+ unique: dict[str, Path] = {}
+ for path in found:
+ key = str(path.resolve())
+ unique.setdefault(key, path)
+
+ return sorted(unique.values(), key=lambda p: str(p)), warnings
+
+
+def strip_to_plain_text(content: str) -> str:
+ """Normalize markdown or MDX content into plain text."""
+ body = analyze_blog.strip_frontmatter(content)
+ body = re.sub(r"```.*?```", "", body, flags=re.DOTALL)
+ body = re.sub(r"<[^>]+>", "", body)
+ body = re.sub(r"!\[.*?\]\(.*?\)", "", body)
+ body = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", body)
+ body = re.sub(r"^#{1,6}\s+", "", body, flags=re.MULTILINE)
+ body = re.sub(r"\n{3,}", "\n\n", body)
+ return body.strip()
+
+
+def sentence_lengths(text: str) -> list[int]:
+ """Return sentence lengths using the same minimum as analyze_blog."""
+ sentences = re.split(r"(?<=[.!?])\s+", text)
+ return [len(sentence.split()) for sentence in sentences if len(sentence.split()) > 2]
+
+
+def word_tokens(text: str) -> list[str]:
+ """Return normalized word tokens for corpus-level rates."""
+ return re.findall(r"[a-z0-9]+(?:'[a-z]+)?", text.lower())
+
+
+def content_tokens(text: str) -> list[str]:
+ """Return non-stopword content tokens for signature phrase extraction."""
+ return [
+ token
+ for token in word_tokens(text)
+ if token not in STOPWORDS and len(token) > 2
+ ]
+
+
+def paragraph_word_counts(content: str) -> list[int]:
+ """Return paragraph word counts using the same broad cleanup as analyze_blog."""
+ cleaned = re.sub(r"```.*?```", "", content, flags=re.DOTALL)
+ cleaned = re.sub(r"<[^>]+>", "", cleaned)
+ cleaned = re.sub(r"^#{1,6}\s+.*$", "", cleaned, flags=re.MULTILINE)
+ cleaned = re.sub(r"!\[.*?\]\(.*?\)", "", cleaned)
+ paragraphs = [p.strip() for p in re.split(r"\n\s*\n", cleaned) if p.strip()]
+ return [len(p.split()) for p in paragraphs if len(p.split()) >= 5]
+
+
+def _round(value: float, digits: int = 2) -> float:
+ """Round floats consistently and avoid negative zero."""
+ rounded = round(value, digits)
+ return 0.0 if rounded == -0.0 else rounded
+
+
+def _pct(part: int | float, whole: int | float) -> float:
+ """Return a rounded percentage."""
+ return _round((part / whole * 100) if whole else 0.0, 2)
+
+
+def _rate_per_1k(count: int | float, words: int) -> float:
+ """Return a rounded per-1,000-word rate."""
+ return _round((count / words * 1000) if words else 0.0, 2)
+
+
+def _distribution(values: list[int]) -> dict[str, dict[str, float | int]]:
+ """Bucket paragraph lengths into readable ranges."""
+ bins = {
+ "under_40": lambda value: value < 40,
+ "40_to_80": lambda value: 40 <= value <= 80,
+ "81_to_150": lambda value: 81 <= value <= 150,
+ "151_to_200": lambda value: 151 <= value <= 200,
+ "over_200": lambda value: value > 200,
+ }
+ total = len(values)
+ return {
+ name: {
+ "count": count,
+ "pct": _pct(count, total),
+ }
+ for name, predicate in bins.items()
+ for count in [sum(1 for value in values if predicate(value))]
+ }
+
+
+def signature_phrases(tokens: list[str], limit: int = 12) -> list[dict[str, Any]]:
+ """Return top 2-gram and 3-gram content phrases."""
+ counts: Counter[tuple[str, ...]] = Counter()
+ for size in (2, 3):
+ for index in range(0, len(tokens) - size + 1):
+ ngram = tuple(tokens[index:index + size])
+ if len(set(ngram)) == 1:
+ continue
+ counts[ngram] += 1
+
+ ranked = sorted(counts.items(), key=lambda item: (-item[1], len(item[0]), " ".join(item[0])))
+ return [
+ {
+ "phrase": " ".join(ngram),
+ "count": count,
+ "ngram_size": len(ngram),
+ }
+ for ngram, count in ranked[:limit]
+ ]
+
+
+def derive_tone_descriptors(metrics: dict[str, Any]) -> list[str]:
+ """Infer compact tone labels from aggregate metrics."""
+ descriptors: list[str] = []
+ sentence_mean = metrics["sentence_length"]["mean_words"]
+ variance = metrics["sentence_length"]["burstiness_variance"]
+ transition_pct = metrics["rates"]["transition_sentence_pct"]
+ passive_pct = metrics["rates"]["passive_sentence_pct"]
+ first_person = metrics["rates"]["first_person_per_1k_words"]
+ question_ratio = metrics["headings"]["question_ratio"]
+ ai_per_1k = metrics["rates"]["ai_trigger_words_per_1k"]
+ flesch = metrics["readability"]["flesch_reading_ease_mean"]
+
+ if sentence_mean <= 15:
+ descriptors.append("punchy")
+ elif sentence_mean >= 22:
+ descriptors.append("expansive")
+ else:
+ descriptors.append("balanced cadence")
+
+ if variance >= 80:
+ descriptors.append("varied rhythm")
+ elif variance <= 25:
+ descriptors.append("steady rhythm")
+
+ if passive_pct <= 8:
+ descriptors.append("active voice")
+ elif passive_pct >= 18:
+ descriptors.append("formal construction")
+
+ if transition_pct >= 25:
+ descriptors.append("highly signposted")
+ elif transition_pct <= 8:
+ descriptors.append("direct")
+
+ if first_person >= 8:
+ descriptors.append("personal")
+ elif first_person <= 1:
+ descriptors.append("institutional")
+
+ if question_ratio >= 0.3:
+ descriptors.append("question-led")
+
+ if ai_per_1k <= 2:
+ descriptors.append("plainspoken")
+ elif ai_per_1k >= 8:
+ descriptors.append("buzzword-prone")
+
+ if flesch >= 60:
+ descriptors.append("accessible")
+ elif flesch <= 45:
+ descriptors.append("technical")
+
+ unique: list[str] = []
+ for descriptor in descriptors:
+ if descriptor not in unique:
+ unique.append(descriptor)
+ return unique[:7]
+
+
+def analyze_sample(path: Path) -> dict[str, Any]:
+ """Analyze one sample post with the shared analyzer functions."""
+ content = path.read_text(encoding="utf-8")
+ body = analyze_blog.strip_frontmatter(content)
+ plain_text = strip_to_plain_text(content)
+
+ sentences = analyze_blog.analyze_sentences(plain_text)
+ readability = analyze_blog.analyze_readability(plain_text)
+ transitions = analyze_blog.analyze_transition_words(plain_text)
+ passive = analyze_blog.analyze_passive_voice(plain_text)
+ ai_triggers = analyze_blog.analyze_ai_trigger_words(plain_text)
+ paragraphs = analyze_blog.analyze_paragraphs(body)
+ originality = analyze_blog.analyze_originality(body)
+ headings = analyze_blog.analyze_headings(body)
+
+ tokens = word_tokens(plain_text)
+ first_person_count = sum(1 for token in tokens if token in FIRST_PERSON_TERMS)
+ heading_question_count = sum(1 for heading in headings["headings"] if heading["is_question"])
+
+ return {
+ "file": str(path),
+ "word_count": len(tokens),
+ "word_tokens": tokens,
+ "sentence_lengths": sentence_lengths(plain_text),
+ "paragraph_lengths": paragraph_word_counts(body),
+ "content_tokens": content_tokens(plain_text),
+ "first_person_count": first_person_count,
+ "heading_question_count": heading_question_count,
+ "headings_total": headings["total"],
+ "analysis": {
+ "sentences": sentences,
+ "readability": readability,
+ "transition_words": transitions,
+ "passive_voice": passive,
+ "ai_trigger_words": ai_triggers,
+ "paragraphs": paragraphs,
+ "originality": originality,
+ "headings": headings,
+ },
+ }
+
+
+def learn_style(inputs: Sequence[str | Path], min_posts: int = 5) -> dict[str, Any]:
+ """Learn an aggregate voice profile from files or directories."""
+ paths, warnings = collect_post_paths(inputs)
+ if len(paths) < min_posts:
+ warnings.append(
+ f"Only {len(paths)} sample post(s) supplied. Recommended minimum is {min_posts}."
+ )
+
+ samples = [analyze_sample(path) for path in paths]
+ sentence_values = [value for sample in samples for value in sample["sentence_lengths"]]
+ paragraph_values = [value for sample in samples for value in sample["paragraph_lengths"]]
+ all_word_tokens = [token for sample in samples for token in sample["word_tokens"]]
+ all_tokens = [token for sample in samples for token in sample["content_tokens"]]
+ total_word_count = sum(sample["word_count"] for sample in samples)
+
+ transition_count = sum(s["analysis"]["transition_words"]["transition_count"] for s in samples)
+ transition_sentences = sum(s["analysis"]["transition_words"]["total_sentences"] for s in samples)
+ passive_count = sum(s["analysis"]["passive_voice"]["passive_count"] for s in samples)
+ passive_sentences = sum(s["analysis"]["passive_voice"]["total_sentences"] for s in samples)
+ ai_trigger_count = sum(s["analysis"]["ai_trigger_words"]["trigger_count"] for s in samples)
+ first_person_count = sum(s["first_person_count"] for s in samples)
+ originality_markers = sum(s["analysis"]["originality"]["marker_count"] for s in samples)
+ first_person_experience = sum(s["analysis"]["originality"]["first_person_count"] for s in samples)
+ heading_questions = sum(s["heading_question_count"] for s in samples)
+ heading_total = sum(s["headings_total"] for s in samples)
+ h2_questions = sum(s["analysis"]["headings"]["h2_question_count"] for s in samples)
+ h2_total = sum(s["analysis"]["headings"]["h2_count"] for s in samples)
+ readability_values = [
+ s["analysis"]["readability"].get("flesch_reading_ease", 0)
+ for s in samples
+ if s["analysis"]["readability"].get("flesch_reading_ease") is not None
+ ]
+
+ sentence_mean = statistics.mean(sentence_values) if sentence_values else 0.0
+ sentence_median = statistics.median(sentence_values) if sentence_values else 0.0
+ sentence_variance = statistics.pvariance(sentence_values) if len(sentence_values) > 1 else 0.0
+ paragraph_mean = statistics.mean(paragraph_values) if paragraph_values else 0.0
+ paragraph_median = statistics.median(paragraph_values) if paragraph_values else 0.0
+ flesch_mean = statistics.mean(readability_values) if readability_values else 0.0
+ unique_words = len(set(all_word_tokens))
+ vocabulary_ttr = unique_words / total_word_count if total_word_count else 0.0
+
+ profile: dict[str, Any] = {
+ "profile_version": "1.0",
+ "sample": {
+ "post_count": len(samples),
+ "min_recommended": min_posts,
+ "files": [str(path) for path in paths],
+ "warnings": warnings,
+ },
+ "sentence_length": {
+ "mean_words": _round(sentence_mean),
+ "median_words": _round(float(sentence_median)),
+ "burstiness_variance": _round(sentence_variance),
+ "std_dev_words": _round(sentence_variance ** 0.5),
+ "sentence_count": len(sentence_values),
+ },
+ "vocabulary": {
+ "ttr": _round(vocabulary_ttr, 3),
+ "total_words": total_word_count,
+ "unique_words": unique_words,
+ },
+ "readability": {
+ "flesch_reading_ease_mean": _round(flesch_mean),
+ },
+ "rates": {
+ "transition_sentence_pct": _pct(transition_count, transition_sentences),
+ "passive_sentence_pct": _pct(passive_count, passive_sentences),
+ "ai_trigger_words_per_1k": _rate_per_1k(ai_trigger_count, total_word_count),
+ "first_person_per_1k_words": _rate_per_1k(first_person_count, total_word_count),
+ },
+ "paragraph_lengths": {
+ "mean_words": _round(paragraph_mean),
+ "median_words": _round(float(paragraph_median)),
+ "paragraph_count": len(paragraph_values),
+ "distribution": _distribution(paragraph_values),
+ },
+ "first_person": {
+ "pronoun_count": first_person_count,
+ "experience_marker_count": first_person_experience,
+ "originality_marker_count": originality_markers,
+ },
+ "headings": {
+ "question_count": heading_questions,
+ "total": heading_total,
+ "question_ratio": _round((heading_questions / heading_total) if heading_total else 0.0, 3),
+ "h2_question_ratio": _round((h2_questions / h2_total) if h2_total else 0.0, 3),
+ },
+ "signature_phrases": signature_phrases(all_tokens),
+ "per_post": [
+ {
+ "file": sample["file"],
+ "word_count": sample["word_count"],
+ "sentence_mean_words": sample["analysis"]["sentences"]["avg_length"],
+ "transition_sentence_pct": sample["analysis"]["transition_words"]["transition_pct"],
+ "passive_sentence_pct": sample["analysis"]["passive_voice"]["passive_pct"],
+ "ai_trigger_words_per_1k": sample["analysis"]["ai_trigger_words"]["per_1k"],
+ "h2_question_ratio": sample["analysis"]["headings"]["h2_question_ratio"],
+ }
+ for sample in samples
+ ],
+ }
+ profile["tone_descriptors"] = derive_tone_descriptors(profile)
+ return profile
+
+
+def render_json(profile: dict[str, Any]) -> str:
+ """Render a deterministic JSON profile."""
+ return json.dumps(profile, indent=2, sort_keys=True) + "\n"
+
+
+def render_markdown(profile: dict[str, Any]) -> str:
+ """Render a VOICE.md-ready markdown profile block."""
+ sample = profile["sample"]
+ sentence = profile["sentence_length"]
+ rates = profile["rates"]
+ paragraphs = profile["paragraph_lengths"]
+ headings = profile["headings"]
+ vocabulary = profile["vocabulary"]
+ phrases = profile["signature_phrases"]
+ tone = profile["tone_descriptors"]
+
+ phrase_lines = [
+ f"- `{item['phrase']}`: {item['count']} occurrence(s)"
+ for item in phrases
+ ] or ["- No repeated content n-grams found"]
+
+ tone_line = ", ".join(tone) if tone else "No strong tone descriptors detected"
+ warnings = sample.get("warnings", [])
+ warning_lines = [f"- {warning}" for warning in warnings] or ["- None"]
+
+ distribution_lines = [
+ f"- {name}: {bucket['count']} paragraph(s), {bucket['pct']}%"
+ for name, bucket in paragraphs["distribution"].items()
+ ]
+
+ return "\n".join([
+ "<!-- VOICE_PROFILE_START -->",
+ "## Learned Voice Profile",
+ "",
+ f"Sample: {sample['post_count']} post(s).",
+ "",
+ "### Style Baselines",
+ "",
+ f"- Sentence length: mean {sentence['mean_words']} words, median {sentence['median_words']} words.",
+ f"- Sentence burstiness: variance {sentence['burstiness_variance']}, standard deviation {sentence['std_dev_words']} words.",
+ f"- Vocabulary richness: TTR {vocabulary['ttr']} across {vocabulary['total_words']} words.",
+ f"- Transition rate: {rates['transition_sentence_pct']}% of sentences.",
+ f"- Passive voice rate: {rates['passive_sentence_pct']}% of sentences.",
+ f"- AI trigger baseline: {rates['ai_trigger_words_per_1k']} words per 1,000.",
+ f"- First-person rate: {rates['first_person_per_1k_words']} mentions per 1,000 words.",
+ f"- Heading question ratio: {headings['question_ratio']}.",
+ "",
+ "### Paragraph Distribution",
+ "",
+ *distribution_lines,
+ "",
+ "### Tone Descriptors",
+ "",
+ f"- {tone_line}",
+ "",
+ "### Signature Phrases",
+ "",
+ *phrase_lines,
+ "",
+ "### Warnings",
+ "",
+ *warning_lines,
+ "<!-- VOICE_PROFILE_END -->",
+ "",
+ ])
+
+
+def build_parser() -> argparse.ArgumentParser:
+ """Build the command line parser."""
+ parser = argparse.ArgumentParser(description="Learn a blog author voice profile.")
+ parser.add_argument("paths", nargs="+", help="Blog post files or directories to analyze")
+ parser.add_argument("--min", type=int, default=5, help="Minimum sample count before warning")
+ parser.add_argument("--output", help="Write the rendered profile to this path")
+ parser.add_argument("--format", choices=("json", "markdown"), default="json", help="Output format")
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ """Run the style learning CLI."""
+ parser = build_parser()
+ args = parser.parse_args(argv)
+
+ profile = learn_style(args.paths, min_posts=args.min)
+ rendered = render_markdown(profile) if args.format == "markdown" else render_json(profile)
+
+ for warning in profile["sample"].get("warnings", []):
+ print(f"Warning: {warning}", file=sys.stderr)
+
+ if args.output:
+ Path(args.output).write_text(rendered, encoding="utf-8")
+ else:
+ print(rendered, end="")
+
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/blog-decay/SKILL.md b/skills/blog-decay/SKILL.md
new file mode 100644
index 0000000..7c93ffc
--- /dev/null
+++ b/skills/blog-decay/SKILL.md
@@ -0,0 +1,81 @@
+---
+name: blog-decay
+description: Detect content decay from Google Search Console exports by comparing current and previous page performance, flagging quarter-over-quarter traffic drops, dropped pages, and refresh, consolidate, prune, or query-shift actions. Use when the user says "/blog decay", "content decay", "traffic drop", "QoQ decline", "GSC decay", or "refresh declining posts".
+argument-hint: "<current-gsc.json> <previous-gsc.json> [threshold] [metric]"
+user-invokable: true
+license: MIT
+---
+
+# Blog Decay
+
+Use `/blog decay` to find pages whose Google Search Console performance has
+declined quarter-over-quarter. The command compares a current-period export
+against a previous-period export, flags pages with a 20% or larger decline by
+default, and recommends the next content action.
+
+## Default Offline Workflow
+
+Run the local analyzer against two GSC page exports:
+
+```bash
+python3 scripts/content_decay.py current.json previous.json
+```
+
+Useful options:
+
+```bash
+python3 scripts/content_decay.py current.json previous.json --threshold 0.30
+python3 scripts/content_decay.py current.json previous.json --metric impressions
+python3 scripts/content_decay.py current.json previous.json --format markdown --output decay-report.md
+```
+
+The script accepts JSON lists of page rows with `page` or `url`, `clicks`, and
+`impressions`. It also accepts the object shape returned by `blog-google` when
+the rows are under a top-level `rows` key.
+
+## Optional Live GSC Export
+
+For live data, use `/blog google gsc` or the underlying `blog-google` command
+to create each period export, then run the offline analyzer:
+
+```bash
+python3 skills/blog-google/scripts/run.py gsc_query --property sc-domain:example.com --dimensions page --start-date YYYY-MM-DD --end-date YYYY-MM-DD --json > gsc-current.json
+python3 skills/blog-google/scripts/run.py gsc_query --property sc-domain:example.com --dimensions page --start-date YYYY-MM-DD --end-date YYYY-MM-DD --json > gsc-previous.json
+python3 scripts/content_decay.py gsc-current.json gsc-previous.json --format markdown
+```
+
+Use adjacent periods of similar length. For quarter-over-quarter checks, compare
+the last completed quarter with the quarter before it.
+
+## Decay Model
+
+The default metric is `clicks`. Use `--metric impressions` when discovery loss
+matters more than traffic loss.
+
+Severity:
+
+| Decline | Severity |
+| --- | --- |
+| 20% to 39.9% | warning |
+| 40% to 59.9% | high |
+| 60% or more | critical |
+
+Dropped pages are previous-period pages missing from the current export. They
+are surfaced as full decline items with `dropped_out: true`.
+
+## Recommended Actions
+
+Use the action as the first triage path:
+
+| Action | Use when |
+| --- | --- |
+| refresh/update content | The page still has demand and likely needs freshness, title, internal link, or section updates. |
+| investigate query shift | Clicks fell while impressions held up, suggesting CTR, rank, SERP, or query mix changes. |
+| consolidate/redirect | The page dropped out or the loss is severe enough that merging into a stronger URL may recover value faster. |
+| prune | The page had very low prior demand and may not justify rewrite effort. |
+
+## Cross-references
+
+Use `blog-google` to collect Search Console exports when live credentials are
+available. Use `blog-rewrite` after decay detection when the recommended action
+is refresh/update content and the page is worth improving.
diff --git a/skills/blog-style/SKILL.md b/skills/blog-style/SKILL.md
new file mode 100644
index 0000000..5c75266
--- /dev/null
+++ b/skills/blog-style/SKILL.md
@@ -0,0 +1,88 @@
+---
+name: blog-style
+description: Learn author writing style from 5 to 10 existing blog posts and generate a voice profile for /blog style learn, VOICE.md, blog-persona, and blog-write when users ask to infer tone, analyze author voice, learn style, or build a writing baseline.
+argument-hint: "learn <paths>"
+user-invokable: true
+license: MIT
+---
+
+# Blog Style - Writing Style Learning
+
+Learn an author voice profile from existing posts, then use it as a baseline for
+VOICE.md, blog-persona, and blog-write. The profile captures measurable style
+signals so future drafts can preserve the author's cadence, vocabulary, and
+tone.
+
+## Commands
+
+| Command | Purpose |
+|---------|---------|
+| `/blog style learn <paths>` | Analyze sample posts and generate a voice profile |
+
+## Learn Workflow
+
+Use 5 to 10 representative posts from the same author, brand, or editorial
+voice. Accept individual markdown files, MDX files, text files, or a directory
+containing posts.
+
+Run the local learner:
+
+```bash
+python3 scripts/style_learn.py <paths> --format markdown
+```
+
+For machine-readable output:
+
+```bash
+python3 scripts/style_learn.py <paths> --format json --output voice-profile.json
+```
+
+For a VOICE.md-ready block:
+
+```bash
+python3 scripts/style_learn.py <paths> --format markdown --output VOICE.md
+```
+
+If fewer than the requested minimum sample count is supplied, warn and continue.
+The default minimum is 5 posts.
+
+## Profile Fields
+
+The learner aggregates the existing blog analyzer across each sample post:
+
+- Sentence length mean and median
+- Sentence length burstiness as corpus variance
+- Vocabulary richness as type-token ratio
+- Transition-word sentence rate
+- Passive-voice sentence rate
+- AI trigger words per 1,000 words as a baseline to preserve or avoid
+- Paragraph-length distribution
+- First-person usage rate
+- Heading-as-question ratio
+- Signature phrases from top 2-gram and 3-gram content phrases with stopwords removed
+- Tone descriptors derived from the measured metrics
+
+## Consuming the Profile
+
+Drop the markdown block into project `VOICE.md` when the goal is durable
+project context. Blog-write can use the style baselines as drafting targets:
+
+- Keep average sentence length near the learned mean.
+- Match the learned sentence variation unless the user asks for a tighter or
+ looser cadence.
+- Preserve signature phrases only when they fit the topic naturally.
+- Treat the AI trigger baseline as a ceiling when the author rarely uses those
+ terms.
+- Use the first-person and heading-question rates to decide how personal and
+ question-led the draft should feel.
+
+Feed the JSON output into blog-persona when a structured persona should be
+created or updated. Map the learned values to persona sentence length, passive
+voice, readability, vocabulary, and tone settings.
+
+## Error Handling
+
+- **Too few posts**: Continue and warn that the profile may be less stable.
+- **Missing paths**: Skip missing paths and include a warning in the profile.
+- **Unsupported files**: Skip unsupported file types and include a warning.
+- **Empty samples**: Return zeroed metrics rather than crashing.
diff --git a/tests/fixtures/blog_fail.md b/tests/fixtures/blog_fail.md
new file mode 100644
index 0000000..3dd9565
--- /dev/null
+++ b/tests/fixtures/blog_fail.md
@@ -0,0 +1,9 @@
+---
+title: Thin Post
+description: A short note that has frontmatter but does not give readers enough useful evidence.
+date: 2026-06-01
+---
+
+# Thin Post
+
+This note says the topic matters. It gives no examples, no links, no author proof, no source citations, and no useful structure for a reader to follow.
diff --git a/tests/fixtures/blog_pass.md b/tests/fixtures/blog_pass.md
new file mode 100644
index 0000000..779cd63
--- /dev/null
+++ b/tests/fixtures/blog_pass.md
@@ -0,0 +1,74 @@
+---
+title: Practical Blog Quality Gate Playbook for Teams
+description: Use this 2026 checklist to raise blog quality with structured sections, source links, author proof, review steps, and quality metrics before every post ships.
+author: Maya Chen
+date: 2026-06-01
+type: news
+keyword: blog quality gate
+slug: blog-quality-gate-playbook
+image: /images/blog-quality-gate.webp
+---
+
+# Practical Blog Quality Gate Playbook for Teams
+
+## What changed for editorial teams?
+
+In June 2026, our team measured the last fifty publishing reviews from a small editorial desk and found that posts with a written quality gate reached approval in 31% fewer review cycles. [ORIGINAL DATA] The pattern was simple: editors made faster decisions when each draft had a score, source list, author note, and clear next action. For example, a draft that linked to the [/blog/editorial-review](/blog/editorial-review) checklist moved from copy edit to approval on the first pass because the reviewer could see the evidence trail. What happens when a draft misses the gate? The team pauses publication, fixes the exact gaps, and reruns the same review so the standard stays consistent.
+
+## Why does a score gate improve trust?
+
+**Quality gate** is a publishing rule that checks whether a post is useful, sourced, structured, and ready for a real reader before it ships. We analyzed review notes and saw the biggest gains when the rule measured concrete evidence instead of taste. The draft needed a named author, a current date, links to sources such as [Pew Research Center](https://www.pewresearch.org/internet/2025/01/15/news-and-information-trust/), and internal paths for readers who wanted more context. Therefore, a score gate works because it turns vague feedback into a visible standard. Is the draft useful without a reviewer guessing? If the answer is unclear, the post needs more reporting before release.
+
+## What should teams check before publishing?
+
+**Review packet** is the set of signals an editor can inspect in one sitting: title, description, author, date, citations, headings, links, schema, and mobile readability. Our team tested the packet on launch drafts and tracked which fields caused rework. For instance, posts missing source citations took the longest to fix because writers had to reopen research notes and verify claims against references such as [U.S. Census data](https://www.census.gov/programs-surveys/acs) and [Bureau of Labor Statistics releases](https://www.bls.gov/news.release/). Use the [/blog/style-guide](/blog/style-guide), the [/about](/about) page, and the [/contact](/contact) path to keep trust signals visible.
+
+| Check | Passing signal | Owner |
+| --- | --- | --- |
+| Evidence | At least two credible external sources | Writer |
+| Structure | Three or more useful sections | Editor |
+| Trust | Named author and contact path | Publisher |
+
+- Confirm the title matches search intent.
+- Confirm the description explains the reader benefit.
+- Confirm each statistic has a nearby source.
+- Confirm internal links point to helpful next steps.
+
+## How do citations and structure help AI answers?
+
+**Citation-ready passage** means a short section that can stand alone when a search assistant quotes it. We conducted a small comparison between drafts with long blocks and drafts with 120 to 180 word passages. The shorter passages were easier to summarize, and reviewers found fewer missing context problems. The bottom line: a post needs source-backed claims, direct answers, and stable entity names. Helpful source links include [Reuters Institute research](https://reutersinstitute.politics.ox.ac.uk/digital-news-report/2025), [NIH public guidance](https://www.nih.gov/about-nih), and [ACM publishing guidance](https://www.acm.org/publications). However, links alone do not create quality. The writer still has to explain what changed, who is affected, and how the reader should act.
+
+![Editorial workflow dashboard](/images/editorial-dashboard.webp)
+
+## FAQ
+
+### How often should teams rerun the gate?
+
+Rerun the gate before every commit that changes a post and again before publication. In our experience, the second pass catches stale dates, removed citations, and headings that changed during copy edit. A weekly audit also helps teams spot patterns, such as repeated missing author fields or thin sections.
+
+### What score should trigger a rewrite?
+
+A score below 70 should block the commit until the post has stronger evidence, clearer structure, and better trust signals. Scores from 70 to 79 are publishable only when the editor agrees that the remaining issues are low risk.
+
+<script type="application/ld+json">
+[
+ {
+ "@context": "https://schema.org",
+ "@type": "BlogPosting",
+ "headline": "Practical Blog Quality Gate Playbook for Teams",
+ "author": {
+ "@type": "Person",
+ "name": "Maya Chen"
+ }
+ },
+ {
+ "@context": "https://schema.org",
+ "@type": "Person",
+ "name": "Maya Chen"
+ },
+ {
+ "@context": "https://schema.org",
+ "@type": "FAQPage"
+ }
+]
+</script>
diff --git a/tests/fixtures/gsc_current.json b/tests/fixtures/gsc_current.json
new file mode 100644
index 0000000..6b59ed3
--- /dev/null
+++ b/tests/fixtures/gsc_current.json
@@ -0,0 +1,22 @@
+[
+ {
+ "page": "https://example.com/stable",
+ "clicks": 95,
+ "impressions": 980
+ },
+ {
+ "page": "https://example.com/refresh-me",
+ "clicks": 60,
+ "impressions": 600
+ },
+ {
+ "page": "https://example.com/query-shift",
+ "clicks": 20,
+ "impressions": 920
+ },
+ {
+ "page": "https://example.com/prune-me",
+ "clicks": 0,
+ "impressions": 10
+ }
+]
diff --git a/tests/fixtures/gsc_previous.json b/tests/fixtures/gsc_previous.json
new file mode 100644
index 0000000..3d75aff
--- /dev/null
+++ b/tests/fixtures/gsc_previous.json
@@ -0,0 +1,27 @@
+[
+ {
+ "page": "https://example.com/stable",
+ "clicks": 100,
+ "impressions": 1000
+ },
+ {
+ "page": "https://example.com/refresh-me",
+ "clicks": 100,
+ "impressions": 1100
+ },
+ {
+ "page": "https://example.com/query-shift",
+ "clicks": 50,
+ "impressions": 900
+ },
+ {
+ "url": "https://example.com/drop-out",
+ "clicks": 30,
+ "impressions": 400
+ },
+ {
+ "page": "https://example.com/prune-me",
+ "clicks": 2,
+ "impressions": 30
+ }
+]
diff --git a/tests/test_ai_citation_score.py b/tests/test_ai_citation_score.py
new file mode 100644
index 0000000..ecc3b55
--- /dev/null
+++ b/tests/test_ai_citation_score.py
@@ -0,0 +1,101 @@
+"""Tests for the AI citation probability scorer."""
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent / "scripts"))
+
+import ai_citation_score
+
+
+FRONTMATTER_BOUNDARY = "-" * 3
+
+
+HIGH_QUALITY_POST = f"""{FRONTMATTER_BOUNDARY}
+title: AI Citation Optimization Benchmarks for 2026
+description: Evidence-backed benchmarks for increasing AI citation probability across Google, Perplexity, and ChatGPT.
+author: Jane Doe
+date: 2026-01-15
+lastUpdated: 2026-06-20
+{FRONTMATTER_BOUNDARY}
+
+# AI Citation Optimization Benchmarks for 2026
+
+TL;DR: AI citation optimization works best when a post gives a direct answer, cites authoritative sources, defines entities, and keeps data fresh.
+
+## What raises AI citation probability?
+
+AI citation probability rises when a page gives a complete answer in one extractable passage. **AI citation probability** is the estimated chance that an answer engine will quote or reference a page for a matching query. In our testing, answer-first sections worked best when the first paragraph named the entity, gave the direct answer, added a current statistic, and linked to the source. A 2026 review found that 68% of cited passages included a direct definition and a source link [NIH research](https://nih.gov/example-ai-citations). A second benchmark found 54% better retrieval when headings used questions [Stanford study](https://stanford.edu/example-study). The strongest posts also used short paragraphs, one idea per section, and a summary list that a model can lift without extra context. This paragraph is intentionally self-contained so an answer engine can cite it without reading the rest of the article.
+
+## How should sources be added?
+
+Every statistic should sit beside its source. A 2026 newsroom sample found 41% more citations when articles linked to primary data [Reuters analysis](https://reuters.com/example-ai-study). A public health review found 33% fewer hallucinated summaries when sources were named near the claim [CDC guidance](https://cdc.gov/example-guidance).
+
+- Define the core entity.
+- Put the direct answer first.
+- Refresh the date when facts change.
+
+## FAQ
+
+### What is a citable passage?
+
+A citable passage is a short, self-contained answer that names the topic, explains the claim, and includes enough context for reuse.
+
+<script type="application/ld+json">
+{{
+ "@context": "https://schema.org",
+ "@type": "BlogPosting",
+ "headline": "AI Citation Optimization Benchmarks for 2026",
+ "author": {{"@type": "Person", "name": "Jane Doe"}},
+ "dateModified": "2026-06-20"
+}}
+</script>
+"""
+
+
+THIN_POST = """# Short Update
+
+This post says AI citations matter. It has no source links, no schema, and no clear answer structure.
+"""
+
+
+def _write_post(tmp_path: Path, name: str, content: str) -> Path:
+ path = tmp_path / name
+ path.write_text(content, encoding="utf-8")
+ return path
+
+
+def test_scores_have_expected_shape(tmp_path):
+ post = _write_post(tmp_path, "high.md", HIGH_QUALITY_POST)
+ result = ai_citation_score.score_file(post)
+
+ assert isinstance(result["overall"], int)
+ assert 0 <= result["overall"] <= 100
+ assert set(result["engines"]) == {"ai_overview", "perplexity", "chatgpt"}
+ assert isinstance(result["factors"], dict)
+ assert isinstance(result["recommendations"], list)
+
+ for engine_result in result["engines"].values():
+ assert isinstance(engine_result["score"], int)
+ assert 0 <= engine_result["score"] <= 100
+
+
+def test_scoring_is_deterministic(tmp_path):
+ post = _write_post(tmp_path, "high.md", HIGH_QUALITY_POST)
+
+ first = ai_citation_score.score_file(post)
+ second = ai_citation_score.score_file(post)
+
+ assert first == second
+
+
+def test_high_quality_fixture_scores_higher_than_thin_fixture(tmp_path):
+ high_post = _write_post(tmp_path, "high.md", HIGH_QUALITY_POST)
+ thin_post = _write_post(tmp_path, "thin.md", THIN_POST)
+
+ high_score = ai_citation_score.score_file(high_post)["overall"]
+ thin_score = ai_citation_score.score_file(thin_post)["overall"]
+
+ assert high_score > thin_score
diff --git a/tests/test_content_decay.py b/tests/test_content_decay.py
new file mode 100644
index 0000000..f976ec7
--- /dev/null
+++ b/tests/test_content_decay.py
@@ -0,0 +1,141 @@
+"""Tests for the content decay detection script."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent.parent / "scripts"))
+
+import content_decay
+
+
+ROOT = Path(__file__).resolve().parent.parent
+FIXTURES = ROOT / "tests" / "fixtures"
+SCRIPT = ROOT / "scripts" / "content_decay.py"
+
+
+def _fixture(name: str) -> list[dict]:
+ return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
+
+
+def test_analyze_decay_flags_threshold_dropouts_and_actions():
+ report = content_decay.analyze_decay(
+ _fixture("gsc_current.json"),
+ _fixture("gsc_previous.json"),
+ )
+
+ assert report["summary"]["flagged_pages"] == 4
+ assert report["summary"]["dropped_out_pages"] == 1
+
+ by_page = {row["page"]: row for row in report["decays"]}
+ assert "https://example.com/stable" not in by_page
+
+ refresh = by_page["https://example.com/refresh-me"]
+ assert refresh["severity"] == "high"
+ assert refresh["decline_percent"] == 40.0
+ assert refresh["recommended_action"] == "refresh/update content"
+
+ query_shift = by_page["https://example.com/query-shift"]
+ assert query_shift["severity"] == "critical"
+ assert query_shift["recommended_action"] == "investigate query shift"
+
+ drop_out = by_page["https://example.com/drop-out"]
+ assert drop_out["dropped_out"] is True
+ assert drop_out["recommended_action"] == "consolidate/redirect"
+
+ prune = by_page["https://example.com/prune-me"]
+ assert prune["recommended_action"] == "prune"
+
+
+def test_analyze_decay_sorts_by_severity_then_decline():
+ report = content_decay.analyze_decay(
+ _fixture("gsc_current.json"),
+ _fixture("gsc_previous.json"),
+ )
+
+ severities = [row["severity"] for row in report["decays"]]
+ assert severities[:3] == ["critical", "critical", "critical"]
+ assert severities[-1] == "high"
+ assert report["decays"][0]["decline"] >= report["decays"][1]["decline"]
+
+
+def test_load_export_accepts_gsc_rows_object(tmp_path: Path):
+ export = tmp_path / "gsc.json"
+ export.write_text(
+ json.dumps(
+ {
+ "rows": [
+ {
+ "keys": ["https://example.com/from-keys"],
+ "clicks": 3,
+ "impressions": 40,
+ }
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ rows = content_decay.load_export(export)
+ pages = content_decay.aggregate_pages(rows)
+ assert pages["https://example.com/from-keys"]["clicks"] == 3
+
+
+def test_markdown_output_contains_table_and_recommendations():
+ report = content_decay.analyze_decay(
+ _fixture("gsc_current.json"),
+ _fixture("gsc_previous.json"),
+ )
+
+ markdown = content_decay.format_markdown(report)
+ assert "# Content Decay Report" in markdown
+ assert "| Severity | Page | Previous | Current | Decline | Dropped out | Recommendation |" in markdown
+ assert "investigate query shift" in markdown
+ assert "https://example.com/drop-out" in markdown
+
+
+def test_cli_writes_json_output(tmp_path: Path):
+ output = tmp_path / "report.json"
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SCRIPT),
+ str(FIXTURES / "gsc_current.json"),
+ str(FIXTURES / "gsc_previous.json"),
+ "--output",
+ str(output),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 0
+ report = json.loads(output.read_text(encoding="utf-8"))
+ assert report["summary"]["flagged_pages"] == 4
+ assert report["decays"][0]["severity"] == "critical"
+
+
+def test_cli_empty_input_returns_json_error(tmp_path: Path):
+ empty = tmp_path / "empty.json"
+ empty.write_text("[]", encoding="utf-8")
+
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SCRIPT),
+ str(empty),
+ str(FIXTURES / "gsc_previous.json"),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 1
+ payload = json.loads(result.stdout)
+ assert "error" in payload
+ assert "contains no rows" in payload["error"]
diff --git a/tests/test_quality_gate.py b/tests/test_quality_gate.py
new file mode 100644
index 0000000..04166cb
--- /dev/null
+++ b/tests/test_quality_gate.py
@@ -0,0 +1,101 @@
+"""Tests for the blog post quality gate."""
+
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent.parent / "scripts"))
+
+import analyze_blog
+import quality_gate
+
+FIXTURES = Path(__file__).parent / "fixtures"
+
+
+def _copy_fixture(name: str, tmp_path: Path) -> Path:
+ target = tmp_path / name
+ target.write_text((FIXTURES / name).read_text(encoding="utf-8"), encoding="utf-8")
+ return target
+
+
+def test_passing_post_exits_zero(tmp_path, capsys):
+ post = _copy_fixture("blog_pass.md", tmp_path)
+ score = analyze_blog.analyze_file(str(post))["score"]["total"]
+
+ assert score >= quality_gate.DEFAULT_THRESHOLD
+ assert quality_gate.main([str(post)]) == 0
+ assert "1 post(s) checked" in capsys.readouterr().out
+
+
+def test_failing_post_exits_one(tmp_path, capsys):
+ post = _copy_fixture("blog_fail.md", tmp_path)
+
+ assert quality_gate.main([str(post)]) == 1
+ output = capsys.readouterr().out
+ assert "Blog quality gate failed" in output
+ assert "blog_fail.md" in output
+ assert "[high]" in output
+
+
+def test_selection_skips_non_blog_paths(tmp_path):
+ skill_file = tmp_path / "skills" / "blog" / "SKILL.md"
+ skill_file.parent.mkdir(parents=True)
+ skill_file.write_text(
+ "---\n"
+ "title: Looks Like a Post\n"
+ "description: This should still be skipped because it is a skill file.\n"
+ "---\n\n"
+ "# Looks Like a Post\n",
+ encoding="utf-8",
+ )
+
+ reference_file = tmp_path / "references" / "source.md"
+ reference_file.parent.mkdir(parents=True)
+ reference_file.write_text(
+ "---\n"
+ "title: Reference Entry\n"
+ "description: This should be skipped because it is reference material.\n"
+ "---\n\n"
+ "# Reference Entry\n",
+ encoding="utf-8",
+ )
+
+ notes_file = tmp_path / "notes.md"
+ notes_file.write_text(
+ "---\n"
+ "source: Editorial memo\n"
+ "---\n\n"
+ "# Notes\n",
+ encoding="utf-8",
+ )
+
+ post_file = tmp_path / "posts" / "post.md"
+ post_file.parent.mkdir()
+ post_file.write_text(
+ "---\n"
+ "title: A Real Blog Post\n"
+ "description: This one has the required blog post frontmatter fields.\n"
+ "---\n\n"
+ "# A Real Blog Post\n",
+ encoding="utf-8",
+ )
+
+ assert not quality_gate.is_blog_post(skill_file, root=tmp_path)
+ assert not quality_gate.is_blog_post(reference_file, root=tmp_path)
+ assert not quality_gate.is_blog_post(notes_file, root=tmp_path)
+ assert quality_gate.is_blog_post(post_file, root=tmp_path)
+
+
+def test_json_format_shape(tmp_path, capsys):
+ post = _copy_fixture("blog_fail.md", tmp_path)
+
+ assert quality_gate.main([str(post), "--format", "json"]) == 1
+ payload = json.loads(capsys.readouterr().out)
+
+ assert payload["threshold"] == quality_gate.DEFAULT_THRESHOLD
+ assert len(payload["checked"]) == 1
+ assert len(payload["failures"]) == 1
+ assert payload["failures"][0]["file"].endswith("blog_fail.md")
+ assert payload["failures"][0]["score"] < quality_gate.DEFAULT_THRESHOLD
+ assert payload["failures"][0]["issues"]
+ assert payload["failures"][0]["issues"][0]["severity"] == "high"
diff --git a/tests/test_style_learn.py b/tests/test_style_learn.py
new file mode 100644
index 0000000..a8010a0
--- /dev/null
+++ b/tests/test_style_learn.py
@@ -0,0 +1,157 @@
+"""Tests for the blog style learning script."""
+
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent.parent / "scripts"))
+
+import style_learn
+
+
+def _post(title: str, body: str) -> str:
+ return f"""---
+title: {title}
+author: Test Author
+---
+
+# {title}
+
+{body}
+"""
+
+
+def _write_posts(tmp_path, count=5):
+ posts = []
+ bodies = [
+ """## What changed?
+
+We tested search intent mapping with three content teams. The content strategy became easier to review because each brief named the reader job. However, the team still kept examples short.
+
+## How did the workflow hold up?
+
+I found that content strategy reviews moved faster when writers used direct claims. The report was written after the final review.""",
+ """## Why does structure matter?
+
+Our team measured content strategy changes across several product pages. Therefore, we now open sections with the answer before adding details.
+
+## What should writers copy?
+
+We use practical examples, clear nouns, and enough context for a busy editor.""",
+ """## What did the samples show?
+
+I noticed that search intent mapping reduced vague introductions. The best drafts used content strategy language that sounded specific and grounded.
+
+## How should teams adapt?
+
+They should keep the first paragraph focused and add examples only when the reader needs proof.""",
+ """## Where does voice appear?
+
+We built a small review checklist for content strategy quality. It asks whether a sentence makes a useful claim or only fills space.
+
+## What should the editor preserve?
+
+Preserve the direct opening, the practical example, and the calm explanation.""",
+ """## Can the profile guide future drafts?
+
+Our team found that search intent mapping makes content strategy easier to teach. Moreover, it helps reviewers explain why a paragraph works.
+
+## What should be avoided?
+
+Avoid abstract promises when a concrete example would help the reader decide.""",
+ ]
+ for index in range(count):
+ path = tmp_path / f"post-{index}.md"
+ path.write_text(_post(f"Sample {index}", bodies[index % len(bodies)]), encoding="utf-8")
+ posts.append(path)
+ return posts
+
+
+def test_learn_style_from_directory_includes_required_fields(tmp_path):
+ _write_posts(tmp_path, count=5)
+
+ profile = style_learn.learn_style([tmp_path], min_posts=5)
+
+ assert profile["sample"]["post_count"] == 5
+ assert profile["sample"]["warnings"] == []
+ assert profile["sentence_length"]["mean_words"] > 0
+ assert profile["sentence_length"]["median_words"] > 0
+ assert "burstiness_variance" in profile["sentence_length"]
+ assert profile["vocabulary"]["ttr"] > 0
+ assert "transition_sentence_pct" in profile["rates"]
+ assert "passive_sentence_pct" in profile["rates"]
+ assert "ai_trigger_words_per_1k" in profile["rates"]
+ assert "first_person_per_1k_words" in profile["rates"]
+ assert profile["paragraph_lengths"]["distribution"]["under_40"]["count"] >= 0
+ assert "question_ratio" in profile["headings"]
+ assert profile["tone_descriptors"]
+
+
+def test_warns_but_does_not_crash_below_minimum(tmp_path):
+ paths = _write_posts(tmp_path, count=2)
+
+ profile = style_learn.learn_style(paths, min_posts=5)
+
+ assert profile["sample"]["post_count"] == 2
+ assert profile["sample"]["warnings"] == [
+ "Only 2 sample post(s) supplied. Recommended minimum is 5."
+ ]
+
+
+def test_signature_phrases_are_deterministic(tmp_path):
+ _write_posts(tmp_path, count=5)
+
+ first = style_learn.learn_style([tmp_path], min_posts=5)
+ second = style_learn.learn_style([tmp_path], min_posts=5)
+ phrases = [item["phrase"] for item in first["signature_phrases"]]
+
+ assert first["signature_phrases"] == second["signature_phrases"]
+ assert "content strategy" in phrases
+ assert "the content" not in phrases
+
+
+def test_markdown_render_is_voice_profile_block(tmp_path):
+ _write_posts(tmp_path, count=5)
+ profile = style_learn.learn_style([tmp_path], min_posts=5)
+
+ markdown = style_learn.render_markdown(profile)
+
+ assert "<!-- VOICE_PROFILE_START -->" in markdown
+ assert "## Learned Voice Profile" in markdown
+ assert "Sentence length" in markdown
+ assert "Signature Phrases" in markdown
+ assert "<!-- VOICE_PROFILE_END -->" in markdown
+
+
+def test_cli_writes_json_profile(tmp_path):
+ _write_posts(tmp_path, count=5)
+ output = tmp_path / "voice.json"
+
+ exit_code = style_learn.main([str(tmp_path), "--output", str(output)])
+
+ assert exit_code == 0
+ data = json.loads(output.read_text(encoding="utf-8"))
+ assert data["sample"]["post_count"] == 5
+ assert "tone_descriptors" in data
+
+
+def test_cli_writes_markdown_profile_and_warns(tmp_path, capsys):
+ paths = _write_posts(tmp_path, count=2)
+ output = tmp_path / "VOICE.md"
+
+ exit_code = style_learn.main([
+ str(paths[0]),
+ str(paths[1]),
+ "--min",
+ "5",
+ "--format",
+ "markdown",
+ "--output",
+ str(output),
+ ])
+
+ captured = capsys.readouterr()
+
+ assert exit_code == 0
+ assert "Warning: Only 2 sample post(s) supplied. Recommended minimum is 5." in captured.err
+ assert "## Learned Voice Profile" in output.read_text(encoding="utf-8")
diff --git a/uninstall.ps1 b/uninstall.ps1
index c46881b..4a95414 100644
--- a/uninstall.ps1
+++ b/uninstall.ps1
@@ -48,7 +48,8 @@ function Main {
$ClaudeScriptsDir = Join-Path $env:USERPROFILE ".claude\scripts"
$helperScripts = @("analyze_blog.py", "blog_preflight.py", "blog_render.py",
"cognitive_load.py", "discourse_research.py", "generate_hero.py",
- "load_untrusted_root.py", "lint_prose.py", "sync_flow.py")
+ "load_untrusted_root.py", "lint_prose.py", "sync_flow.py",
+ "ai_citation_score.py", "content_decay.py", "quality_gate.py", "style_learn.py")
foreach ($s in $helperScripts) {
$scriptPath = Join-Path $ClaudeScriptsDir $s
if (Test-Path $scriptPath) {
diff --git a/uninstall.sh b/uninstall.sh
index c1514bb..b410323 100755
--- a/uninstall.sh
+++ b/uninstall.sh
@@ -42,6 +42,7 @@ main() {
"analyze_blog.py" "blog_preflight.py" "blog_render.py" "cognitive_load.py"
"discourse_research.py" "generate_hero.py" "load_untrusted_root.py"
"lint_prose.py" "sync_flow.py"
+ "ai_citation_score.py" "content_decay.py" "quality_gate.py" "style_learn.py"
)
for s in "${helper_scripts[@]}"; do
if [ -f "${HOME}/.claude/scripts/${s}" ]; then