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.

39.0 KB
Raw Blame
"""Regression coverage for v2.2.0 release and repository safeguards."""

from __future__ import annotations

import hashlib
import importlib.util
import json
import os
import re
import subprocess
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parent.parent


def _load_module(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, path)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


@pytest.fixture
def preflight_module():
    return _load_module("release_preflight", ROOT / "scripts" / "blog_preflight.py")


def test_has_module_handles_missing_dotted_parent(monkeypatch, preflight_module) -> None:
    def missing_parent(_name: str):
        raise ModuleNotFoundError("missing parent")

    monkeypatch.setattr(preflight_module.importlib.util, "find_spec", missing_parent)
    assert preflight_module._has_module("missing.child") is False


def test_has_module_handles_module_with_unset_spec(monkeypatch, preflight_module) -> None:
    def unset_spec(_name: str):
        raise ValueError("module.__spec__ is None")

    monkeypatch.setattr(preflight_module.importlib.util, "find_spec", unset_spec)
    assert preflight_module._has_module("loaded_without_spec") is False


def test_pagespeed_response_populates_audit_details(monkeypatch) -> None:
    scripts_dir = ROOT / "skills" / "blog-google" / "scripts"
    sys.path.insert(0, str(scripts_dir))
    try:
        module = _load_module("release_pagespeed", scripts_dir / "pagespeed_check.py")
    finally:
        sys.path.pop(0)

    class Response:
        status_code = 200
        text = ""

        @staticmethod
        def raise_for_status() -> None:
            return None

        @staticmethod
        def json() -> dict:
            return {
                "analysisUTCTimestamp": "2026-07-23T00:00:00Z",
                "lighthouseResult": {
                    "categories": {},
                    "audits": {
                        "image-delivery-insight": {
                            "title": "Improve image delivery",
                            "score": 0.5,
                            "details": {
                                "type": "table",
                                "headings": [{"key": "url"}],
                                "items": [{"url": "https://example.com/hero.jpg"}],
                            },
                        }
                    },
                },
            }

    monkeypatch.setattr(module, "request_with_retries", lambda *_a, **_kw: Response())
    result = module.run_pagespeed("https://example.com")
    assert result["error"] is None
    assert result["audit_details"]["image-delivery-insight"]["total_items"] == 1


def test_readme_installer_hashes_match_release_files() -> None:
    readme = (ROOT / "README.md").read_text(encoding="utf-8")
    for name in ("install.sh", "install.ps1"):
        canonical = (ROOT / name).read_bytes().replace(b"\r\n", b"\n")
        digest = hashlib.sha256(canonical).hexdigest()
        assert digest in readme, f"README digest for {name} is stale"


def test_installer_hash_is_independent_of_checkout_line_endings() -> None:
    canonical = (ROOT / "install.ps1").read_bytes().replace(b"\r\n", b"\n")
    expected = hashlib.sha256(canonical).hexdigest()
    crlf_checkout = canonical.replace(b"\n", b"\r\n")
    normalized = crlf_checkout.replace(b"\r\n", b"\n")

    assert hashlib.sha256(normalized).hexdigest() == expected
    assert hashlib.sha256(normalized + b"# content drift\n").hexdigest() != expected


def test_powershell_installer_detects_its_local_checkout() -> None:
    installer = (ROOT / "install.ps1").read_text(encoding="utf-8")
    assert "$PSScriptRoot" in installer
    assert "$MyInvocation.MyCommand.Path" not in installer


def test_docs_have_no_active_powershell_pipe_to_execution() -> None:
    pattern = re.compile(
        r"(?:\birm\b|\bInvoke-RestMethod\b)[^\n]*\|\s*(?:iex|Invoke-Expression)\b",
        re.IGNORECASE,
    )
    violations = []
    for path in sorted((ROOT / "docs").rglob("*.md")):
        if pattern.search(path.read_text(encoding="utf-8")):
            violations.append(path.relative_to(ROOT).as_posix())
    assert not violations, f"active PowerShell pipe-to-execution instructions: {violations}"


def test_docs_have_no_active_shell_download_to_execution() -> None:
    pattern = re.compile(
        r"(?:\bcurl\b|\bwget\b)[^\n]*\|\s*(?:bash|sh)\b",
        re.IGNORECASE,
    )
    violations = []
    for path in sorted((ROOT / "docs").rglob("*.md")):
        if pattern.search(path.read_text(encoding="utf-8")):
            violations.append(path.relative_to(ROOT).as_posix())
    assert not violations, f"active shell download-to-execution instructions: {violations}"


def test_workflows_pin_reviewed_action_releases_by_sha() -> None:
    workflows = tuple(sorted((ROOT / ".github" / "workflows").glob("*.yml")))
    combined = "\n".join(path.read_text(encoding="utf-8") for path in workflows)

    expected = {
        "actions/checkout": "3d3c42e5aac5ba805825da76410c181273ba90b1",
        "actions/setup-python": "5fda3b95a4ea91299a34e894583c3862153e4b97",
        "actions/setup-node": "949feb2413d6458794dcd2491c4babbbce0c15c1",
    }
    for action, sha in expected.items():
        refs = set(re.findall(rf"{re.escape(action)}@([^\s#]+)", combined))
        assert refs == {sha}, f"unreviewed {action} refs: {sorted(refs)}"


def test_editorial_guidance_has_no_stat_or_length_delivery_quotas() -> None:
    template_paths = (
        "news-analysis.md",
        "faq-knowledge.md",
        "data-research.md",
        "comparison.md",
        "tutorial.md",
        "case-study.md",
    )
    stat_quota = re.compile(
        r"(?:at least|minimum)\s+(?:one|\d+)[^\n]*(?:\[STAT\]|statistic)",
        re.IGNORECASE,
    )
    for name in template_paths:
        text = (ROOT / "skills" / "blog" / "templates" / name).read_text(
            encoding="utf-8"
        )
        assert not stat_quota.search(text), f"hard statistic quota remains in {name}"

    orchestrator = (ROOT / "skills" / "blog" / "SKILL.md").read_text(
        encoding="utf-8"
    )
    outline = (ROOT / "skills" / "blog-outline" / "SKILL.md").read_text(
        encoding="utf-8"
    )
    assert "canonical target word count" not in orchestrator.lower()
    assert "never changes a score or blocks" in orchestrator
    assert "never score or block" in outline


def test_first_hand_and_retrieval_guidance_remains_evidence_conditional() -> None:
    brief = (ROOT / "skills" / "blog-brief" / "SKILL.md").read_text(
        encoding="utf-8"
    )
    reviewer = (ROOT / "agents" / "blog-reviewer.md").read_text(
        encoding="utf-8"
    )
    synthesis = (
        ROOT / "skills" / "blog" / "references" / "synthesis-contract.md"
    ).read_text(encoding="utf-8")
    research = (
        ROOT / "skills" / "blog" / "references" / "research-quality.md"
    ).read_text(encoding="utf-8")

    assert "only when the user supplies supporting methodology" in brief
    assert "markers alone earn no credit" in reviewer
    assert "retrieval notes required by FLOW" not in synthesis
    assert "retrieval notes required by FLOW" not in research


def test_editorial_heuristics_do_not_reward_fixed_passages_or_faq() -> None:
    guidance = (
        ROOT / "skills" / "blog" / "references" / "editorial-heuristics.md"
    ).read_text(encoding="utf-8")

    assert "about 50-word direct-answer" not in guidance
    assert "120 to 180 word citable passage" not in guidance
    assert "missing FAQ" not in guidance
    assert "Q&A presence and passage length earn no points" in guidance
    assert "intent-appropriate openings" in guidance


def test_active_templates_do_not_require_faq_counts_or_market_stat_openers() -> None:
    template_dir = ROOT / "skills" / "blog" / "templates"
    paths = [*sorted(template_dir.glob("*.md")), ROOT / "docs" / "TEMPLATES.md"]
    fixed_faq_count = re.compile(
        r"(?:FAQ|Q&A)[^\n]*\(\s*\d+(?:-\d+)?\s*(?:questions?|items?)",
        re.IGNORECASE,
    )

    for path in paths:
        text = path.read_text(encoding="utf-8")
        assert not fixed_faq_count.search(text), (
            f"fixed FAQ count remains in {path.relative_to(ROOT)}"
        )
        assert "At least 12 total questions" not in text
        assert "Only 3 questions" not in text

    listicle = (template_dir / "listicle.md").read_text(encoding="utf-8")
    assert "Open with the single most important market statistic" not in listicle
    assert "a market statistic only when it is material and sourced" in listicle


def test_length_experience_and_style_diagnostics_are_conditional() -> None:
    quality = (
        ROOT / "skills" / "blog" / "references" / "quality-scoring.md"
    ).read_text(encoding="utf-8")
    eeat = (
        ROOT / "skills" / "blog" / "references" / "eeat-signals.md"
    ).read_text(encoding="utf-8")
    instruction_paths = [ROOT / "CLAUDE.md"]
    agents_path = ROOT / "AGENTS.md"
    if agents_path.is_file():
        instruction_paths.append(agents_path)

    assert "Paragraphs > 200 words (Yoast red)" not in quality
    assert "length alone does not set priority" in quality
    assert "never from length alone" in quality
    assert "needs first-hand testing" not in eeat
    assert "neutral sourced analysis can rely on" in eeat
    for path in instruction_paths:
        instructions = path.read_text(encoding="utf-8")
        assert "with AI detection" not in instructions
        assert "not authorship detection" in instructions


def test_evidence_guidance_has_no_placement_or_source_count_quotas() -> None:
    troubleshooting = (ROOT / "docs" / "TROUBLESHOOTING.md").read_text(
        encoding="utf-8"
    )
    scorer = (ROOT / "scripts" / "ai_citation_score.py").read_text(
        encoding="utf-8"
    )

    assert "must be in the FIRST paragraph" not in troubleshooting
    assert "**Incorrect pattern** (stat buried)" not in troubleshooting
    assert "where it best supports\ncomprehension" in troubleshooting
    assert "at least three unique tier 1 or tier 2 citations" not in scorer
    assert "source count and diversity only when the topic" in scorer


def test_pillar_and_quality_gate_source_only_material_numeric_claims() -> None:
    pillar = (
        ROOT / "skills" / "blog" / "templates" / "pillar-page.md"
    ).read_text(encoding="utf-8")
    orchestrator = (ROOT / "skills" / "blog" / "SKILL.md").read_text(
        encoding="utf-8"
    )

    assert "Include at least one data point per core section" not in pillar
    assert "only when\nit materially improves the section" in pillar
    assert "Every number must have a named source" not in orchestrator
    assert "Source material factual statistics, measurements" in orchestrator
    assert "do not need redundant inline sourcing" in orchestrator


def test_brain_delivery_gate_matches_v21_editorial_thresholds() -> None:
    gate = (
        ROOT / "brain" / "wiki" / "quality" / "Delivery Contract Gate.md"
    ).read_text(encoding="utf-8")
    rubric = (
        ROOT / "brain" / "wiki" / "quality" / "Quality Score Rubric.md"
    ).read_text(encoding="utf-8")
    readiness = (
        ROOT
        / "brain"
        / "wiki"
        / "quality"
        / "AI Citation Readiness Subscore.md"
    ).read_text(encoding="utf-8")

    quality_gate = (ROOT / "scripts" / "quality_gate.py").read_text(
        encoding="utf-8"
    )

    assert "below 90" in gate
    assert "descriptive and non-blocking" in gate
    assert "word-count mismatch beyond the allowed tolerance" not in gate
    assert "pre-commit `quality_gate.py` threshold is 70" in rubric
    assert "90 to 100 are delivery" in rubric
    assert "DEFAULT_THRESHOLD = 70" in quality_gate
    assert "internal AI citation readiness heuristic" in readiness
    assert "not a calibrated probability" in readiness


def test_rendering_guidance_accepts_valid_google_rendered_dom() -> None:
    analyzer = (ROOT / "skills" / "blog-analyze" / "SKILL.md").read_text(
        encoding="utf-8"
    )
    crawler = (
        ROOT / "skills" / "blog" / "references" / "ai-crawler-guide.md"
    ).read_text(encoding="utf-8")

    assert "rendered DOM exposes consistent visible content and valid schema" in analyzer
    assert "not unconditional requirements" in analyzer
    assert "SSR/SSG, no JS-gated content" not in analyzer
    assert "single most common reason" not in crawler
    assert "test the deployed response" in crawler
    assert "not unconditional Google pass criteria" in crawler


def test_public_marketplace_slug_is_current() -> None:
    readme = (ROOT / "README.md").read_text(encoding="utf-8")
    assert "claude-blog@agricidaniel-blog" in readme
    assert "claude-blog@agricidaniel-claude-blog" not in readme


def test_dependency_requirements_and_locks_are_coherent() -> None:
    import tomllib
    from packaging.requirements import Requirement
    from packaging.utils import canonicalize_name

    project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
    uv_lock = tomllib.loads((ROOT / "uv.lock").read_text(encoding="utf-8"))
    groups = project["project"]["optional-dependencies"]
    extras = {
        canonicalize_name(Requirement(raw).name): Requirement(raw)
        for group in groups.values() for raw in group
    }
    locked_uv = {
        (canonicalize_name(package["name"]), package["version"])
        for package in uv_lock["package"]
    }
    requirement_paths = [ROOT / "requirements.txt"] + [
        ROOT / "skills" / skill / "scripts" / "requirements.txt"
        for skill in ("blog-audio", "blog-google", "blog-notebooklm")
    ]
    shared_pins = {"google-genai", "patchright", "google-ads"}
    for path in requirement_paths:
        declarations = [
            Requirement(line.split("#", 1)[0].strip())
            for line in path.read_text(encoding="utf-8").splitlines()
            if line.split("#", 1)[0].strip()
        ]
        lock = path.with_suffix(".lock").read_text(encoding="utf-8")
        pins = {
            canonicalize_name(name): version
            for name, version in re.findall(r"^([A-Za-z0-9_.-]+)==([^ \\]+)", lock, re.MULTILINE)
        }
        for requirement in declarations:
            name = canonicalize_name(requirement.name)
            assert name in pins, f"{path}: {name} is missing from the hash lock"
            version = pins[name]
            assert requirement.specifier.contains(version), f"{path}: {name}=={version} violates {requirement}"
            if name in extras:
                assert extras[name].specifier.contains(version), f"pyproject extra rejects {name}=={version}"
            if name in shared_pins:
                assert (name, version) in locked_uv, f"uv.lock disagrees on {name}=={version}"
            block = re.search(
                rf"^{re.escape(requirement.name)}=={re.escape(version)}(?P<body>.*?)(?=^[A-Za-z0-9_.-]+==|\Z)",
                lock, re.MULTILINE | re.DOTALL | re.IGNORECASE,
            )
            assert block and "--hash=sha256:" in block.group("body"), f"{path}: {name} has no hash"
    audio = {canonicalize_name(Requirement(raw).name): Requirement(raw) for raw in groups["presentation"]}
    assert str(audio["google-genai"].specifier) == str(next(
        req.specifier for req in [Requirement(line) for line in
            (ROOT / "skills/blog-audio/scripts/requirements.txt").read_text().splitlines()
            if line and not line.startswith("#")]
        if canonicalize_name(req.name) == "google-genai"
    ))


def test_shell_installer_is_locale_safe_and_complete(tmp_path: Path) -> None:
    fake_bin = tmp_path / "bin"
    fake_bin.mkdir()
    fake_pip = fake_bin / "pip3"
    fake_pip.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
    fake_pip.chmod(0o755)

    env = os.environ.copy()
    env.update({
        "HOME": str(tmp_path / "home"),
        "CLAUDE_BLOG_SKIP_PIP": "1",
        "LANG": "tr_TR.UTF-8",
        "LC_ALL": "tr_TR.UTF-8",
        "PATH": f"{fake_bin}:{env['PATH']}",
    })
    result = subprocess.run(
        ["bash", str(ROOT / "install.sh")],
        cwd=ROOT,
        env=env,
        text=True,
        capture_output=True,
        check=False,
    )

    expected = len([
        path for path in (ROOT / "skills").glob("*/SKILL.md")
        if path.parent.name != "blog"
    ])
    installed = len(list((tmp_path / "home" / ".claude" / "skills").glob("blog-*/SKILL.md")))

    assert result.returncode == 0, result.stderr
    assert "refusing skill" not in result.stderr
    assert f"Sub-skills:   {expected} installed" in result.stdout
    assert installed == expected


def test_standalone_installers_ship_google_update_ledger() -> None:
    assert (ROOT / "data" / "google-updates.json").is_file()
    ownership = _load_module("release_installer_ownership", ROOT / "scripts/installer_ownership.py")
    inventory = ownership.build_inventory(ROOT)[0]
    ledger = next(item for relative, item in inventory.items() if str(relative) == "skills/blog/data/google-updates.json")
    assert ledger.source == ROOT / "data/google-updates.json"
    windows = (ROOT / "scripts/windows_installer_ownership.ps1").read_text(encoding="utf-8")
    assert "Add-CBPlanFile $plan $ledger 'skills/blog/data/google-updates.json'" in windows
    assert "Invoke-ClaudeBlogInstall" in (ROOT / "install.ps1").read_text(encoding="utf-8")
    assert "blog" in (ROOT / "uninstall.sh").read_text(encoding="utf-8")
    assert "blog" in (ROOT / "uninstall.ps1").read_text(encoding="utf-8")


def test_uninstallers_preserve_shared_google_credentials() -> None:
    for name in ("uninstall.sh", "uninstall.ps1"):
        text = (ROOT / name).read_text(encoding="utf-8")
        assert "oauth-token.json" not in text
        assert "google-api.json" not in text
        assert "left intact" in text


def test_dependency_smoke_cli_is_explicit_and_offline() -> None:
    script = (ROOT / "scripts" / "dependency_smoke.py").read_text(
        encoding="utf-8"
    )
    workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text(
        encoding="utf-8"
    )
    for component in ("audio", "browser", "preflight"):
        assert f'"{component}"' in script
    assert "--require-hashes" in workflow
    assert "skills/blog-audio/scripts/requirements.lock" in workflow
    assert "skills/blog-notebooklm/scripts/requirements.lock" in workflow
    assert "--component audio" in workflow
    assert "--component browser --component preflight" in workflow
    assert "browser_launched" in script and "network_used" in script
    assert "generate_single_speaker" in script
    assert "tts_path_exercised" in script
    assert "response_modalities" in script
    assert "inline_pcm_verified" in script


def test_ledger_consumer_guidance_matches_installed_path() -> None:
    orchestrator = (ROOT / "skills" / "blog" / "SKILL.md").read_text(
        encoding="utf-8"
    )
    currentness = (
        ROOT
        / "skills"
        / "blog-google"
        / "references"
        / "search-currentness.md"
    ).read_text(encoding="utf-8")
    unix_inventory = (ROOT / "scripts/installer_ownership.py").read_text(encoding="utf-8")
    windows_inventory = (ROOT / "scripts/windows_installer_ownership.ps1").read_text(encoding="utf-8")

    # The skill is host-rendered in both distribution layouts. A reference
    # receives the caller's trusted root instead of assuming substitution.
    assert '${CLAUDE_SKILL_DIR}/../../data/google-updates.json' in orchestrator
    assert '${CLAUDE_SKILL_DIR}/data/google-updates.json' in orchestrator
    for guidance in (orchestrator, currentness):
        assert '.claude-plugin/plugin.json' in guidance
        assert 'never from CWD' in guidance or 'current working directory' in guidance
    assert 'supplied by the caller' in currentness
    assert '~/.claude/skills/blog/data/google-updates.json' in currentness
    assert '"skills/blog/data/google-updates.json"' in unix_inventory
    assert "'skills/blog/data/google-updates.json'" in windows_inventory


def _write_flow_lock(root: Path, content: bytes = b"prompt\n") -> None:
    prompt = (
        root
        / "skills"
        / "blog-flow"
        / "references"
        / "prompts"
        / "find"
        / "prompt.md"
    )
    prompt.parent.mkdir(parents=True)
    prompt.write_bytes(content)
    lock = root / "skills" / "blog-flow" / "references" / "flow-prompts.lock"
    lock.write_text(
        f"{hashlib.sha256(content).hexdigest()}  "
        "skills/blog-flow/references/prompts/find/prompt.md\n",
        encoding="utf-8",
    )


def test_consistency_checker_errors_on_missing_target_and_warns_on_orphan(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "release_consistency", ROOT / "scripts" / "consistency_check.py"
    )
    (tmp_path / "docs").mkdir()
    (tmp_path / "docs" / "guide.md").write_text(
        "[missing](missing.md)\n", encoding="utf-8"
    )
    (tmp_path / "scripts").mkdir()
    (tmp_path / "scripts" / "orphan.py").write_text(
        '"""fixture"""\n', encoding="utf-8"
    )
    _write_flow_lock(tmp_path)

    report = module.check(tmp_path)
    assert report["status"] == "fail"
    assert any(e["kind"] == "missing_markdown_target" for e in report["errors"])
    assert any(w["target"] == "scripts/orphan.py" for w in report["warnings"])


def test_consistency_checker_discovers_skill_relative_resources_and_agents(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "release_consistency_relative",
        ROOT / "scripts" / "consistency_check.py",
    )
    skill = tmp_path / "skills" / "blog-demo"
    (skill / "references").mkdir(parents=True)
    (skill / "scripts").mkdir()
    (skill / "templates").mkdir()
    (skill / "SKILL.md").write_text(
        "Use `references/guide.md`, run `scripts/run.py`, load "
        "`templates/example.md`, then dispatch `blog-demo-agent`.\n",
        encoding="utf-8",
    )
    for relative in (
        "references/guide.md",
        "scripts/run.py",
        "templates/example.md",
    ):
        (skill / relative).write_text("fixture\n", encoding="utf-8")
    (tmp_path / "agents").mkdir()
    (tmp_path / "agents" / "blog-demo-agent.md").write_text(
        "agent\n", encoding="utf-8"
    )
    _write_flow_lock(tmp_path)

    report = module.check(tmp_path)
    warned = {entry["target"] for entry in report["warnings"]}
    assert report["status"] == "pass"
    assert "skills/blog-demo/references/guide.md" not in warned
    assert "skills/blog-demo/scripts/run.py" not in warned
    assert "skills/blog-demo/templates/example.md" not in warned
    assert "agents/blog-demo-agent.md" not in warned


def _public_fixture(root: Path) -> None:
    public = "https://github.com/AgriciDaniel/claude-blog"
    version = "2.3.2"
    raw_sh = (
        "https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.sh"
    )
    raw_ps1 = (
        "https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.ps1"
    )
    (root / ".claude-plugin").mkdir(parents=True)
    (root / ".github" / "ISSUE_TEMPLATE").mkdir(parents=True)
    (root / "skills" / "blog").mkdir(parents=True)
    (root / "README.md").write_text(
        f"{public}\nclaude-blog@agricidaniel-blog\n{raw_sh}\n{raw_ps1}\n"
        "git checkout <commit-sha-or-release-tag>\n"
        "CLAUDE_BLOG_REF=<commit-sha-or-release-tag>\n",
        encoding="utf-8",
    )
    (root / "CLAUDE.md").write_text(
        "CLAUDE_BLOG_REF=<commit-sha-or-release-tag>\n",
        encoding="utf-8",
    )
    (root / "CITATION.cff").write_text(
        f'repository-code: "{public}"\nversion: {version}\n',
        encoding="utf-8",
    )
    (root / "pyproject.toml").write_text(
        "\n".join(
            [f'version = "{version}"']
            + [
                f'{field} = "{public}{suffix}"'
                for field, suffix in (
                    ("homepage", ""),
                    ("repository", ""),
                    ("issues", "/issues"),
                    ("documentation", "/tree/main/docs"),
                    ("changelog", "/blob/main/CHANGELOG.md"),
                )
            ]
        ),
        encoding="utf-8",
    )
    (root / ".claude-plugin" / "plugin.json").write_text(
        json.dumps(
            {
                "name": "claude-blog",
                "version": version,
                "homepage": public,
                "repository": public,
                "author": {
                    "name": "AgriciDaniel",
                    "url": "https://github.com/AgriciDaniel",
                },
            }
        ),
        encoding="utf-8",
    )
    (root / ".claude-plugin" / "marketplace.json").write_text(
        json.dumps(
            {
                "name": "agricidaniel-blog",
                "owner": {"name": "AgriciDaniel"},
                "plugins": [{"name": "claude-blog", "source": "./"}],
            }
        ),
        encoding="utf-8",
    )
    (root / ".github" / "ISSUE_TEMPLATE" / "config.yml").write_text(
        "\n".join(
            (
                f"url: {public}/discussions",
                f"url: {public}/security/advisories/new",
                f"url: {public}/tree/main/docs",
            )
        ),
        encoding="utf-8",
    )
    (root / ".github" / "SECURITY.md").write_text(
        "Only the latest version is supported.\n"
        "Use `git checkout <commit-sha-or-release-tag>` before installation.\n",
        encoding="utf-8",
    )
    (root / "install.sh").write_text(
        f'{raw_sh}\nCLAUDE_BLOG_VERSION="{version}"\n'
        'repo="${CLAUDE_BLOG_REPO:-AgriciDaniel/claude-blog}"\n',
        encoding="utf-8",
    )
    (root / "install.ps1").write_text(
        f'{raw_ps1}\n$ClaudeBlogVersion = "{version}"\n'
        '$Repo = "AgriciDaniel/claude-blog"\n',
        encoding="utf-8",
    )
    for uninstaller in ("uninstall.sh", "uninstall.ps1"):
        (root / uninstaller).write_text("# public ownership-aware uninstaller\n", encoding="utf-8")
    (root / "skills" / "blog" / "SKILL.md").write_text(
        f'  version: "{version}"\n',
        encoding="utf-8",
    )


def test_public_release_validator_passes_normalized_fixture(tmp_path: Path) -> None:
    module = _load_module(
        "release_public_validator",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    assert module.validate(tmp_path)["status"] == "pass"


@pytest.mark.parametrize("surface", ["plugin.json", "marketplace.json"])
def test_public_release_validator_rejects_desynchronized_plugin_identity(
    tmp_path: Path, surface: str,
) -> None:
    module = _load_module("release_identity_validator", ROOT / "scripts/validate_public_release.py")
    _public_fixture(tmp_path)
    path = tmp_path / ".claude-plugin" / surface
    data = json.loads(path.read_text(encoding="utf-8"))
    if surface == "plugin.json":
        data["name"] = "blog-engine"
        expected_kind = "invalid_public_plugin_ownership"
    else:
        data["plugins"][0]["name"] = "blog-engine"
        expected_kind = "invalid_public_marketplace_plugin"
    path.write_text(json.dumps(data), encoding="utf-8")
    result = module.validate(tmp_path)
    assert result["status"] == "fail"
    assert any(error["kind"] == expected_kind for error in result["errors"])


_STUDIO_ENTRY = {
    "name": "blog-studio",
    "source": {
        "source": "git-subdir",
        "url": "AgriciDaniel/claude-blog",
        "path": "plugins/blog-studio",
        "ref": "blog-studio",
        "sha": "c1cc72f8" * 5,
    },
    "version": "0.3.0",
    "homepage": "https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio",
}


def _with_studio(root: Path, entry: dict) -> None:
    path = root / ".claude-plugin" / "marketplace.json"
    data = json.loads(path.read_text(encoding="utf-8"))
    data["plugins"].append(entry)
    path.write_text(json.dumps(data), encoding="utf-8")


def test_public_release_validator_accepts_the_pinned_studio_entry(tmp_path: Path) -> None:
    module = _load_module("release_studio_validator", ROOT / "scripts/validate_public_release.py")
    _public_fixture(tmp_path)
    _with_studio(tmp_path, _STUDIO_ENTRY)
    assert module.validate(tmp_path)["status"] == "pass"


@pytest.mark.parametrize(
    ("change", "expected_kind"),
    [
        ({"source": "./plugins/blog-studio"}, "local_companion_source"),
        ({"source": {**_STUDIO_ENTRY["source"], "sha": "__STUDIO_SHA__"}}, "invalid_studio_distribution"),
        ({"source": {**_STUDIO_ENTRY["source"], "sha": "C1CC72F8" * 5}}, "invalid_studio_distribution"),
        ({"source": {**_STUDIO_ENTRY["source"], "ref": "main"}}, "invalid_studio_distribution"),
        ({"source": {**_STUDIO_ENTRY["source"], "url": "Someone/claude-blog"}}, "invalid_studio_distribution"),
        ({"homepage": "https://example.com"}, "invalid_studio_distribution"),
    ],
)
def test_public_release_validator_rejects_a_bad_studio_entry(
    tmp_path: Path, change: dict, expected_kind: str,
) -> None:
    module = _load_module("release_bad_studio_validator", ROOT / "scripts/validate_public_release.py")
    _public_fixture(tmp_path)
    _with_studio(tmp_path, {**_STUDIO_ENTRY, **change})
    result = module.validate(tmp_path)
    assert result["status"] == "fail"
    assert any(error["kind"] == expected_kind for error in result["errors"])


def test_public_release_validator_rejects_a_nested_plugin_manifest(tmp_path: Path) -> None:
    module = _load_module("release_nested_validator", ROOT / "scripts/validate_public_release.py")
    _public_fixture(tmp_path)
    nested = tmp_path / "plugins" / "blog-studio" / ".claude-plugin"
    nested.mkdir(parents=True)
    (nested / "plugin.json").write_text('{"name": "blog-studio"}', encoding="utf-8")
    result = module.validate(tmp_path)
    assert result["status"] == "fail"
    assert {"kind": "nested_plugin_manifest", "file": "plugins/blog-studio/.claude-plugin/plugin.json"} in result["errors"]


@pytest.mark.parametrize(
    ("surface", "unsafe"),
    [
        ("README.md", "git checkout v2.2.0\n"),
        ("README.md", "CLAUDE_BLOG_REF=v2.2.0 bash install.sh\n"),
        ("CLAUDE.md", 'CLAUDE_BLOG_REF="v2.2.0"\n'),
        ("CLAUDE.md", "https://raw.githubusercontent.com/AgriciDaniel/claude-blog/v2.2.0/install.sh\n"),
        (".github/SECURITY.md", "cd claude-blog && git checkout v2.2.0\n"),
        (".github/SECURITY.md", "CLAUDE_BLOG_REF=v2.2.0 ./install.sh\n"),
    ],
)
def test_public_release_validator_rejects_pinning_install_docs_to_preownership_tag(
    tmp_path: Path, surface: str, unsafe: str,
) -> None:
    """v2.2.0 ships an uninstall.sh with an unguarded recursive delete."""
    module = _load_module("release_preownership_validator", ROOT / "scripts/validate_public_release.py")
    _public_fixture(tmp_path)
    path = tmp_path / surface
    path.write_text(path.read_text(encoding="utf-8") + unsafe, encoding="utf-8")
    result = module.validate(tmp_path)
    assert result["status"] == "fail"
    assert any(error["kind"] == "unsafe_preownership_installer_pin" for error in result["errors"])


def test_validator_does_not_depend_on_the_host_plugin_validator() -> None:
    """The reserved-name check in newer Claude Code is not part of release logic."""
    source = (ROOT / "scripts/validate_public_release.py").read_text(encoding="utf-8")
    assert "subprocess" not in source and "plugin validate" not in source
    assert 'PUBLIC_PLUGIN_IDENTIFIER = "claude-blog"' in source
    manifest = json.loads((ROOT / ".claude-plugin/plugin.json").read_text(encoding="utf-8"))
    marketplace = json.loads((ROOT / ".claude-plugin/marketplace.json").read_text(encoding="utf-8"))
    assert manifest["name"] == "claude-blog"
    assert marketplace["name"] == "agricidaniel-blog"
    assert [entry["name"] for entry in marketplace["plugins"]] == ["claude-blog", "blog-studio"]
    assert "blog-engine" not in json.dumps([manifest, marketplace])


def test_documented_install_flow_never_runs_the_preownership_release() -> None:
    for relative in ("README.md", "CLAUDE.md", "docs/INSTALLATION.md"):
        text = (ROOT / relative).read_text(encoding="utf-8")
        assert "v2.2.0/install.sh" not in text, relative
        assert "git checkout v2.2.0" not in text, relative
        assert "CLAUDE_BLOG_REF=v2.2.0" not in text, relative
    readme = (ROOT / "README.md").read_text(encoding="utf-8")
    assert "Integrity is only as pinned as `CLAUDE_BLOG_REF`" in readme
    assert "full commit SHA" in readme


@pytest.mark.parametrize("relative", ["skills/blog-write/SKILL.md", "scripts/unlisted.py", "scripts/unlisted.ps1", "data/unlisted.json"])
def test_public_release_validator_checks_unlisted_runtime_surfaces(tmp_path: Path, relative: str) -> None:
    module = _load_module("release_unlisted_validator", ROOT / "scripts/validate_public_release.py")
    _public_fixture(tmp_path)
    path = tmp_path / relative
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("claude-blog@ai-marketing-hub-claude-blog\n", encoding="utf-8")
    result = module.validate(tmp_path)
    assert any(error["kind"] == "private_marketplace_slug" and error["file"] == relative for error in result["errors"])


def test_current_public_release_surfaces_pass_validator() -> None:
    private_note = ROOT / "docs" / "PUBLIC-BACKLOG-TRIAGE-2026-07-23.md"
    if private_note.exists():
        pytest.skip("private source worktree intentionally retains its triage note")
    module = _load_module(
        "release_public_validator_current",
        ROOT / "scripts" / "validate_public_release.py",
    )
    assert module.validate(ROOT)["status"] == "pass"


def test_public_release_validator_requires_corrected_security_guidance(
    tmp_path: Path,
) -> None:
    """SECURITY.md must tell users to pin a reviewed ref, not the v2.2.0 tag."""
    module = _load_module(
        "release_public_validator_security_version",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    security = tmp_path / ".github" / "SECURITY.md"
    security.write_text(
        security.read_text(encoding="utf-8").replace(
            "git checkout <commit-sha-or-release-tag>", "git checkout v1.7.0"
        ),
        encoding="utf-8",
    )
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(
        error["kind"] == "invalid_public_security_guidance"
        and error["file"] == ".github/SECURITY.md"
        for error in report["errors"]
    )


def test_security_policy_never_tells_users_to_run_the_preownership_installer() -> None:
    text = (ROOT / ".github" / "SECURITY.md").read_text(encoding="utf-8")
    assert "git checkout <commit-sha-or-release-tag>" in text
    assert "git checkout v2.2.0" not in text
    assert "CLAUDE_BLOG_REF=v2.2.0" not in text


def test_public_release_validator_rejects_private_raw_url(tmp_path: Path) -> None:
    module = _load_module(
        "release_public_validator_private",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    (tmp_path / "install.sh").write_text(
        "https://raw.githubusercontent.com/AI-Marketing-Hub/claude-blog/main/install.sh\n",
        encoding="utf-8",
    )
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(e["kind"] == "private_raw_url" for e in report["errors"])


def test_public_release_validator_rejects_private_issue_routing(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "release_public_validator_issue_routing",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    config = tmp_path / ".github" / "ISSUE_TEMPLATE" / "config.yml"
    config.write_text(
        config.read_text(encoding="utf-8").replace(
            "https://github.com/AgriciDaniel/claude-blog/discussions",
            "https://github.com/AI-Marketing-Hub/claude-blog/discussions",
        ),
        encoding="utf-8",
    )
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(
        error["file"] == ".github/ISSUE_TEMPLATE/config.yml"
        and error["kind"] in {
            "private_repository_url",
            "invalid_public_issue_routing",
        }
        for error in report["errors"]
    )


def test_public_release_validator_rejects_version_collision(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "release_public_validator_version",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    pyproject = tmp_path / "pyproject.toml"
    pyproject.write_text(
        pyproject.read_text(encoding="utf-8").replace("2.3.2", "2.1.0"),
        encoding="utf-8",
    )
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(
        error["kind"] == "invalid_public_release_version"
        and error["file"] == "pyproject.toml"
        for error in report["errors"]
    )


def test_public_release_validator_rejects_third_party_raw_url(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "release_public_validator_third_party",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    readme = (tmp_path / "README.md").read_text(encoding="utf-8")
    (tmp_path / "README.md").write_text(
        readme.replace(
            "https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.sh",
            "https://raw.githubusercontent.com/ThirdParty/claude-blog/main/install.sh",
        ),
        encoding="utf-8",
    )
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(
        e["kind"] == "wrong_public_raw_installer_url" for e in report["errors"]
    )


def test_public_release_validator_rejects_wrong_plugin_repository_owner(
    tmp_path: Path,
) -> None:
    module = _load_module(
        "release_public_validator_wrong_owner",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    plugin_path = tmp_path / ".claude-plugin" / "plugin.json"
    plugin = json.loads(plugin_path.read_text(encoding="utf-8"))
    plugin["repository"] = "https://github.com/ThirdParty/claude-blog"
    plugin_path.write_text(json.dumps(plugin), encoding="utf-8")
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(
        e["kind"] == "invalid_public_plugin_ownership"
        and e.get("field") == "repository"
        for e in report["errors"]
    )


def test_public_release_validator_rejects_private_docs(tmp_path: Path) -> None:
    module = _load_module(
        "release_public_validator_docs",
        ROOT / "scripts" / "validate_public_release.py",
    )
    _public_fixture(tmp_path)
    (tmp_path / "docs").mkdir()
    (tmp_path / "docs" / "INSTALLATION.md").write_text(
        "Use an authenticated gh auth login for access to the AI-Marketing-Hub org.\n",
        encoding="utf-8",
    )
    report = module.validate(tmp_path)
    assert report["status"] == "fail"
    assert any(e["kind"] == "private_auth_instruction" for e in report["errors"])


def test_public_triage_note_covers_entire_open_backlog() -> None:
    path = ROOT / "docs" / "PUBLIC-BACKLOG-TRIAGE-2026-07-23.md"
    if not path.exists():
        pytest.skip("private-only triage note is excluded from public releases")
    text = path.read_text(encoding="utf-8")
    for number in (48, 47, 46, 42, 41, 40, 38, 37, 26, 25, 23, 20, 19, 18, 17, 15, 13, 10):
        assert f"/pull/{number}" in text
    for number in (44, 36, 33, 29, 22):
        assert f"/issues/{number}" in text
    assert "No public mutations were performed" in text