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.
Python agent-skillsaiai-citationsai-contentai-marketingai-marketing-hubblogblog-writingclaude-codeclaude-code-skillclaude-pluginclaude-skillcontent-creationcontent-optimizationcontent-strategyeeatgeomultilingualopen-sourceseo
feat(v1.9.0): Blog Delivery Contract + 5-gate enforcement + hero ladder
Daniel04c183ee572f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 1b08038..6855b8c 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "claude-blog","description": "AI-powered blog skill suite with 30 sub-skills and 5 agents. FLOW framework integration (Find/Optimize/Win, 30 evidence-led prompts), semantic topic-cluster planning + execution, multilingual publishing (translate/localize/locale-audit), Google API integration (PageSpeed, CrUX, GSC, GA4, YouTube, NLP, Keywords), YouTube video embedding, persona-driven writing, two-tier AI slop detection, 0-4 editorial heuristics rubric, cognitive-load assessment, durable BRAND.md + VOICE.md context, API-free last-30-days discourse research, 5-dimension research quality rubric, 6-LAW synthesis contract, fact-checking, cannibalization detection, CMS taxonomy sync, NotebookLM research, Gemini TTS audio narration, 5-category scoring, and Gemini image generation. Optimized for Google rankings and AI citations (GEO/AEO).",- "version": "1.8.6",+ "version": "1.9.0","author": {"name": "AgriciDaniel","url": "https://github.com/AgriciDaniel"diff --git a/.gitignore b/.gitignoreindex c8dbee0..11bbd74 100644--- a/.gitignore+++ b/.gitignore@@ -95,3 +95,6 @@ definitive-resesarch-blueprint-for-claude-blog.md# Hex-named cached GIFs at repo root only (auto-downloaded artifacts)/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*.gif++# Session-scoped audit evidence at repo root (regenerated per audit cycle)+/audit-results.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 770e631..e3412c2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+_No unreleased changes._++## [1.9.0] - 2026-05-18++### Blog Delivery Contract (mandatory pre-presentation gate)++The rankenstein.pro audit-asymptote drafting cycle surfaced a structural gap: `/blog write` had a `blog-reviewer` step but it ran as advisory. Sloppy drafts (no real hero image, broken og:image, SVG overflows visible on first render, no .pdf, .md/.html divergence) reached the user before any gate fired. v1.9.0 converts the Category-3 "reviewer exists but does not block" defect into infrastructure. Same lesson as the v1.8.x cycle; one layer up.++**Five-gate delivery contract** (`skills/blog/references/blog-delivery-contract.md`):++1. Capability Discovery: enumerate MCP servers, env vars, optional deps, agents, helper scripts before writing. Output `capabilities.json`.+2. Format Completeness: every draft ships `.md` + `.html` + `.pdf` + a real `hero.<ext>`. The renderer (`scripts/blog_render.py`) produces all three from the same source.+3. Visual Verification: render the HTML via `patchright` at 3 viewport widths (375, 768, 1280), capture screenshots, assert no SVG child overflows its viewBox, validate JSON-LD, check dark-mode color swap, capture console errors.+4. Content Review (BLOCKING): `blog-reviewer` agent scores against the rendered HTML. Threshold: score 90/100 or higher AND zero P0 issues from `editorial-heuristics.md`. Reviewer emits `BLOCKING: true|false (reason)` line for machine-readable gating.+5. Asset + Link Integrity: every img src resolves, og:image points to a real file, external links return 200, JSON-LD wordCount matches body word count within 5%.++**Hero image generation ladder** (`scripts/generate_hero.py`):++1. Banana MCP (orchestrator-level; when nanobanana-mcp is loaded)+2. Direct Gemini API via google-genai (when GOOGLE_AI_API_KEY is set)+3. Premium stock APIs: Unsplash, Pexels, Pixabay (any key suffices)+4. Openverse public API (CC-licensed; no key required)+5. Block with setup instructions if none succeed++Iteration loop: on any gate failure the orchestrator iterates up to 3 times before escalating to the user with a diagnostic. The user is no longer the first reviewer; the gates are.++**Added**++- `skills/blog/references/blog-delivery-contract.md` (the contract spec)+- `scripts/blog_preflight.py` (runs Gates 1, 2, 3, 5; reads Gate 4 output)+- `scripts/blog_render.py` (md to html to pdf, deterministic)+- `scripts/generate_hero.py` (5-step image ladder)+- `tests/test_blog_delivery_contract.py` (locks the contract in place)+- `pyproject.toml`: new `presentation` optional-deps group (patchright, weasyprint, google-genai, requests, markdown)++**Changed**++- `agents/blog-reviewer.md`: scorecard now ends with `BLOCKING: true|false (reason)` line; blocking thresholds documented (score 90+, zero P0)+- `skills/blog/SKILL.md`: new Step 6.5 between Score and Deliver; reference count 20 to 21+- `skills/blog-write/SKILL.md`: new Phase 6.5 enforcement section+- `skills/blog-rewrite/SKILL.md`: new Phase 5.5 enforcement section+- `install.sh`, `install.ps1`, `uninstall.sh`, `uninstall.ps1`: ship the 3 new scripts (caught immediately by `test_installer_sync.py` from v1.8.6)++**Why this matters**++The v1.8.x cycle taught a lesson: audits ladder you up to your asymptote; infrastructure raises the asymptote. v1.9.0 applies that one level up, from the project's code to the project's own output. Sloppy drafts cannot reach the user because the gates use the project's tools automatically, without depending on the writer to remember.+## [1.8.6] - 2026-05-17Seventh-round hostile-audit hardening. The 7th audit caught 18 file:linediff --git a/CITATION.cff b/CITATION.cffindex 9f637bc..a0e96d0 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -11,8 +11,8 @@ authors:repository-code: "https://github.com/AgriciDaniel/claude-blog"url: "https://claude-blog.md"license: MIT-version: 1.8.6-date-released: "2026-05-17"+version: 1.9.0+date-released: "2026-05-18"keywords:- claude-code- blogdiff --git a/CLAUDE.md b/CLAUDE.mdindex 3690aee..792950c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5,7 +5,7 @@This repository contains **Claude Blog**, a Tier 4 Claude Code skill for blog contentcreation, optimization, and management. It follows the Agent Skills open standard and the3-layer architecture (directive, orchestration, execution). 30 sub-skills, 5 specialized-subagents, 12 content templates, and 20 reference docs are dual-optimized for Google rankings+subagents, 12 content templates, and 21 reference docs are dual-optimized for Google rankings(December 2025 Core Update, E-E-A-T) and AI citations (GEO/AEO). Includes FLOW frameworkintegration, semantic topic-cluster planning + execution, multilingual publishing (Pro HubChallenge v1.7.0), BRAND.md/VOICE.md/DISCOURSE.md project-root context auto-load (v1.8.0,@@ -31,7 +31,7 @@ claude-blog/scripts/sync_flow.py # Pulls FLOW references (stdlib, sandboxed)skills/ # 30 sub-skills (blog/ is the orchestrator)blog/SKILL.md # Main orchestrator, routing, scoring- references/ # 20 on-demand knowledge files (5 new in v1.8.0)+ references/ # 21 on-demand knowledge files (5 in v1.8.0, 1 in v1.9.0)templates/ # 12 content templatesscripts/ # Python analysis scriptsblog-write/SKILL.md # Write new articles from scratchdiff --git a/README.md b/README.mdindex 363d1e6..3947714 100644--- a/README.md+++ b/README.md@@ -124,6 +124,20 @@ Five reference documents under `skills/blog/references/` define the editorial anAdapted from `pbakaus/impeccable` (Apache 2.0) and `mvanhorn/last30days-skill` (MIT). See `CONTRIBUTORS.md` for the full attribution.+### Delivery contract (v1.9.0)++Every blog passes a 5-gate contract before being shown to the user. The user is never the first reviewer; the gates are.++| Gate | Enforces | Implementation |+|---|---|---|+| 1. Capability Discovery | Required tools and agents present before write | `scripts/blog_preflight.py --gate 1` |+| 2. Format Completeness | `.md` + `.html` + `.pdf` + real hero image | `scripts/blog_render.py`, `scripts/generate_hero.py` |+| 3. Visual Verification | No SVG overflow, valid JSON-LD, dark mode works | `patchright` at 3 viewport widths |+| 4. Content Review (BLOCKING) | `blog-reviewer` score 90+ AND zero P0 issues | `agents/blog-reviewer.md` (now blocking) |+| 5. Asset + Link Integrity | Every img resolves, og:image exists, links return 200 | `scripts/blog_preflight.py --gate 5` |++Hero image ladder: Banana MCP, direct Gemini API, premium stock (Unsplash, Pexels, Pixabay), Openverse public API. First available wins. Block-and-iterate up to 3 times on any gate failure before escalating to the user. Full spec: `skills/blog/references/blog-delivery-contract.md`.+## Features### 12 Content Templates@@ -193,7 +207,7 @@ claude-blog/├── skills/│ ├── blog/ # Main orchestrator│ │ ├── SKILL.md # Routes all 29 user-facing commands (28 distinct + `/blog update` alias)-│ │ ├── references/ # 20 on-demand reference docs (5 new in v1.8.0)+│ │ ├── references/ # 21 on-demand reference docs (5 new in v1.8.0, 1 new in v1.9.0)│ │ └── templates/ # 12 content type templates│ ├── blog-write/SKILL.md # Sub-skills (28 user-facing + 2 internal-only)│ ├── blog-rewrite/SKILL.mddiff --git a/agents/blog-reviewer.md b/agents/blog-reviewer.mdindex 4ff72da..d2d3887 100644--- a/agents/blog-reviewer.md+++ b/agents/blog-reviewer.md@@ -175,7 +175,31 @@ When reviewing citations, verify against this tier system:1. [Highest impact fix]2. [Second priority]3. [Third priority]++BLOCKING: true|false (one-line reason)+```++## Blocking Decision (v1.9.0)++The scorecard MUST end with a `BLOCKING: true|false (reason)` line. This line is machine-readable by `scripts/blog_preflight.py` Gate 4 and drives the iteration loop in the orchestrator.++Set `BLOCKING: true` if ANY of the following hold:++- Overall score below 90/100 (the Exceptional band)+- Any P0 issue from `skills/blog/references/editorial-heuristics.md` (fabricated stats, broken structure, plagiarism risk; see that file for the full list)+- Burstiness score in the Flagged range (too uniform sentence length)+- More than 3 known AI phrases detected+- Vocabulary diversity (TTR) below 0.4++Set `BLOCKING: false` only when none of those conditions hold. The reason field is the single most important sentence on the line; it tells the orchestrator what to fix in the next iteration. Examples:+```+BLOCKING: true (overall 87/100 below threshold; P0 on heuristic 5)+BLOCKING: true (TTR 0.32 indicates AI-generated content; vary vocabulary)+BLOCKING: false (cleared all gates; 92/100 overall, no P0)+```++The reviewer is now a **blocking** gate, not advisory. The user does not see the draft until this line says `false`.## Review Guidelines@@ -183,4 +207,4 @@ When reviewing citations, verify against this tier system:- Be actionable: every issue must have a concrete fix- Be honest: do not inflate scores. A 75 that deserves a 75 is more helpful than a generous 85- Score content you cannot check (page speed, mobile) as N/A and note it-- Count exact statistics, images, charts, headings - do not estimate+- Count exact statistics, images, charts, headings; do not estimatediff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex eee299a..ceb17e1 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -440,7 +440,7 @@ After installation, `claude-blog` occupies this structure inside `~/.claude/`:**Component counts (v1.8.5)**: 1 orchestrator + 29 sub-skills = 30 skill dirstotal, 5 agents (blog-researcher, blog-writer, blog-seo, blog-reviewer,-blog-translator), 20 references in `skills/blog/references/` (plus per-sub-skill+blog-translator), 21 references in `skills/blog/references/` (plus per-sub-skillreferences and 30 synced FLOW prompts under `skills/blog-flow/references/`),12 content templates, 6 root-level scripts (`scripts/analyze_blog.py`,`cognitive_load.py`, `discourse_research.py`, `load_untrusted_root.py`,diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex e893afb..3f8447c 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -19,8 +19,8 @@ Every command is invoked through the main orchestrator| Command | Sub-Skill | Description ||---------|-----------|-------------|-| `write <topic>` | blog-write | Write a new blog post from scratch |-| `rewrite <file>` | blog-rewrite | Optimize an existing blog post |+| `write <topic>` | blog-write | Write a new blog post from scratch (v1.9.0: iterates through the 5-gate delivery contract until score 90+ and zero P0, max 3 iterations) |+| `rewrite <file>` | blog-rewrite | Optimize an existing blog post (v1.9.0: same delivery contract; rewrites must score at least as high as the original) || `analyze <file-or-url>` | blog-analyze | Audit blog quality with 0-100 score || `brief <topic>` | blog-brief | Generate a detailed content brief || `calendar [monthly\|quarterly]` | blog-calendar | Generate an editorial calendar |diff --git a/install.ps1 b/install.ps1index 60eb3dc..81ad40e 100644--- a/install.ps1+++ b/install.ps1@@ -174,7 +174,8 @@ function Main {Write-Color Green " Main skill: blog/ (orchestrator + 20 references + 12 templates)"Write-Color Green " Sub-skills: 30 (29 user-invokable + 1 internal blog-chart)"Write-Color Green " Agents: 5 specialists"- Write-Color Green " Scripts: 6 root-level (analyze_blog, cognitive_load, discourse_research,"+ Write-Color Green " Scripts: 9 root-level (analyze_blog, blog_preflight, blog_render,"+ Write-Color Green " cognitive_load, discourse_research, generate_hero,"Write-Color Green " load_untrusted_root, lint_prose, sync_flow) + per-skill scripts"Write-Color White ""Write-Color White "Commands available:"diff --git a/install.sh b/install.shindex 8304387..ada8212 100755--- a/install.sh+++ b/install.sh@@ -149,7 +149,8 @@ main() {echo " Main skill: blog/ (orchestrator + 20 references + 12 templates)"echo " Sub-skills: 30 (29 user-invokable + 1 internal blog-chart)"echo " Agents: 5 specialists"- echo " Scripts: 6 root-level (analyze_blog, cognitive_load, discourse_research,"+ echo " Scripts: 9 root-level (analyze_blog, blog_preflight, blog_render,"+ echo " cognitive_load, discourse_research, generate_hero,"echo " load_untrusted_root, lint_prose, sync_flow) + per-skill scripts"echo ""echo " Commands available:"diff --git a/pyproject.toml b/pyproject.tomlindex 47defb0..d4c9dc1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -13,7 +13,7 @@ py-modules = [][project]name = "claude-blog"-version = "1.8.6"+version = "1.9.0"description = "AI-powered blog creation and optimization skill for Claude Code"readme = "README.md"license = {text = "MIT"}@@ -59,6 +59,17 @@ ads = [# manifest declaration)."google-ads>=22.0.0,<26.0.0",]+presentation = [+ # v1.9.0 Blog Delivery Contract: enables scripts/blog_preflight.py+ # (Gate 3 visual verification via patchright), scripts/blog_render.py+ # (PDF generation via patchright or weasyprint), and+ # scripts/generate_hero.py (Gemini API hero generation + stock fetch).+ "patchright>=1.40,<2.0",+ "weasyprint>=60,<70",+ "google-genai>=0.5.0,<2.0.0",+ "requests>=2.32.4,<3.0.0",+ "markdown>=3.5,<4.0",+]dev = ["pytest>=8.0,<9.0","textstat>=0.7.3,<1.0.0",diff --git a/scripts/blog_preflight.py b/scripts/blog_preflight.pynew file mode 100644index 0000000..f3244da--- /dev/null+++ b/scripts/blog_preflight.py@@ -0,0 +1,551 @@+#!/usr/bin/env python3+"""Run the Blog Delivery Contract preflight gates against a draft folder.++Implements Gates 1, 2, 3, and 5 of the v1.9.0 Blog Delivery Contract.+Gate 4 (Content Review) is dispatched by the orchestrator as the+blog-reviewer agent; this script only verifies that the agent's output+exists and that its BLOCKING decision is `false`.++Output:+ <draft>/preflight-report.json: machine-readable gate results+ <draft>/capabilities.json: emitted by Gate 1, consumed by 2-5+ <draft>/preview/*.png: emitted by Gate 3 (if patchright installed)++Usage:+ python3 scripts/blog_preflight.py --draft <dir> [--gate N] [--strict] [--json]++ --gate N Run only the named gate (1-5). Default: all 5 sequentially.+ --strict Exit 1 if any gate blocks. Default: on. Use --no-strict to+ proceed regardless (logs the bypass loudly).+ --json Emit the report JSON to stdout in addition to the file.++Exit codes: 0 = all gates passed; 1 = at least one gate blocked+(when --strict). Warnings never block.+"""++from __future__ import annotations++import argparse+import importlib.util+import json+import os+import re+import shutil+import sys+import urllib.parse+import urllib.request+from html.parser import HTMLParser+from pathlib import Path+from typing import Any, Optional++CONTRACT_REF = "skills/blog/references/blog-delivery-contract.md"+REQUIRED_AGENTS = ("blog-reviewer",)+OPTIONAL_AGENTS = ("blog-researcher", "blog-writer", "blog-seo", "blog-translator")+REQUIRED_SCRIPTS = ("scripts/lint_prose.py", "scripts/load_untrusted_root.py", "scripts/analyze_blog.py")+VIEWPORTS = [+ {"name": "mobile", "width": 375, "height": 812},+ {"name": "tablet", "width": 768, "height": 1024},+ {"name": "desktop", "width": 1280, "height": 800},+]+HEAD_TIMEOUT = 10+USER_AGENT = "claude-blog/1.9.0 preflight (+https://github.com/AgriciDaniel/claude-blog)"+URL_ALLOWLIST = ("localhost", "127.0.0.1", "example.com", "example.org")+++def _gate_result(gate: int, name: str, passed: bool, violations: Optional[list] = None, warnings: Optional[list] = None, **kwargs: Any) -> dict:+ return {+ "gate": gate,+ "name": name,+ "passed": passed,+ "violations": violations or [],+ "warnings": warnings or [],+ **kwargs,+ }+++def _has_module(name: str) -> bool:+ return importlib.util.find_spec(name) is not None+++def _project_root() -> Path:+ return Path(__file__).resolve().parent.parent+++def _detect_loaded_mcp() -> list[str]:+ """Best-effort detection. The MCP transport state is not introspectable+ from a subprocess; we report what's declared in .mcp.json. The+ orchestrator's tool availability is the real authority."""+ mcp_path = _project_root() / ".mcp.json"+ if not mcp_path.is_file():+ return []+ try:+ cfg = json.loads(mcp_path.read_text(encoding="utf-8"))+ return list((cfg.get("mcpServers") or {}).keys())+ except Exception:+ return []+++def gate_1_capability_discovery(draft_dir: Path) -> dict:+ """Enumerate available capabilities; write capabilities.json."""+ root = _project_root()+ env_keys = {+ "GOOGLE_AI_API_KEY": bool(os.environ.get("GOOGLE_AI_API_KEY")),+ "UNSPLASH_ACCESS_KEY": bool(os.environ.get("UNSPLASH_ACCESS_KEY")),+ "PEXELS_API_KEY": bool(os.environ.get("PEXELS_API_KEY")),+ "PIXABAY_API_KEY": bool(os.environ.get("PIXABAY_API_KEY")),+ }+ mcp_declared = _detect_loaded_mcp()+ py_deps = {+ "patchright": _has_module("patchright"),+ "playwright": _has_module("playwright"),+ "weasyprint": _has_module("weasyprint"),+ "google.genai": _has_module("google.genai") or _has_module("google_genai"),+ "requests": _has_module("requests"),+ "markdown": _has_module("markdown"),+ }+ project_files = {+ "BRAND.md": (root / "BRAND.md").is_file(),+ "VOICE.md": (root / "VOICE.md").is_file(),+ "DISCOURSE.md": (root / "DISCOURSE.md").is_file(),+ }+ agents = {a: (root / "agents" / f"{a}.md").is_file() for a in REQUIRED_AGENTS + OPTIONAL_AGENTS}+ scripts = {s: (root / s).is_file() for s in REQUIRED_SCRIPTS}++ configured_image_paths = (+ "nanobanana-mcp" in mcp_declared+ or env_keys["GOOGLE_AI_API_KEY"]+ or env_keys["UNSPLASH_ACCESS_KEY"]+ or env_keys["PEXELS_API_KEY"]+ or env_keys["PIXABAY_API_KEY"]+ )+ # Openverse is the no-key fallback at the bottom of the ladder. We do NOT+ # probe its reachability here (network HEAD at gate-1 time is too slow+ # and flaky); we report it as best-effort and let generate_hero.py+ # surface a runtime failure if Openverse is unreachable when invoked.+ image_gen_available = configured_image_paths # explicit configured paths+ openverse_assumed_available = True # best-effort fallback++ capabilities = {+ "mcp_declared": mcp_declared,+ "env_keys_present": env_keys,+ "python_deps": py_deps,+ "project_root_files": project_files,+ "agents": agents,+ "scripts": scripts,+ "image_gen_path_available": image_gen_available,+ "openverse_assumed_available": openverse_assumed_available,+ }+ (draft_dir / "capabilities.json").write_text(json.dumps(capabilities, indent=2), encoding="utf-8")++ violations = []+ warnings = []+ if not agents.get("blog-reviewer", False):+ violations.append("blog-reviewer agent missing; cannot enforce Gate 4")+ if not image_gen_available:+ # No configured image path. Openverse is the best-effort fallback but+ # is not probed for reachability here (D1 from v1.9.0 hostile review:+ # do not short-circuit gate-1 with `or True`). Warn loudly so the+ # operator knows the contract will degrade to Openverse-only.+ warnings.append(+ "no configured image-gen path (Banana MCP / GOOGLE_AI_API_KEY / "+ "UNSPLASH_ACCESS_KEY / PEXELS_API_KEY / PIXABAY_API_KEY). "+ "generate_hero.py will fall through to Openverse (no key required) "+ "and fail at runtime if Openverse is unreachable."+ )+ if not py_deps["patchright"] and not py_deps["playwright"]:+ warnings.append("neither patchright nor playwright installed; Gate 3 will warn-and-pass")+ if not py_deps["weasyprint"] and not py_deps["patchright"] and not py_deps["playwright"]:+ warnings.append("no PDF backend installed (patchright/playwright/weasyprint); PDF generation will fail")++ return _gate_result(1, "Capability Discovery", not violations, violations, warnings, capabilities=capabilities)+++def gate_2_format_completeness(draft_dir: Path) -> dict:+ """Verify .md, .html, .pdf, hero.<ext> all exist."""+ mds = list(draft_dir.glob("*.md"))+ htmls = list(draft_dir.glob("*.html"))+ pdfs = list(draft_dir.glob("*.pdf"))+ heroes = list(draft_dir.glob("hero.*"))+ review = draft_dir / "review.md"++ violations = []+ if not mds:+ violations.append("no .md source found")+ if not htmls:+ violations.append("no .html artifact found (run scripts/blog_render.py)")+ if not pdfs:+ violations.append("no .pdf artifact found (run scripts/blog_render.py)")+ hero_files = [h for h in heroes if h.name != "hero-credit.txt" and h.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}]+ if not hero_files:+ violations.append("no hero.<png|jpg|jpeg|webp> found (run scripts/generate_hero.py)")++ return _gate_result(+ 2, "Format Completeness", not violations, violations, [],+ artifacts={+ "md": [str(p.name) for p in mds],+ "html": [str(p.name) for p in htmls],+ "pdf": [str(p.name) for p in pdfs],+ "hero": [str(p.name) for p in hero_files],+ "review_present": review.is_file(),+ },+ )+++def gate_3_visual_verification(draft_dir: Path) -> dict:+ """Render the .html via patchright (or playwright); screenshot at 3+ widths; check SVG bboxes, dark mode, console errors, JSON-LD."""+ sync_playwright = None+ backend = None+ try:+ from patchright.sync_api import sync_playwright # type: ignore+ backend = "patchright"+ except ImportError:+ try:+ from playwright.sync_api import sync_playwright # type: ignore+ backend = "playwright"+ except ImportError:+ pass+ if sync_playwright is None:+ return _gate_result(+ 3, "Visual Verification", True, [],+ ["neither patchright nor playwright installed; skipping visual checks. Run pip install -e .[presentation] to enable."],+ )++ htmls = list(draft_dir.glob("*.html"))+ if not htmls:+ return _gate_result(3, "Visual Verification", False, ["no .html artifact to verify"])++ html_path = htmls[0]+ preview_dir = draft_dir / "preview"+ preview_dir.mkdir(exist_ok=True)++ violations = []+ warnings = [f"backend: {backend}"]+ per_viewport: dict = {}++ bbox_check_js = """+() => {+ const overflows = [];+ const svgs = document.querySelectorAll('svg');+ svgs.forEach((svg, i) => {+ const svgBox = svg.getBoundingClientRect();+ const desc = svg.querySelectorAll('text, path, rect, image, circle, line');+ desc.forEach((child) => {+ const r = child.getBoundingClientRect();+ const margin = 2;+ if (r.left < svgBox.left - margin || r.right > svgBox.right + margin ||+ r.top < svgBox.top - margin || r.bottom > svgBox.bottom + margin) {+ overflows.push({svgIndex: i, tag: child.tagName, content: (child.textContent||'').slice(0,40),+ childBox:{l:r.left,r:r.right,t:r.top,b:r.bottom},+ svgBox:{l:svgBox.left,r:svgBox.right,t:svgBox.top,b:svgBox.bottom}});+ }+ });+ });+ const bg = getComputedStyle(document.body).backgroundColor;+ const jsonLd = document.querySelector('script[type="application/ld+json"]');+ let jsonLdValid = false, jsonLdType = null, jsonLdMissingFields = [];+ if (jsonLd) {+ try {+ const obj = JSON.parse(jsonLd.textContent);+ jsonLdValid = true;+ jsonLdType = obj['@type'];+ const required = ['headline','image','datePublished','author'];+ jsonLdMissingFields = required.filter(k => !obj[k]);+ } catch (e) { jsonLdValid = false; }+ }+ return {overflows, bg, jsonLdValid, jsonLdType, jsonLdMissingFields};+}+""".strip()++ try:+ with sync_playwright() as p:+ browser = p.chromium.launch()+ for vp in VIEWPORTS:+ context = browser.new_context(viewport={"width": vp["width"], "height": vp["height"]})+ page = context.new_page()+ console_errors: list[str] = []+ page.on("console", lambda msg: console_errors.append(msg.text) if msg.type == "error" else None)+ page.goto(f"file://{html_path.resolve()}", wait_until="networkidle", timeout=30_000)+ page.screenshot(path=str(preview_dir / f"{vp['name']}-{vp['width']}.png"), full_page=True)+ result = page.evaluate(bbox_check_js)+ per_viewport[vp["name"]] = {"result": result, "console_errors": console_errors}+ if result["overflows"]:+ violations.append(f"{vp['name']}: {len(result['overflows'])} SVG overflow(s)")+ if console_errors:+ violations.append(f"{vp['name']}: {len(console_errors)} console error(s)")+ if not result["jsonLdValid"]:+ violations.append(f"{vp['name']}: JSON-LD invalid or missing")+ elif result["jsonLdType"] != "BlogPosting":+ violations.append(f"{vp['name']}: JSON-LD @type != BlogPosting")+ elif result["jsonLdMissingFields"]:+ violations.append(f"{vp['name']}: JSON-LD missing fields: {result['jsonLdMissingFields']}")+ context.close()++ # Dark mode pass at desktop width+ context = browser.new_context(viewport={"width": 1280, "height": 800}, color_scheme="dark")+ page = context.new_page()+ page.goto(f"file://{html_path.resolve()}", wait_until="networkidle", timeout=30_000)+ dark_bg = page.evaluate("() => getComputedStyle(document.body).backgroundColor")+ light_bg = per_viewport["desktop"]["result"]["bg"]+ page.screenshot(path=str(preview_dir / "desktop-1280-dark.png"), full_page=True)+ if dark_bg == light_bg:+ violations.append(f"dark mode did not change background color (still {dark_bg})")+ per_viewport["desktop-dark"] = {"bg": dark_bg, "light_bg": light_bg}+ context.close()+ browser.close()+ except Exception as e:+ return _gate_result(3, "Visual Verification", False, [f"patchright runtime error: {e}"])++ return _gate_result(3, "Visual Verification", not violations, violations, warnings, per_viewport=per_viewport)+++class _MetaParser(HTMLParser):+ def __init__(self):+ super().__init__()+ self.imgs: list[str] = []+ self.links: list[str] = []+ self.codes: list[str] = []+ self.og_image: Optional[str] = None+ self.canonical: Optional[str] = None+ self.json_ld_blocks: list[str] = []+ self._in_jsonld = False+ self._in_article = False+ self._in_code = False+ self._in_header = False+ self._in_footer = False+ self.article_text_chars = 0++ def handle_starttag(self, tag, attrs):+ d = dict(attrs)+ if tag == "img" and d.get("src"):+ self.imgs.append(d["src"])+ elif tag == "a" and d.get("href"):+ self.links.append(d["href"])+ elif tag == "meta" and d.get("property") == "og:image" and d.get("content"):+ self.og_image = d["content"]+ elif tag == "link" and d.get("rel") == "canonical" and d.get("href"):+ self.canonical = d["href"]+ elif tag == "script" and d.get("type") == "application/ld+json":+ self._in_jsonld = True+ elif tag == "article":+ self._in_article = True+ elif tag == "header":+ self._in_header = True+ elif tag == "footer":+ self._in_footer = True+ elif tag == "code":+ self._in_code = True++ def handle_endtag(self, tag):+ if tag == "script":+ self._in_jsonld = False+ elif tag == "article":+ self._in_article = False+ elif tag == "header":+ self._in_header = False+ elif tag == "footer":+ self._in_footer = False+ elif tag == "code":+ self._in_code = False++ def handle_data(self, data):+ if self._in_jsonld:+ self.json_ld_blocks.append(data)+ if self._in_code and self._in_article:+ self.codes.append(data.strip())+ # Count body-only words: exclude <header> (title, byline), <footer>+ # (site/date), and <code> blocks. Aligned with blog_render.py's+ # wordCount semantics so Gate 5 catches real drift, not template+ # boilerplate (v1.9.0 audit fix).+ if (self._in_article and not self._in_code+ and not self._in_header and not self._in_footer):+ self.article_text_chars += len(re.findall(r"\b\w+\b", data))+++def _http_head(url: str) -> int:+ try:+ req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": USER_AGENT})+ with urllib.request.urlopen(req, timeout=HEAD_TIMEOUT) as resp:+ return resp.status+ except Exception:+ return 0+++def _is_allowed_unreachable(url: str) -> bool:+ parsed = urllib.parse.urlparse(url)+ return any(part in parsed.netloc for part in URL_ALLOWLIST)+++def gate_5_asset_link_integrity(draft_dir: Path) -> dict:+ """Verify all <img> resolve, all <a> return 200, schema validates,+ word count within +/-5%."""+ htmls = list(draft_dir.glob("*.html"))+ if not htmls:+ return _gate_result(5, "Asset + Link Integrity", False, ["no .html artifact to verify"])++ html_path = htmls[0]+ raw = html_path.read_text(encoding="utf-8")+ parser = _MetaParser()+ parser.feed(raw)++ violations = []+ warnings = []++ # img src resolution+ for src in parser.imgs:+ if src.startswith("http://") or src.startswith("https://"):+ if _is_allowed_unreachable(src):+ continue+ if _http_head(src) != 200:+ warnings.append(f"img src returned non-200: {src}")+ else:+ local = (draft_dir / src).resolve()+ if not local.exists():+ violations.append(f"img src not on disk: {src}")++ # og:image specifically must resolve to a local hero.<ext> when canonical points to a host+ if parser.og_image:+ if parser.og_image.startswith("http"):+ hero_files = list(draft_dir.glob("hero.*"))+ hero_files = [h for h in hero_files if h.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}]+ if not hero_files:+ violations.append(f"og:image declared {parser.og_image} but no hero.<ext> exists locally")++ # canonical present+ if not parser.canonical:+ warnings.append("no <link rel=canonical> in document")++ # External links: explicit http/https allowlist. Other schemes (file://,+ # gopher://, ftp://, javascript:) are flagged as violations rather than+ # silently skipped (S3 from v1.9.0 hostile review). Relative/anchor links+ # without a scheme are left to Gate 5's img-src check above.+ for href in parser.links:+ if href.startswith(("http://", "https://")):+ if _is_allowed_unreachable(href):+ continue+ status = _http_head(href)+ if status == 0 or status >= 400:+ warnings.append(f"link returned {status}: {href}")+ continue+ if "://" in href or href.startswith(("javascript:", "data:", "vbscript:")):+ violations.append(+ f"non-http(s) URL scheme is not allowed in published links: {href}"+ )++ # JSON-LD validation+ json_ld_ok = False+ declared_word_count: Optional[int] = None+ if parser.json_ld_blocks:+ try:+ obj = json.loads("".join(parser.json_ld_blocks))+ json_ld_ok = True+ required = ("headline", "image", "datePublished", "author")+ missing = [k for k in required if not obj.get(k)]+ if missing:+ violations.append(f"JSON-LD missing required fields: {missing}")+ declared_word_count = obj.get("wordCount")+ except json.JSONDecodeError as e:+ violations.append(f"JSON-LD invalid: {e}")+ else:+ violations.append("no JSON-LD <script> block present")++ # word count match+ if declared_word_count is not None:+ actual = parser.article_text_chars+ if actual > 0:+ diff_pct = abs(declared_word_count - actual) / actual * 100+ if diff_pct > 5:+ violations.append(f"JSON-LD wordCount {declared_word_count} differs from actual {actual} by {diff_pct:.1f}%")++ return _gate_result(+ 5, "Asset + Link Integrity", not violations, violations, warnings,+ imgs=parser.imgs, links_checked=len(parser.links),+ json_ld_valid=json_ld_ok, declared_word_count=declared_word_count,+ actual_word_count=parser.article_text_chars,+ )+++def gate_4_content_review(draft_dir: Path) -> dict:+ """Check that the blog-reviewer agent has run and emitted review.md+ with `BLOCKING: false`. The agent itself is dispatched by the+ orchestrator, not by this script."""+ review = draft_dir / "review.md"+ if not review.is_file():+ return _gate_result(+ 4, "Content Review", False,+ ["review.md absent; orchestrator must dispatch blog-reviewer agent before preflight Gate 4"],+ )+ text = review.read_text(encoding="utf-8")+ m = re.search(r"^BLOCKING:\s*(true|false)\s*(?:\((.*?)\))?\s*$", text, re.IGNORECASE | re.MULTILINE)+ if not m:+ return _gate_result(+ 4, "Content Review", False,+ ["review.md present but no `BLOCKING: true|false` line found at end of scorecard"],+ )+ blocking = m.group(1).lower() == "true"+ reason = (m.group(2) or "").strip()+ if blocking:+ return _gate_result(4, "Content Review", False, [f"reviewer blocked: {reason or 'see review.md'}"], [], blocking=True, reason=reason)+ return _gate_result(4, "Content Review", True, [], [], blocking=False, reason=reason)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--draft", required=True, help="Draft folder containing the .md/.html/.pdf/hero artifacts")+ parser.add_argument("--gate", type=int, choices=[1, 2, 3, 4, 5], help="Run only this gate (default: all)")+ parser.add_argument("--strict", dest="strict", action="store_true", default=True)+ parser.add_argument("--no-strict", dest="strict", action="store_false")+ parser.add_argument("--json", action="store_true", help="Emit report JSON to stdout")+ args = parser.parse_args()++ draft = Path(args.draft).resolve()+ if not draft.is_dir():+ print(f"ERROR: {draft} is not a directory", file=sys.stderr)+ return 1++ gates = [+ (1, gate_1_capability_discovery),+ (2, gate_2_format_completeness),+ (3, gate_3_visual_verification),+ (4, gate_4_content_review),+ (5, gate_5_asset_link_integrity),+ ]+ if args.gate:+ gates = [(n, fn) for (n, fn) in gates if n == args.gate]++ results: list[dict] = []+ blocked = False+ for n, fn in gates:+ r = fn(draft)+ results.append(r)+ if not r["passed"]:+ blocked = True++ report = {+ "draft": str(draft),+ "strict": args.strict,+ "blocked": blocked,+ "gates": results,+ }+ (draft / "preflight-report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")++ if args.json:+ print(json.dumps(report))+ else:+ for r in results:+ mark = "PASS" if r["passed"] else "FAIL"+ print(f"[{mark}] Gate {r['gate']}: {r['name']}")+ for v in r.get("violations", []):+ print(f" violation: {v}")+ for w in r.get("warnings", []):+ print(f" warning: {w}")+ if blocked and not args.strict:+ print("WARNING: contract bypassed via --no-strict; do not publish without manual review.", file=sys.stderr)++ if blocked and args.strict:+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/blog_render.py b/scripts/blog_render.pynew file mode 100644index 0000000..cc58777--- /dev/null+++ b/scripts/blog_render.py@@ -0,0 +1,503 @@+#!/usr/bin/env python3+"""Render a blog post markdown to .html and .pdf deterministically.++Reads a single .md file plus its frontmatter, emits:+ <out-dir>/<slug>.html: self-contained, dark-mode-aware, JSON-LD,+ Open Graph + Twitter Card, references hero.<ext> from the same dir.+ <out-dir>/<slug>.pdf: via patchright `page.pdf()` (preferred) or+ weasyprint fallback (only if patchright is unavailable).++This is the Gate 2 (Format Completeness) implementation of the v1.9.0+Blog Delivery Contract. Same source produces both outputs so they cannot+diverge.++Usage:+ python3 scripts/blog_render.py --md <path.md> --out-dir <dir> \\+ [--pdf-engine playwright|weasyprint|auto] [--json]++Returns 0 on success, 1 on render error or missing required artifact.+"""++from __future__ import annotations++import argparse+import html as html_lib+import json+import errno+import os+import re+import stat+import sys+from datetime import datetime, timezone+from pathlib import Path+from typing import Optional++MAX_MD_BYTES = 4 * 1024 * 1024 # 4MB cap on a single markdown source+REQUIRED_FRONTMATTER_KEYS = ("title", "description", "date", "author")+# Markdown syntax fingerprints handled by python-markdown but NOT by the+# stdlib fallback in _stdlib_markdown. If the fallback path is taken AND+# any of these patterns appear in the body, the fallback emits a loud+# stderr warning so a silent-lossy render cannot ship undetected.+_LOSSY_FALLBACK_PATTERNS = {+ "table": re.compile(r"^\s*\|.+\|\s*$", re.MULTILINE),+ "footnote": re.compile(r"\[\^[^\]]+\]"),+ "definition_list": re.compile(r"^[^\n:]+\n:\s+", re.MULTILINE),+ "fenced_code_with_language": re.compile(r"^```[a-zA-Z0-9_+-]+", re.MULTILINE),+}++HTML_TEMPLATE = """<!DOCTYPE html>+<html lang="{lang}">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0">+<meta name="theme-color" content="#0d9488" media="(prefers-color-scheme: light)">+<meta name="theme-color" content="#18181b" media="(prefers-color-scheme: dark)">+<title>{title_escaped}</title>+<meta name="description" content="{description_escaped}">+{canonical_tag}+<meta name="author" content="{author_escaped}">+<meta name="robots" content="index, follow, max-image-preview:large">+<meta property="og:type" content="article">+<meta property="og:title" content="{title_escaped}">+<meta property="og:description" content="{description_escaped}">+{og_url_tag}+<meta property="og:image" content="{og_image}">+<meta property="og:image:width" content="1200">+<meta property="og:image:height" content="630">+<meta property="og:image:alt" content="{og_image_alt_escaped}">+<meta property="og:site_name" content="{site_name_escaped}">+<meta property="article:published_time" content="{published_iso}">+<meta property="article:author" content="{author_escaped}">+<meta name="twitter:card" content="summary_large_image">+<meta name="twitter:title" content="{title_escaped}">+<meta name="twitter:description" content="{description_escaped}">+<meta name="twitter:image" content="{og_image}">+<script type="application/ld+json">{json_ld}</script>+<style>{css}</style>+</head>+<body>+<article>+<header>+<p class="kicker">{kicker_escaped}</p>+<h1>{title_escaped}</h1>+<p class="dek">{description_escaped}</p>+<p class="byline"><strong>By {author_escaped}</strong> · {published_human} · {reading_time_min} min read · {word_count} words</p>+</header>+<figure class="hero"><img src="{hero_filename}" alt="{og_image_alt_escaped}" width="1200" height="630"></figure>+{body_html}+<footer class="post-footer"><span>Published at <a href="{site_url_or_dash}">{site_name_escaped}</a></span><span>{published_human} · {author_escaped}</span></footer>+</article>+</body>+</html>+"""++CSS = """+:root{--bg:#fafaf9;--surface:#fff;--text:#1c1917;--muted:#57534e;--soft:#78716c;--accent:#0d9488;--accent-soft:#ccfbf1;--accent-deep:#115e59;--border:#e7e5e4;--code-bg:#f5f5f4;--warn:#b91c1c;--shadow:0 1px 3px rgba(0,0,0,.06),0 4px 12px rgba(0,0,0,.04)}+@media (prefers-color-scheme:dark){:root{--bg:#18181b;--surface:#27272a;--text:#fafafa;--muted:#a1a1aa;--soft:#71717a;--accent:#2dd4bf;--accent-soft:#134e4a;--accent-deep:#99f6e4;--border:#3f3f46;--code-bg:#1f1f23;--warn:#fca5a5;--shadow:0 1px 3px rgba(0,0,0,.4),0 4px 12px rgba(0,0,0,.3)}}+*,*::before,*::after{box-sizing:border-box}+html{-webkit-text-size-adjust:100%;scroll-behavior:smooth}+body{background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;line-height:1.65;margin:0;font-size:17px;-webkit-font-smoothing:antialiased}+article{max-width:740px;margin:0 auto;padding:3rem 1.5rem 5rem}+.kicker{font-family:ui-monospace,"SF Mono",Monaco,monospace;font-size:.78rem;letter-spacing:.12em;text-transform:uppercase;color:var(--accent);margin:0 0 .85rem;font-weight:600}+h1{font-size:clamp(2rem,5vw,2.85rem);line-height:1.12;letter-spacing:-.025em;margin:0 0 1.1rem;font-weight:800}+.dek{color:var(--muted);font-size:clamp(1.05rem,2.5vw,1.2rem);line-height:1.5;margin:0 0 1.75rem;max-width:60ch}+.byline{color:var(--soft);font-size:.875rem;font-family:ui-monospace,monospace;margin:0 0 2.5rem}+.byline strong{color:var(--text);font-weight:600}+.hero{margin:0 0 2.5rem;background:var(--surface);border:1px solid var(--border);border-radius:14px;overflow:hidden;box-shadow:var(--shadow)}+.hero img{display:block;width:100%;height:auto;aspect-ratio:1200/630;object-fit:cover}+h2{font-size:clamp(1.4rem,3vw,1.75rem);line-height:1.22;letter-spacing:-.015em;margin:3rem 0 1rem;font-weight:700;scroll-margin-top:1rem}+h3{font-size:1.2rem;margin:2rem 0 .75rem;font-weight:700}+p{margin:0 0 1.25rem}+a{color:var(--accent);text-decoration-thickness:1px;text-underline-offset:3px}+a:hover{color:var(--accent-deep)}+code{font-family:ui-monospace,"SF Mono",Monaco,monospace;font-size:.9em;background:var(--code-bg);border:1px solid var(--border);padding:.1em .4em;border-radius:4px}+pre{background:var(--code-bg);border:1px solid var(--border);border-radius:8px;padding:1rem;overflow-x:auto;font-size:.875rem}+pre code{background:none;border:none;padding:0}+blockquote{border-left:3px solid var(--accent);padding:.4rem 0 .4rem 1.25rem;margin:0 0 1.5rem;color:var(--muted)}+ul,ol{margin:0 0 1.25rem;padding-left:1.5rem}+li{margin:.35rem 0}+strong{font-weight:700;color:var(--text)}+img{max-width:100%;height:auto}+.post-footer{margin-top:4rem;padding-top:2rem;border-top:1px solid var(--border);font-size:.875rem;color:var(--muted);font-family:ui-monospace,monospace;display:flex;flex-wrap:wrap;gap:.6rem 1.5rem;justify-content:space-between}+.post-footer a{color:var(--accent);text-decoration:none}+::selection{background:var(--accent);color:var(--bg)}+@media print{body{background:#fff;color:#000;font-size:11pt}article{max-width:none;padding:0 1rem}.hero{box-shadow:none}}+@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}+"""+++def _slugify(text: str) -> str:+ s = text.lower().strip()+ s = re.sub(r"[^a-z0-9\s\-]", "", s)+ s = re.sub(r"\s+", "-", s)+ s = re.sub(r"-+", "-", s)+ return s.strip("-") or "post"+++def _parse_frontmatter(raw: str) -> tuple[dict, str]:+ """Minimal YAML frontmatter parser. Supports flat key: value and simple lists."""+ if not raw.startswith("---"):+ return {}, raw+ end = raw.find("\n---", 3)+ if end == -1:+ return {}, raw+ fm_text = raw[3:end].strip("\n")+ body = raw[end + 4:].lstrip("\n")+ fm: dict = {}+ current_list_key: Optional[str] = None+ for line in fm_text.split("\n"):+ if not line.strip() or line.lstrip().startswith("#"):+ continue+ if line.startswith(" - ") and current_list_key:+ fm.setdefault(current_list_key, []).append(line[4:].strip().strip('"').strip("'"))+ continue+ if ":" in line:+ key, _, value = line.partition(":")+ key = key.strip()+ value = value.strip()+ if not value:+ current_list_key = key+ fm[key] = []+ else:+ current_list_key = None+ fm[key] = value.strip('"').strip("'")+ return fm, body+++def _markdown_to_html(body: str) -> str:+ """Convert markdown body to HTML. Uses python-markdown if installed,+ else a minimal stdlib subset (ATX headings, paragraphs, code, links,+ emphasis, lists, blockquotes, hr, images)."""+ try:+ import markdown # type: ignore+ return markdown.markdown(body, extensions=["extra", "sane_lists"])+ except ImportError:+ return _stdlib_markdown(body)+++def _stdlib_markdown(body: str) -> str:+ lines = body.split("\n")+ out: list[str] = []+ in_code = False+ code_buf: list[str] = []+ para_buf: list[str] = []+ in_list = False+ list_tag = "ul"++ def flush_para():+ if para_buf:+ text = " ".join(para_buf).strip()+ if text:+ out.append(f"<p>{_inline(text)}</p>")+ para_buf.clear()++ def flush_list():+ nonlocal in_list+ if in_list:+ out.append(f"</{list_tag}>")+ in_list = False++ for line in lines:+ stripped = line.rstrip()+ if stripped.startswith("```"):+ if in_code:+ out.append("<pre><code>" + html_lib.escape("\n".join(code_buf)) + "</code></pre>")+ code_buf.clear()+ in_code = False+ else:+ flush_para()+ flush_list()+ in_code = True+ continue+ if in_code:+ code_buf.append(line)+ continue+ if not stripped:+ flush_para()+ flush_list()+ continue+ h = re.match(r"^(#{1,6})\s+(.+)$", stripped)+ if h:+ flush_para()+ flush_list()+ level = len(h.group(1))+ out.append(f"<h{level}>{_inline(h.group(2))}</h{level}>")+ continue+ if stripped.startswith("> "):+ flush_para()+ flush_list()+ out.append(f"<blockquote><p>{_inline(stripped[2:])}</p></blockquote>")+ continue+ if stripped in ("---", "***", "___"):+ flush_para()+ flush_list()+ out.append("<hr>")+ continue+ ol_match = re.match(r"^\d+\.\s+(.+)$", stripped)+ ul_match = re.match(r"^[-*+]\s+(.+)$", stripped)+ if ul_match or ol_match:+ flush_para()+ new_tag = "ol" if ol_match else "ul"+ if in_list and list_tag != new_tag:+ flush_list()+ if not in_list:+ list_tag = new_tag+ out.append(f"<{list_tag}>")+ in_list = True+ content = (ol_match or ul_match).group(1)+ out.append(f"<li>{_inline(content)}</li>")+ continue+ para_buf.append(stripped)++ flush_para()+ flush_list()+ return "\n".join(out)+++def _inline(text: str) -> str:+ """Inline markdown: code, bold, italic, links, images. Operates on+ text where the outer block (heading/paragraph/li) is already established."""+ # Escape HTML first+ text = html_lib.escape(text, quote=False)+ # Images: + text = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r'<img src="\2" alt="\1">', text)+ # Links: [text](url)+ text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)+ # Inline code: `code`+ text = re.sub(r"`([^`]+)`", r"<code>\1</code>", text)+ # Bold: **text**+ text = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", text)+ # Italic: *text*+ text = re.sub(r"(?<!\*)\*([^*]+)\*(?!\*)", r"<em>\1</em>", text)+ return text+++def _build_json_ld(fm: dict, word_count: int, og_image_url: str) -> str:+ data = {+ "@context": "https://schema.org",+ "@type": "BlogPosting",+ "headline": fm.get("title", ""),+ "description": fm.get("description", ""),+ "image": og_image_url,+ "datePublished": fm.get("date", ""),+ "dateModified": fm.get("date", ""),+ "author": {"@type": "Person", "name": fm.get("author", "")},+ "wordCount": word_count,+ "keywords": ", ".join(fm.get("tags", [])) if isinstance(fm.get("tags"), list) else fm.get("tags", ""),+ "inLanguage": fm.get("lang", "en"),+ }+ if fm.get("canonical"):+ data["mainEntityOfPage"] = {"@type": "WebPage", "@id": fm["canonical"]}+ # HTML-safe JSON encoding: escape "</" as "<\/" so an attacker who controls+ # a frontmatter value (e.g. title) cannot inject a literal "</script>" that+ # would break out of the surrounding <script type="application/ld+json">+ # block and execute arbitrary JS. "\/" is a valid JSON escape for "/",+ # so the embedded JSON remains semantically identical for any parser.+ return json.dumps(data, ensure_ascii=False).replace("</", "<\\/")+++def _read_md_safely(path: Path) -> str:+ """Read a markdown source with symlink refusal + size cap. Mirrors the+ O_NOFOLLOW pattern used by scripts/load_untrusted_root.py for project-+ root files so a caller cannot redirect the renderer at an attacker-+ chosen target via symlink."""+ try:+ fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW)+ except OSError as e:+ if e.errno in (errno.ELOOP, errno.EMLINK):+ raise ValueError(f"refusing to follow symlink: {path}")+ raise+ try:+ st = os.fstat(fd)+ if not stat.S_ISREG(st.st_mode):+ raise ValueError(f"not a regular file: {path}")+ if st.st_size > MAX_MD_BYTES:+ raise ValueError(f"source markdown exceeds {MAX_MD_BYTES} bytes")+ data = os.read(fd, MAX_MD_BYTES + 1)+ finally:+ os.close(fd)+ if len(data) > MAX_MD_BYTES:+ raise ValueError(f"source markdown exceeds {MAX_MD_BYTES} bytes")+ return data.decode("utf-8")+++def _validate_frontmatter(fm: dict, body: str) -> None:+ """Reject empty body or missing required frontmatter keys. The renderer+ must not silently produce a content-less HTML shell with a title taken+ from the filename stem (F1, F2 from the v1.9.0 hostile review)."""+ missing = [k for k in REQUIRED_FRONTMATTER_KEYS if not str(fm.get(k, "")).strip()]+ if missing:+ raise ValueError(+ f"missing or empty required frontmatter key(s): {missing}. "+ f"Required: {list(REQUIRED_FRONTMATTER_KEYS)}."+ )+ if not body.strip():+ raise ValueError(+ "markdown body is empty (after frontmatter). The renderer refuses "+ "to produce a content-less HTML shell."+ )+++def _warn_if_stdlib_fallback_is_lossy(body: str) -> None:+ """If python-markdown is not importable AND the body contains syntax the+ stdlib fallback drops on the floor (tables, footnotes, def lists,+ language-tagged fenced code blocks), emit a loud stderr warning so the+ user notices the fidelity loss instead of shipping silently-lossy HTML."""+ try:+ import markdown # noqa: F401 # type: ignore+ return # python-markdown handles all of these+ except ImportError:+ pass+ hits = []+ for name, pattern in _LOSSY_FALLBACK_PATTERNS.items():+ if pattern.search(body):+ hits.append(name)+ if hits:+ print(+ "WARN: python-markdown not installed; the stdlib fallback will "+ f"drop or mis-render: {sorted(hits)}. Install with "+ "`pip install -e .[presentation]` for full fidelity.",+ file=sys.stderr,+ )+++def _render_html(md_path: Path, out_dir: Path, hero_filename: str) -> Path:+ raw = _read_md_safely(md_path)+ fm, body = _parse_frontmatter(raw)+ _validate_frontmatter(fm, body)+ _warn_if_stdlib_fallback_is_lossy(body)++ body_html = _markdown_to_html(body)+ # Strip a leading <h1> from the body if the template already provides+ # the title as H1 from frontmatter (prevents duplicate-H1 SEO defect).+ # Use .*? with DOTALL so inline formatting (<strong>, <em>, <code>) inside+ # the H1 is still recognised; count=1 so only the leading H1 is stripped,+ # never a legitimate mid-document H1.+ body_html = re.sub(r"\A\s*<h1\b[^>]*>.*?</h1>\s*", "", body_html, count=1, flags=re.DOTALL)+ # Word count from rendered visible text. Must match what Gate 5 measures+ # from <article> so the wordCount injected into JSON-LD does not drift+ # past the 5% tolerance and falsely block delivery. Gate 5's _MetaParser+ # in blog_preflight.py excludes <code> content; we exclude <pre>/<code>+ # blocks here too. Counting code-block tokens as prose words causes+ # ~15-20% over-count on docs that contain code samples (real defect+ # caught by the v1.9.0 audit's end-to-end test).+ visible_text = re.sub(r"<pre[^>]*>.*?</pre>", " ", body_html, flags=re.DOTALL)+ visible_text = re.sub(r"<code[^>]*>.*?</code>", " ", visible_text, flags=re.DOTALL)+ visible_text = re.sub(r"<[^>]+>", " ", visible_text)+ visible_text = html_lib.unescape(visible_text)+ word_count = len(re.findall(r"\b\w+\b", visible_text))+ reading_time = max(1, word_count // 200)++ canonical = fm.get("canonical", "")+ title = fm.get("title", md_path.stem)+ site_name = fm.get("site_name") or (canonical.split("/")[2] if canonical.startswith("http") else "")+ site_url = "/".join(canonical.split("/")[:3]) if canonical.startswith("http") else ""+ og_image = canonical.rstrip("/") + "/" + hero_filename if canonical else hero_filename++ rendered = HTML_TEMPLATE.format(+ lang=fm.get("lang", "en"),+ title_escaped=html_lib.escape(title),+ description_escaped=html_lib.escape(fm.get("description", "")),+ canonical_tag=f'<link rel="canonical" href="{html_lib.escape(canonical)}">' if canonical else "",+ author_escaped=html_lib.escape(fm.get("author", "Anonymous")),+ og_url_tag=f'<meta property="og:url" content="{html_lib.escape(canonical)}">' if canonical else "",+ og_image=html_lib.escape(og_image),+ og_image_alt_escaped=html_lib.escape(fm.get("og_image_alt", title)),+ site_name_escaped=html_lib.escape(site_name or "Blog"),+ published_iso=fm.get("date", datetime.now(timezone.utc).strftime("%Y-%m-%d")),+ published_human=fm.get("date", datetime.now(timezone.utc).strftime("%Y-%m-%d")),+ reading_time_min=reading_time,+ word_count=word_count,+ kicker_escaped=html_lib.escape(fm.get("kicker") or (fm.get("tags")[0].title() if isinstance(fm.get("tags"), list) and fm.get("tags") else "Article")),+ hero_filename=html_lib.escape(hero_filename),+ body_html=body_html,+ site_url_or_dash=html_lib.escape(site_url or "#"),+ json_ld=_build_json_ld(fm, word_count, og_image),+ css=CSS,+ )++ slug = fm.get("slug") or _slugify(title)+ out_html = out_dir / f"{slug}.html"+ out_html.write_text(rendered, encoding="utf-8")+ return out_html+++def _render_pdf(html_path: Path, out_pdf: Path, engine: str) -> bool:+ """Render html_path to out_pdf via the chosen engine. Returns True on+ success, False on failure (no exception raised; caller decides)."""+ if engine in ("auto", "playwright"):+ sync_playwright = None+ try:+ from patchright.sync_api import sync_playwright # type: ignore+ except ImportError:+ try:+ from playwright.sync_api import sync_playwright # type: ignore+ except ImportError:+ pass+ if sync_playwright is not None:+ try:+ with sync_playwright() as p:+ browser = p.chromium.launch()+ page = browser.new_page()+ page.goto(f"file://{html_path.resolve()}", wait_until="networkidle")+ page.pdf(path=str(out_pdf), format="A4", print_background=True)+ browser.close()+ return True+ except Exception as e:+ print(f"[render] playwright/patchright failed: {e}", file=sys.stderr)+ if engine == "playwright":+ return False+ if engine in ("auto", "weasyprint"):+ try:+ from weasyprint import HTML # type: ignore+ HTML(filename=str(html_path)).write_pdf(str(out_pdf))+ return True+ except Exception as e:+ print(f"[render] weasyprint failed: {e}", file=sys.stderr)+ return False+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--md", required=True, help="Path to markdown source file")+ parser.add_argument("--out-dir", required=True, help="Output directory for .html and .pdf")+ parser.add_argument("--hero", default="hero.png", help="Hero image filename (relative to out-dir)")+ parser.add_argument("--pdf-engine", choices=["auto", "playwright", "weasyprint", "none"], default="auto")+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args()++ # Do NOT call .resolve() here: that would silently follow symlinks before+ # _read_md_safely (which uses O_NOFOLLOW) gets a chance to refuse them.+ # Use .absolute() to get an unambiguous path that preserves symlink ID.+ md_path = Path(args.md).absolute()+ if not md_path.is_file() and not md_path.is_symlink():+ print(f"ERROR: {md_path} not a file", file=sys.stderr)+ return 1+ out_dir = Path(args.out_dir).resolve()+ out_dir.mkdir(parents=True, exist_ok=True)++ try:+ html_path = _render_html(md_path, out_dir, args.hero)+ except Exception as e:+ print(f"ERROR: html render failed: {e}", file=sys.stderr)+ return 1++ result = {"html": str(html_path), "pdf": None}+ if args.pdf_engine != "none":+ pdf_path = html_path.with_suffix(".pdf")+ if _render_pdf(html_path, pdf_path, args.pdf_engine):+ result["pdf"] = str(pdf_path)++ if args.json:+ print(json.dumps(result))+ else:+ print(f"OK: {html_path}")+ if result["pdf"]:+ print(f"OK: {result['pdf']}")+ else:+ print("WARN: PDF render skipped or failed", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/generate_hero.py b/scripts/generate_hero.pynew file mode 100644index 0000000..99125fe--- /dev/null+++ b/scripts/generate_hero.py@@ -0,0 +1,357 @@+#!/usr/bin/env python3+"""Generate or fetch a 1200x630 hero image for a blog post.++Implements the v1.9.0 Blog Delivery Contract hero-image ladder. The+orchestrator handles step 1 (Banana MCP) when available; this script+handles steps 2-4 and produces the final `hero.<ext>` + `hero-credit.txt`+in the requested output directory.++Ladder:+ 1. (Orchestrator only) Banana MCP via nanobanana-mcp+ 2. Direct Gemini API via google-genai SDK (requires GOOGLE_AI_API_KEY)+ 3. Premium stock APIs: Unsplash, Pexels, Pixabay (any one key suffices)+ 4. Openverse public API (CC-licensed; no key required)+ 5. Exit nonzero with setup instructions++Usage:+ python3 scripts/generate_hero.py --topic "<title>" --tags "a,b,c" \\+ --out <draft-folder> [--width 1200] [--height 630] [--json]++Returns 0 on success (hero.<ext> + hero-credit.txt written). Returns 1+when every ladder step is exhausted with no successful generation.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import tempfile+import urllib.parse+import urllib.request+from pathlib import Path+from typing import Callable, Optional++OUTPUT_FILE_PREFIX = "hero"+DEFAULT_WIDTH = 1200+DEFAULT_HEIGHT = 630+DEFAULT_GEMINI_MODEL = os.environ.get("NANOBANANA_MODEL", "gemini-3.1-flash-image-preview")+OPENVERSE_API = "https://api.openverse.engineering/v1/images/"+UNSPLASH_API = "https://api.unsplash.com/search/photos"+PEXELS_API = "https://api.pexels.com/v1/search"+PIXABAY_API = "https://pixabay.com/api/"+USER_AGENT = "claude-blog/1.9.0 (+https://github.com/AgriciDaniel/claude-blog)"+HTTP_TIMEOUT = 20+++def _atomic_write_bytes(path: Path, data: bytes) -> None:+ """Atomic write via mkstemp + os.replace. Mirrors load_untrusted_root.py."""+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")+ try:+ with os.fdopen(fd, "wb") as f:+ f.write(data)+ os.replace(tmp, str(path))+ except Exception:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+++def _build_prompt(topic: str, tags: list[str]) -> str:+ parts = [+ f"Editorial illustration for a blog post titled '{topic}'.",+ ]+ if tags:+ parts.append(f"Themes: {', '.join(tags[:5])}.")+ parts.extend([+ "16:9 aspect ratio, suitable as a 1200x630 social cover.",+ "Clean, minimalist, professional. No text, no human faces, no logos.",+ ])+ return " ".join(parts)+++def _http_get(url: str, headers: Optional[dict] = None, timeout: int = HTTP_TIMEOUT) -> Optional[bytes]:+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, **(headers or {})})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ return resp.read()+ except Exception as e:+ print(f"[http] {url[:80]}: {e}", file=sys.stderr)+ return None+++def _http_get_json(url: str, headers: Optional[dict] = None) -> Optional[dict]:+ raw = _http_get(url, headers=headers)+ if raw is None:+ return None+ try:+ return json.loads(raw.decode("utf-8"))+ except (json.JSONDecodeError, UnicodeDecodeError) as e:+ print(f"[http] json decode failed: {e}", file=sys.stderr)+ return None+++def _try_gemini(topic: str, tags: list[str], out_dir: Path, width: int, height: int, model: str) -> Optional[dict]:+ """Ladder step 2: direct Gemini API."""+ api_key = os.environ.get("GOOGLE_AI_API_KEY")+ if not api_key:+ return None+ try:+ from google import genai # type: ignore+ except ImportError:+ print("[gemini] google-genai not installed; skipping", file=sys.stderr)+ return None++ prompt = _build_prompt(topic, tags)+ client = genai.Client(api_key=api_key)+ img_bytes: Optional[bytes] = None+ used_model = model++ # Try Gemini image-preview models first (via generate_content)+ for try_model in (model, "gemini-3.1-flash-image-preview", "gemini-2.5-flash-image"):+ try:+ response = client.models.generate_content(model=try_model, contents=prompt)+ cands = getattr(response, "candidates", None) or []+ for cand in cands:+ content = getattr(cand, "content", None)+ if not content:+ continue+ for part in getattr(content, "parts", []) or []:+ inline = getattr(part, "inline_data", None)+ if inline and getattr(inline, "data", None):+ img_bytes = inline.data+ used_model = try_model+ break+ if img_bytes:+ break+ if img_bytes:+ break+ except Exception as e:+ print(f"[gemini] {try_model} generate_content failed: {e}", file=sys.stderr)++ # Fall back to Imagen via generate_images+ if not img_bytes:+ for try_model in ("imagen-4.0-fast-generate-001", "imagen-4.0-generate-001"):+ try:+ response = client.models.generate_images(+ model=try_model, prompt=prompt,+ config={"number_of_images": 1, "aspect_ratio": "16:9"},+ )+ imgs = getattr(response, "generated_images", None) or []+ if imgs:+ img_obj = imgs[0].image+ img_bytes = getattr(img_obj, "image_bytes", None) or img_obj.read()+ used_model = try_model+ break+ except Exception as e:+ print(f"[gemini] {try_model} generate_images failed: {e}", file=sys.stderr)++ if not img_bytes:+ return None++ hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}.png"+ _atomic_write_bytes(hero_path, img_bytes)+ (out_dir / "hero-credit.txt").write_text(+ f"AI-generated via {used_model}. No attribution required.\nPrompt: {prompt}\n",+ encoding="utf-8",+ )+ return {"source": "gemini", "model": used_model, "path": str(hero_path)}+++def _try_unsplash(query: str, out_dir: Path) -> Optional[dict]:+ key = os.environ.get("UNSPLASH_ACCESS_KEY")+ if not key:+ return None+ params = urllib.parse.urlencode({+ "query": query, "orientation": "landscape", "content_filter": "high", "per_page": 10,+ })+ data = _http_get_json(f"{UNSPLASH_API}?{params}", headers={"Authorization": f"Client-ID {key}"})+ if not data or not data.get("results"):+ return None+ item = data["results"][0]+ img_url = item.get("urls", {}).get("regular")+ if not img_url:+ return None+ img_bytes = _http_get(img_url)+ if not img_bytes:+ return None+ hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}.jpg"+ _atomic_write_bytes(hero_path, img_bytes)+ user = item.get("user", {})+ credit = (+ f'Photo by {user.get("name", "Unsplash contributor")} on Unsplash\n'+ f'License: Unsplash License (free for commercial use, no attribution required but appreciated)\n'+ f'Source: {item.get("links", {}).get("html", img_url)}\n'+ )+ (out_dir / "hero-credit.txt").write_text(credit, encoding="utf-8")+ return {"source": "unsplash", "path": str(hero_path)}+++def _try_pexels(query: str, out_dir: Path) -> Optional[dict]:+ key = os.environ.get("PEXELS_API_KEY")+ if not key:+ return None+ params = urllib.parse.urlencode({"query": query, "orientation": "landscape", "per_page": 10})+ data = _http_get_json(f"{PEXELS_API}?{params}", headers={"Authorization": key})+ if not data or not data.get("photos"):+ return None+ item = data["photos"][0]+ img_url = item.get("src", {}).get("large2x") or item.get("src", {}).get("large")+ if not img_url:+ return None+ img_bytes = _http_get(img_url)+ if not img_bytes:+ return None+ hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}.jpg"+ _atomic_write_bytes(hero_path, img_bytes)+ credit = (+ f'Photo by {item.get("photographer", "Pexels contributor")} on Pexels\n'+ f'License: Pexels License (free for commercial use)\n'+ f'Source: {item.get("url", img_url)}\n'+ )+ (out_dir / "hero-credit.txt").write_text(credit, encoding="utf-8")+ return {"source": "pexels", "path": str(hero_path)}+++def _try_pixabay(query: str, out_dir: Path) -> Optional[dict]:+ key = os.environ.get("PIXABAY_API_KEY")+ if not key:+ return None+ params = urllib.parse.urlencode({+ "key": key, "q": query, "orientation": "horizontal",+ "image_type": "photo", "safesearch": "true", "per_page": 10,+ })+ data = _http_get_json(f"{PIXABAY_API}?{params}")+ if not data or not data.get("hits"):+ return None+ item = data["hits"][0]+ img_url = item.get("largeImageURL") or item.get("webformatURL")+ if not img_url:+ return None+ img_bytes = _http_get(img_url)+ if not img_bytes:+ return None+ hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}.jpg"+ _atomic_write_bytes(hero_path, img_bytes)+ credit = (+ f'Image by {item.get("user", "Pixabay contributor")} on Pixabay\n'+ f'License: Pixabay Content License (free for commercial use)\n'+ f'Source: {item.get("pageURL", img_url)}\n'+ )+ (out_dir / "hero-credit.txt").write_text(credit, encoding="utf-8")+ return {"source": "pixabay", "path": str(hero_path)}+++def _try_premium_stock(topic: str, tags: list[str], out_dir: Path) -> Optional[dict]:+ """Ladder step 3: Unsplash > Pexels > Pixabay (first whose key is set)."""+ query = " ".join([topic] + tags[:3])+ for fn in (_try_unsplash, _try_pexels, _try_pixabay):+ result = fn(query, out_dir)+ if result:+ return result+ return None+++def _try_openverse(topic: str, tags: list[str], out_dir: Path) -> Optional[dict]:+ """Ladder step 4: public API, no key required, CC-licensed."""+ query = " ".join([topic] + tags[:3] + ["editorial illustration"])+ params = urllib.parse.urlencode({+ "q": query, "aspect_ratio": "wide", "license": "cc0,by,by-sa",+ "size": "large", "page_size": 10,+ })+ data = _http_get_json(f"{OPENVERSE_API}?{params}")+ if not data or not data.get("results"):+ print("[openverse] no results", file=sys.stderr)+ return None++ item = data["results"][0]+ img_url = item.get("url") or item.get("thumbnail")+ if not img_url:+ return None+ img_bytes = _http_get(img_url)+ if not img_bytes:+ return None++ ext = ".jpg"+ if img_url.lower().endswith(".png"):+ ext = ".png"+ hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{ext}"+ _atomic_write_bytes(hero_path, img_bytes)++ title = item.get("title") or "untitled"+ creator = item.get("creator") or "Unknown"+ license_name = (item.get("license") or "CC").upper()+ source = item.get("source") or "openverse"+ src_url = item.get("foreign_landing_url") or img_url+ (out_dir / "hero-credit.txt").write_text(+ f'"{title}" by {creator}\nLicense: {license_name}\nSource: {source}\nURL: {src_url}\n',+ encoding="utf-8",+ )+ return {"source": "openverse", "creator": creator, "license": license_name, "path": str(hero_path)}+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--topic", required=True, help="Post title or topic for image search/generation")+ parser.add_argument("--tags", default="", help="Comma-separated tag list")+ parser.add_argument("--out", required=True, help="Output directory (will receive hero.<ext> and hero-credit.txt)")+ parser.add_argument("--width", type=int, default=DEFAULT_WIDTH)+ parser.add_argument("--height", type=int, default=DEFAULT_HEIGHT)+ parser.add_argument("--model", default=DEFAULT_GEMINI_MODEL, help="Gemini image model name")+ parser.add_argument("--json", action="store_true", help="Emit JSON result to stdout")+ args = parser.parse_args()++ out_dir = Path(args.out).resolve()+ try:+ out_dir.mkdir(parents=True, exist_ok=True)+ except OSError as e:+ msg = f"ERROR: cannot create output directory {out_dir}: {e}"+ if args.json:+ print(json.dumps({"error": "out-dir-create-failed", "message": msg}))+ else:+ print(msg, file=sys.stderr)+ return 1+ if not os.access(out_dir, os.W_OK):+ msg = f"ERROR: output directory {out_dir} is not writable"+ if args.json:+ print(json.dumps({"error": "out-dir-not-writable", "message": msg}))+ else:+ print(msg, file=sys.stderr)+ return 1+ tags = [t.strip() for t in args.tags.split(",") if t.strip()]++ ladder: list[tuple[str, Callable[[], Optional[dict]]]] = [+ ("gemini", lambda: _try_gemini(args.topic, tags, out_dir, args.width, args.height, args.model)),+ ("premium-stock", lambda: _try_premium_stock(args.topic, tags, out_dir)),+ ("openverse", lambda: _try_openverse(args.topic, tags, out_dir)),+ ]++ for name, fn in ladder:+ result = fn()+ if result:+ if args.json:+ print(json.dumps(result))+ else:+ print(f"OK: hero from {result['source']} -> {result['path']}")+ return 0++ err = {+ "error": "no-image-gen-path",+ "message": (+ "Hero image required but no generation path available. Configure Banana MCP, "+ "set GOOGLE_AI_API_KEY, set UNSPLASH_ACCESS_KEY / PEXELS_API_KEY / PIXABAY_API_KEY, "+ "or place a 1200x630 hero.png in the draft folder manually."+ ),+ }+ if args.json:+ print(json.dumps(err))+ else:+ print(err["message"], file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/blog-audio/SKILL.md b/skills/blog-audio/SKILL.mdindex 84dabb0..0b99941 100644--- a/skills/blog-audio/SKILL.md+++ b/skills/blog-audio/SKILL.md@@ -14,7 +14,7 @@ argument-hint: "[generate|voices|setup] [file-or-text] [--mode summary|full|diallicense: MITmetadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"---# Blog Audio: Gemini TTS Narration for Blog Postsdiff --git a/skills/blog-cluster/SKILL.md b/skills/blog-cluster/SKILL.mdindex 84aa683..e9c1bd8 100644--- a/skills/blog-cluster/SKILL.md+++ b/skills/blog-cluster/SKILL.md@@ -15,7 +15,7 @@ license: MITcompatibility: Requires Claude Code and claude-blog (provides blog-write, blog-chart, blog-image)metadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: bloguser-invokable: trueargument-hint: "[plan|execute] [seed-keyword|cluster-plan.json]"diff --git a/skills/blog-flow/SKILL.md b/skills/blog-flow/SKILL.mdindex edbae1e..bfba198 100644--- a/skills/blog-flow/SKILL.md+++ b/skills/blog-flow/SKILL.md@@ -12,7 +12,7 @@ license: MITcompatibility: Requires Claude Code and Python 3.11+ for the sync scriptmetadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: blog---diff --git a/skills/blog-google/SKILL.md b/skills/blog-google/SKILL.mdindex d541211..f7bfd0e 100644--- a/skills/blog-google/SKILL.md+++ b/skills/blog-google/SKILL.md@@ -15,7 +15,7 @@ argument-hint: "[setup|pagespeed|crux|crux-history|gsc|inspect|index|ga4|nlp|youlicense: MITmetadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: blog---diff --git a/skills/blog-image/SKILL.md b/skills/blog-image/SKILL.mdindex f206e62..dc1ea4d 100644--- a/skills/blog-image/SKILL.md+++ b/skills/blog-image/SKILL.md@@ -17,7 +17,7 @@ argument-hint: "[generate|edit|setup] [description-or-path]"license: MITmetadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"mcp-package: "@ycse/nanobanana-mcp"---diff --git a/skills/blog-locale-audit/SKILL.md b/skills/blog-locale-audit/SKILL.mdindex 2b961cc..f2b6fc2 100644--- a/skills/blog-locale-audit/SKILL.md+++ b/skills/blog-locale-audit/SKILL.md@@ -14,7 +14,7 @@ license: MITcompatibility: Standalone within claude-blog. Optional richer hreflang validation via claude-seo seo-hreflang.metadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: blog---diff --git a/skills/blog-localize/SKILL.md b/skills/blog-localize/SKILL.mdindex 98c4624..d1f7904 100644--- a/skills/blog-localize/SKILL.md+++ b/skills/blog-localize/SKILL.md@@ -19,7 +19,7 @@ license: MITcompatibility: Standalone within claude-blog. Invoked by blog-multilingual.metadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: blog---diff --git a/skills/blog-multilingual/SKILL.md b/skills/blog-multilingual/SKILL.mdindex 77594af..8fc867f 100644--- a/skills/blog-multilingual/SKILL.md+++ b/skills/blog-multilingual/SKILL.md@@ -15,7 +15,7 @@ license: MITcompatibility: Requires claude-blog (blog-write). Optional integration with claude-seo (seo-hreflang) for richer hreflang validation.metadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: blog---diff --git a/skills/blog-notebooklm/SKILL.md b/skills/blog-notebooklm/SKILL.mdindex 74b5ec7..dfda6c2 100644--- a/skills/blog-notebooklm/SKILL.md+++ b/skills/blog-notebooklm/SKILL.md@@ -14,7 +14,7 @@ argument-hint: "[ask|discover|library|setup|status|cleanup] [question-or-url]"license: MITmetadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"source: "https://github.com/PleasePrompto/notebooklm-skill"---diff --git a/skills/blog-rewrite/SKILL.md b/skills/blog-rewrite/SKILL.mdindex 2a9b7eb..b30b126 100644--- a/skills/blog-rewrite/SKILL.md+++ b/skills/blog-rewrite/SKILL.md@@ -349,6 +349,20 @@ After rewriting, verify all quality gates pass:- Publishing / deploying```+## Phase 5.5: Delivery Contract Enforcement (v1.9.0)++Before presenting the rewritten draft, run the 5-gate delivery contract per `skills/blog/references/blog-delivery-contract.md`. The contract applies to rewrites the same way it applies to new posts: the user is never the first reviewer.++Steps:++1. **Hero check**: if the existing post already has a hero image referenced and still on disk, keep it. If the rewrite changed the topic substantially OR the hero is missing, regenerate via `python scripts/generate_hero.py --topic "<new title>" --tags "<tags>" --out <folder>`.+2. **Re-render**: run `python scripts/blog_render.py --md <slug>.md --out-dir <folder>` to refresh the `.html` and `.pdf` from the updated `.md`.+3. **Reviewer dispatch**: dispatch the `blog-reviewer` agent against the rendered `.html`. Threshold: score 90/100 or higher AND zero P0 issues.+4. **Preflight**: run `python scripts/blog_preflight.py --draft <folder> --strict`. Exit 0 = ship; exit 1 = block.+5. **Iterate on failure**: maximum 3 iterations. After the 3rd failure, STOP and present the diagnostic from `<folder>/preflight-report.json`.++Rewrites have a higher implicit threshold because the existing draft was presumably already published. Re-presenting something worse than the original is not acceptable. If the rewritten score is lower than the original score, that itself is a P0 condition.+## Update ModeWhen invoked as `/blog update <file>`, focus on freshness:diff --git a/skills/blog-translate/SKILL.md b/skills/blog-translate/SKILL.mdindex 24ae697..0599947 100644--- a/skills/blog-translate/SKILL.md+++ b/skills/blog-translate/SKILL.md@@ -18,7 +18,7 @@ license: MITcompatibility: Standalone within claude-blog. Invoked by blog-multilingual.metadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"category: blog---diff --git a/skills/blog-write/SKILL.md b/skills/blog-write/SKILL.mdindex 3d6dd09..a9caa35 100644--- a/skills/blog-write/SKILL.md+++ b/skills/blog-write/SKILL.md@@ -490,9 +490,29 @@ Before delivering, verify:18. **Rhetorical questions** - Verify at least one rhetorical question every 200-300 words to break up declarative patterns.19. **YouTube videos** - 2-3 embeds with lazy loading, aria-labels, and noscript fallback (see `skills/blog/references/video-embeds.md`)+### Phase 6.5: Delivery Contract Enforcement (v1.9.0)++Before Phase 7, run the 5-gate delivery contract per `skills/blog/references/blog-delivery-contract.md`. The user is never the first reviewer; the gates are.++Steps:++1. **Capability discovery + hero**: run `python scripts/blog_preflight.py --draft <folder> --gate 1` to enumerate available paths. If `nanobanana-mcp` is loaded, generate the hero via the MCP tool. Otherwise run `python scripts/generate_hero.py --topic "<title>" --tags "<tags>" --out <folder>` (uses the Gemini, Unsplash, Pexels, Pixabay, Openverse ladder).++2. **Format completeness**: render the canonical `.md` to `.html` and `.pdf` via `python scripts/blog_render.py --md <slug>.md --out-dir <folder>`. All three artifacts plus `hero.<ext>` must end up in the draft folder.++3. **Content review (blocking)**: dispatch the `blog-reviewer` agent (Task tool) against the rendered `.html`. The agent emits its scorecard to `<folder>/review.md` ending with `BLOCKING: true|false (reason)`. Threshold: overall score 90/100 or higher AND zero P0 issues per `editorial-heuristics.md`.++4. **Visual + asset gates**: run `python scripts/blog_preflight.py --draft <folder> --strict`. This runs Gate 3 (visual verification via patchright at 3 viewport widths), Gate 4 (reads review.md BLOCKING line), and Gate 5 (asset + link integrity). Exit 0 = ship; exit 1 = block.++5. **Iteration**: on any block, capture the failure diagnostic from `<folder>/preflight-report.json`, re-dispatch the blog-writer agent with the diagnostic as input, and re-run from step 1. Maximum 3 iterations. On the 3rd failure, STOP and present the failure diagnostic instead of the draft.++The orchestrator holds the loop counter; this sub-skill never loops itself.+### Phase 7: Delivery-Present the completed article with a summary:+Present the completed article ONLY after Phase 6.5 returns all gates passing. Include the screenshots from `<folder>/preview/*.png` in the summary so the user can see what they are getting before reading the prose.++Summary template:```## Blog Post Complete: [Title]diff --git a/skills/blog/SKILL.md b/skills/blog/SKILL.mdindex 8f8be63..7d0eb3f 100644--- a/skills/blog/SKILL.md+++ b/skills/blog/SKILL.md@@ -16,7 +16,7 @@ license: MITcompatibility: Requires Claude Code and Python 3.11+ for quality scoringmetadata:author: AgriciDaniel- version: "1.8.6"+ version: "1.9.0"user-invokable: trueargument-hint: "[write|rewrite|analyze|brief|calendar|cannibalization|strategy|outline|seo-check|schema|repurpose|geo|image|audit|factcheck|persona|brand|discourse|taxonomy|notebooklm|audio|google|update|cluster|multilingual|translate|localize|locale-audit|flow] [topic-or-file]"---@@ -158,6 +158,7 @@ These are hard rules. Never ship content that violates them:| Image alt text | Required on all images | Descriptive, includes topic keywords naturally || Self-promotion | Max 1 brand mention | Author bio context only || Chart diversity | No duplicate types | Each chart must be a different type |+| Delivery contract (v1.9.0) | All 5 gates pass | Blocked drafts iterate up to 3x; see `references/blog-delivery-contract.md` |## Community Footer@@ -225,7 +226,7 @@ Blog quality is scored across 5 categories (100 points total):## Reference Files-Load on-demand as needed (20 references; 13 original + 5 v1.8.0 methodology + 2 supplemental):+Load on-demand as needed (21 references; 13 original + 5 v1.8.0 methodology + 2 supplemental + 1 v1.9.0 delivery contract):- `references/google-landscape-2026.md`: December 2025 Core Update, E-E-A-T, algorithm changes- `references/geo-optimization.md`: GEO/AEO techniques, AI citation factors@@ -247,6 +248,7 @@ Load on-demand as needed (20 references; 13 original + 5 v1.8.0 methodology + 2- `references/cognitive-load.md`: per-section concept-density model with `scripts/cognitive_load.py` (v1.8.0)- `references/research-quality.md`: 5-dim research rubric, pre-flight trap classes, cross-source clustering, freshness floors (v1.8.0)- `references/synthesis-contract.md`: 6 LAWs for research-synthesis output (v1.8.0)+- `references/blog-delivery-contract.md`: 5-gate enforcement between content generation and user delivery (v1.9.0)## Content Templates@@ -345,7 +347,8 @@ Standard execution order for `/blog write`:4. **Write**: Spawn `blog-writer` agent with research packet and outline5. **Optimize**: Spawn `blog-seo` agent for on-page validation6. **Score**: Spawn `blog-reviewer` agent for 100-point quality audit-7. **Deliver**: Output final content with scorecard and improvement notes+6.5. **Delivery Contract Enforcement (v1.9.0)**: Run the 5-gate preflight per `references/blog-delivery-contract.md`. Generate hero via `scripts/generate_hero.py`. Render `.md`/`.html`/`.pdf` via `scripts/blog_render.py`. Run `scripts/blog_preflight.py --draft <folder> --strict`. Check the `BLOCKING:` line in `<folder>/review.md` written by Step 6. If any gate blocks: loop back to Step 4 with the failure diagnostic; max 3 iterations; on the 3rd failure, STOP and present the diagnostic instead of the draft. The user is NEVER the first reviewer; the gates are.+7. **Deliver**: Output final content with scorecard, `preview/*.png` screenshots, and improvement notes ONLY when all gates passFor `/blog analyze`, only steps 1 and 6 run (read + score).For `/blog audit`, step 6 runs in parallel across all posts in the directory.diff --git a/skills/blog/references/blog-delivery-contract.md b/skills/blog/references/blog-delivery-contract.mdnew file mode 100644index 0000000..ac0114c--- /dev/null+++ b/skills/blog/references/blog-delivery-contract.md@@ -0,0 +1,155 @@+# Blog Delivery Contract++The contract every blog must pass before being presented to the user. Five gates that fire automatically between content generation and delivery, plus an iteration loop that retries failures up to three times before escalating.++This contract is the v1.9.0 answer to a failure pattern from the v1.8.x cycle: skills had reviewers, but the reviewer ran as advisory and the writer presented sloppy drafts anyway. The fix is infrastructure, not effort. Same shape as `scripts/lint_prose.py` (v1.8.4) and `tests/test_installer_sync.py` (v1.8.6).++## Gate summary++| Gate | What it enforces | Failure mode | Implementation |+|---|---|---|---|+| 1. Capability Discovery | Required tools + agents are available before write begins | Block if no image-gen path; block if reviewer agent missing | `scripts/blog_preflight.py --gate 1` |+| 2. Format Completeness | `.md` + `.html` + `.pdf` + `hero.png` all present | Block on any missing artifact | `scripts/blog_render.py` produces all three |+| 3. Visual Verification | Rendered HTML has no SVG overflow, no console errors, valid JSON-LD | Block on any defect; preserve screenshots | `scripts/blog_preflight.py --gate 3` via `patchright` |+| 4. Content Review | `blog-reviewer` scores ≥ 90/100 AND zero P0 issues | Block + iterate | `agents/blog-reviewer.md` (now blocking) |+| 5. Asset + Link Integrity | Every `<img>` resolves, every `<a>` returns 200, schema validates | Block on any 404 or count mismatch | `scripts/blog_preflight.py --gate 5` |++All gates run sequentially. First failure halts the chain and triggers the iteration loop. Successful drafts ship with `preflight-report.json` + `review.md` + `preview/*.png` in the draft folder.++## Gate 1: Capability Discovery++Runs once at the start of `/blog write` or `/blog rewrite`. Enumerates the project's available capabilities and writes `<draft-folder>/capabilities.json`. Every later gate consumes this artifact rather than re-detecting.++### What gets enumerated++- **MCP servers loaded**: `nanobanana-mcp`, `dataforseo-mcp`, others. Detected via tool availability, not by reading `.mcp.json` (the file may declare servers that failed to start).+- **Env vars present**: `GOOGLE_AI_API_KEY`, `UNSPLASH_ACCESS_KEY`, `PEXELS_API_KEY`, `PIXABAY_API_KEY`. Key names only; values never read or logged.+- **Optional Python deps**: `patchright`, `weasyprint`, `google-genai`, `requests`. Probed via `importlib.util.find_spec()`.+- **Project-root context files**: `BRAND.md`, `VOICE.md`, `DISCOURSE.md`. Loaded via `scripts/load_untrusted_root.py` (the existing v1.8.3 helper).+- **Agents available**: `blog-reviewer` is mandatory; `blog-researcher`, `blog-writer`, `blog-seo`, `blog-translator` are optional.+- **Helper scripts present**: `scripts/lint_prose.py`, `scripts/analyze_blog.py`, the new `scripts/blog_preflight.py` itself.++### Failure modes++- **No image-gen path at all** (no Banana MCP + no Gemini key + no stock API key + Openverse unreachable): BLOCK with explicit setup instructions.+- **Reviewer agent missing**: BLOCK. Cannot enforce Gate 4 without it.+- **Capability declared but unused**: WARN (informational, not blocking). Example: `dataforseo-mcp` is loaded but the post topic doesn't need keyword research.++## Gate 2: Format Completeness++Every delivered blog ships with four artifacts in `<draft-folder>/`:++- `<slug>.md`: canonical source of truth. Frontmatter + prose + figure references. The `.html` and `.pdf` are rendered from this; they cannot diverge by construction.+- `<slug>.html`: self-contained, valid HTML5, JSON-LD `BlogPosting` schema, Open Graph + Twitter Card meta, dark-mode-aware CSS via `prefers-color-scheme`, real `<img>` tag for hero (never a chart-as-hero).+- `<slug>.pdf`: generated from rendered HTML via `patchright`'s `page.pdf()`, or `weasyprint` as fallback when Playwright is unavailable.+- `hero.png` (or `.jpg`): 1200×630 raster image. Either generated by an image-gen path or downloaded from a CC-licensed stock source. Never hot-linked; always lives in the draft folder.++Implementation lives in `scripts/blog_render.py`. Failure to produce any of the four artifacts blocks delivery.++## Gate 3: Visual Verification++Renders the `.html` in headless `patchright` at three viewport widths and checks for visual defects. This is the "review before present" step.++### Viewport widths++- 375×812 (mobile, iPhone SE class)+- 768×1024 (tablet, iPad portrait)+- 1280×800 (desktop)++### Checks per viewport++1. **Full-page screenshot**: saved to `<draft-folder>/preview/<width>.png` for inspection.+2. **SVG bounding box check**: for every `<svg>` and `<figure>` element, query `getBoundingClientRect()` on the element and on every descendant `text`, `path`, `rect`, and `image` child. Assert no descendant overflows its parent SVG `viewBox`. This catches the exact class of defect from the rankenstein.pro draft: labels positioned outside the chart area, dashed lines passing through annotation text.+3. **Dark-mode pass**: re-render with `prefers-color-scheme: dark` emulation. Assert the body `background-color` differs from light mode. This catches the `var()` in attribute regression where dark mode silently fails to swap colors because CSS custom properties were used in SVG XML attributes (which don't reliably resolve).+4. **Console errors**: capture browser console output during render. Assert zero errors.+5. **JSON-LD validation**: parse the `<script type="application/ld+json">` block. Assert valid JSON. Assert `@type: BlogPosting` with required fields (`headline`, `image`, `datePublished`, `author`).++### Graceful degradation++If `patchright` is not installed, Gate 3 emits a loud warning and proceeds without blocking. The user may be on a constrained machine. CI and `tests/test_blog_delivery_contract.py` require it, so the project as a whole always has Gate 3 coverage even when individual sessions don't.++## Gate 4: Content Review (BLOCKING)++The existing `blog-reviewer` agent (`agents/blog-reviewer.md`) runs against the rendered `.html` (not the raw `.md`). Reviewer output is now **blocking**, not advisory.++### Blocking decision rules++- Overall score **< 90/100** → BLOCK+- **Any P0 issue** from `editorial-heuristics.md` → BLOCK (a draft can score 95 and still have one load-bearing fabricated stat; P0 is an absolute filter independent of the numeric score)+- AI-detection burstiness flag OR more than 3 known AI phrases OR vocabulary diversity (TTR) below 0.4 → BLOCK+- All clear → proceed to Gate 5++The blocking decision is emitted as the last line of the reviewer scorecard, in the format:++```+BLOCKING: true (Overall 87/100 below threshold; P0 on heuristic 5)+BLOCKING: false (cleared all gates)+```++Machine-readable by `scripts/blog_preflight.py` so the orchestrator does not have to parse the human-readable scorecard.++Reviewer report saved to `<draft-folder>/review.md`. Shown to the user on success ("here is why this passed") and on final failure ("here is why this is still blocked after 3 iterations").++## Gate 5: Asset Existence + Link Integrity++- Every `<img src="...">` resolves. Local paths must exist on disk. Absolute URLs must return HTTP 200 via HEAD request (small allowlist for `localhost`, `127.0.0.1`, and known-good placeholder domains during local development).+- `og:image` URL resolves. Same rule; this is the load-bearing social-preview asset.+- Every `<a href="https://...">` returns 200, or is in the per-project `external-links.allowed` config.+- Every `<code>filename.ext</code>` mention either references a real file in the project (verified via `Path.exists()`) or is wrapped in a "hypothetical example" marker.+- `<link rel="canonical">` is set and well-formed.+- JSON-LD `wordCount` matches actual `<article>` word count within ±5%. Catches the "I claimed 1,715 words but the body is 1,400" honesty defect.++## Hero Image Generation Ladder++Tried in order. First success wins. Skip steps for capabilities not available per Gate 1's `capabilities.json`.++1. **Banana MCP** (`nanobanana-mcp` loaded as a tool, not just declared in `.mcp.json`): call its `generate_image` tool with an optimized six-component prompt (Subject + Action + Context + Composition + Lighting + Style) targeting 1200×630.+2. **Direct Gemini API** (`GOOGLE_AI_API_KEY` present, MCP not loaded): call the `google-genai` SDK with the current image-preview model (`gemini-3.1-flash-image-preview` or successor). This is the fallback that would have prevented the rankenstein draft's hand-rolled-chart failure.+3. **Premium stock APIs** (`UNSPLASH_ACCESS_KEY`, `PEXELS_API_KEY`, or `PIXABAY_API_KEY` present): search using post title + top tags as query. Filter for 16:9 aspect ratio, license in {cc0, by, by-sa}, no-face heuristic. Rank by relevance × source authority (Unsplash 1.0, Pexels 0.9, Wikimedia 0.8, Pixabay 0.7).+4. **Openverse public API** (no key required): `GET https://api.openverse.engineering/v1/images/?q=<query>&aspect_ratio=wide&license=cc0,by`. Pick the top relevance match. Always download to `hero.<ext>` plus `hero-credit.txt` for CC attribution.+5. **Block with clear error**: "Hero image required but no generation path available. Configure Banana MCP, set GOOGLE_AI_API_KEY, set UNSPLASH/PEXELS/PIXABAY key, or place a 1200×630 hero.png in the draft folder manually."++Implementation: `scripts/generate_hero.py`. Always writes `hero-credit.txt` next to `hero.<ext>` for attribution compliance, even when generation paths 1-2 (AI-generated, no attribution needed) are used. The file then contains "AI-generated; no attribution required."++## Iteration Loop++When any gate fails, the orchestrator (`skills/blog/SKILL.md`) drives a retry loop:++1. **Capture diagnostic**: which gate failed, which specific check, screenshot if visual, scorecard if content.+2. **Construct iteration prompt** keyed to the failing gate:+ - Gate 2 missing artifact → re-run `scripts/blog_render.py` after fixing the source `.md`+ - Gate 3 visual fail → re-run `scripts/blog_render.py` with adjusted layout (e.g. shrink SVG inner area, wrap long labels)+ - Gate 4 score < 90 → re-dispatch `blog-writer` agent with the reviewer report as input and an instruction to fix the lowest-scoring category first+ - Gate 4 P0 issue → re-dispatch with a targeted instruction for that specific P0+ - Gate 5 404 → re-dispatch with instruction to remove or replace the broken URL+3. **Re-run all five gates** from Gate 1. (Re-running Gate 1 catches the case where an iteration changed capabilities, e.g. installed a missing dep.)+4. **On pass**: present draft to user with a one-line summary ("Delivered after N iteration(s)").+5. **On fail after 3 iterations**: STOP. Show the user the failure diagnostic for each remaining defect, the partial draft, the latest reviewer report, and an explicit "Manual fix required" message. Do not iterate further automatically.++The orchestrator holds the loop counter. Sub-skills never loop themselves; that would risk infinite loops if two sub-skills disagree.++## Bypass Mechanism++Strict mode is the default. Users can override via the `--no-strict` flag on `scripts/blog_preflight.py` or the `bypass: true` field in the draft frontmatter. Both routes log the bypass loudly:++```+WARNING: Delivery contract bypassed. Failed gates: [Gate 3, Gate 5].+The draft is being presented anyway per --no-strict. Do not publish without manual review.+```++Bypass is intended for two cases: (1) the contract has a false positive the user has verified, (2) the user is iterating on a draft and wants to see intermediate output before the gates pass. It is not intended for shipping. A future CI workflow will reject merges where `preflight-report.json` shows `"blocked": true && "strict": false` (the bypassed-and-published case); that enforcement is not yet implemented.++## References++- `skills/blog/references/quality-scoring.md`: the 100-point numeric scoring rubric used by Gate 4+- `skills/blog/references/editorial-heuristics.md`: the P0-P3 ordinal scoring used for the P0 filter in Gate 4+- `skills/blog/references/visual-media.md`: image and asset standards consumed by Gate 5+- `skills/blog/references/schema-stack.md`: JSON-LD structure validated by Gate 3 step 5+- `agents/blog-reviewer.md`: the reviewer agent that produces the Gate 4 scorecard+- `scripts/load_untrusted_root.py`: the v1.8.3 helper used for project-root file loading in Gate 1+- `scripts/lint_prose.py`: the v1.8.4 prose linter run as part of Gate 4's editorial-heuristics scoring+- `tests/test_blog_delivery_contract.py`: coherence test that asserts this contract and its implementation stay in sync++## How this contract maps to the v1.8.x lesson++The rankenstein.pro draft failure was a Category-3 defect: a contradiction between what the project's tooling could do (Banana MCP, blog-reviewer, /blog image, Playwright) and what the writer actually invoked (none of them). The v1.8.x lesson says: convert Category-3 into a gate or a test, not into more discipline. This contract is exactly that. Five gates fire automatically. The writer cannot forget to use the tools because the tools are wired into the gates themselves.diff --git a/tests/test_blog_delivery_contract.py b/tests/test_blog_delivery_contract.pynew file mode 100644index 0000000..0252174--- /dev/null+++ b/tests/test_blog_delivery_contract.py@@ -0,0 +1,438 @@+"""Blog Delivery Contract coherence regression test (v1.9.0).++Asserts that the contract spec at `skills/blog/references/blog-delivery-contract.md`+stays in sync with its implementation across scripts, skills, and the+reviewer agent. Same shape as v1.8.5's test_command_coherence and v1.8.6's+test_installer_sync. The contract is the source of truth; this test fails+loudly on drift.++The class of defect this prevents: contract documents Gate N but Gate N+is not actually wired into blog_preflight.py, or blog-reviewer.md does+not emit the BLOCKING line the contract requires, or blog-write/SKILL.md+forgets to mention the contract. Each is a Category-3 contradiction+between redundant surfaces.++Stdlib + pytest only.+"""++from __future__ import annotations++import json+import re+import subprocess+import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent.parent+CONTRACT_PATH = ROOT / "skills" / "blog" / "references" / "blog-delivery-contract.md"+PREFLIGHT_PATH = ROOT / "scripts" / "blog_preflight.py"+RENDER_PATH = ROOT / "scripts" / "blog_render.py"+HERO_PATH = ROOT / "scripts" / "generate_hero.py"+WRITE_SKILL = ROOT / "skills" / "blog-write" / "SKILL.md"+REWRITE_SKILL = ROOT / "skills" / "blog-rewrite" / "SKILL.md"+ORCHESTRATOR = ROOT / "skills" / "blog" / "SKILL.md"+REVIEWER = ROOT / "agents" / "blog-reviewer.md"+PYPROJECT = ROOT / "pyproject.toml"+++def test_contract_file_exists() -> None:+ assert CONTRACT_PATH.is_file(), f"Delivery contract missing: {CONTRACT_PATH}"+++def test_contract_declares_all_five_gates() -> None:+ text = CONTRACT_PATH.read_text(encoding="utf-8")+ expected = [+ "Gate 1: Capability Discovery",+ "Gate 2: Format Completeness",+ "Gate 3: Visual Verification",+ "Gate 4: Content Review",+ "Gate 5: Asset Existence + Link Integrity",+ ]+ for name in expected:+ assert name in text, f"Contract missing section: {name}"+++def test_contract_declares_hero_image_ladder() -> None:+ text = CONTRACT_PATH.read_text(encoding="utf-8")+ rungs = ("Banana MCP", "Gemini", "Premium stock", "Openverse")+ for rung in rungs:+ assert rung in text, f"Contract missing hero ladder rung: {rung}"+++def test_contract_declares_iteration_cap() -> None:+ text = CONTRACT_PATH.read_text(encoding="utf-8")+ assert "3 iteration" in text or "three iteration" in text or "max 3" in text.lower(), \+ "Contract must declare the 3-iteration cap"+++def test_contract_declares_score_threshold() -> None:+ """The contract must declare BOTH the numeric 90 threshold and the P0+ filter in load-bearing context (not just somewhere on the page).+ Tightened in v1.9.0 hostile-review fix D2."""+ text = CONTRACT_PATH.read_text(encoding="utf-8")+ # Look for either "< 90", "≥ 90", or "90/100" within 60 chars of "P0" or+ # "BLOCK", to ensure the threshold is in the right context not in passing.+ threshold_patterns = [+ re.compile(r"(?:<|≥|>=|score)\s*90\b", re.IGNORECASE),+ re.compile(r"\b90/100\b"),+ re.compile(r"\bbelow\s*90\b", re.IGNORECASE),+ ]+ assert any(p.search(text) for p in threshold_patterns), (+ "Contract must declare the 90/100 threshold in load-bearing context "+ "(e.g. '< 90', 'score 90', '90/100', 'below 90')"+ )+ assert re.search(r"P0\b.*BLOCK|BLOCK.*P0|zero\s+P0", text, re.IGNORECASE), (+ "Contract must declare the zero-P0 blocking filter"+ )+++def test_preflight_script_exists_and_has_cli() -> None:+ assert PREFLIGHT_PATH.is_file(), "scripts/blog_preflight.py missing"+ result = subprocess.run(+ [sys.executable, str(PREFLIGHT_PATH), "--help"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode == 0+ for flag in ("--draft", "--gate", "--strict", "--no-strict", "--json"):+ assert flag in result.stdout, f"blog_preflight.py missing CLI flag: {flag}"+++def test_render_script_exists_and_has_cli() -> None:+ assert RENDER_PATH.is_file(), "scripts/blog_render.py missing"+ result = subprocess.run(+ [sys.executable, str(RENDER_PATH), "--help"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode == 0+ for flag in ("--md", "--out-dir", "--pdf-engine"):+ assert flag in result.stdout, f"blog_render.py missing CLI flag: {flag}"+++def test_hero_script_exists_and_has_cli() -> None:+ assert HERO_PATH.is_file(), "scripts/generate_hero.py missing"+ result = subprocess.run(+ [sys.executable, str(HERO_PATH), "--help"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode == 0+ for flag in ("--topic", "--out"):+ assert flag in result.stdout, f"generate_hero.py missing CLI flag: {flag}"+++def test_preflight_implements_all_named_gates() -> None:+ """Every gate named in the contract must have a corresponding function+ in blog_preflight.py."""+ text = PREFLIGHT_PATH.read_text(encoding="utf-8")+ for fn in ("gate_1_capability_discovery", "gate_2_format_completeness",+ "gate_3_visual_verification", "gate_4_content_review",+ "gate_5_asset_link_integrity"):+ assert f"def {fn}" in text, f"blog_preflight.py missing function: {fn}"+++def test_blog_write_skill_references_contract() -> None:+ text = WRITE_SKILL.read_text(encoding="utf-8")+ assert "blog-delivery-contract.md" in text, \+ "blog-write/SKILL.md must reference the delivery contract"+ assert "blog_preflight.py" in text, \+ "blog-write/SKILL.md must call blog_preflight.py"+ assert "blog-reviewer" in text, \+ "blog-write/SKILL.md must dispatch blog-reviewer"+++def test_blog_rewrite_skill_references_contract() -> None:+ text = REWRITE_SKILL.read_text(encoding="utf-8")+ assert "blog-delivery-contract.md" in text, \+ "blog-rewrite/SKILL.md must reference the delivery contract"+ assert "blog_preflight.py" in text, \+ "blog-rewrite/SKILL.md must call blog_preflight.py"+++def test_orchestrator_references_contract() -> None:+ text = ORCHESTRATOR.read_text(encoding="utf-8")+ assert "blog-delivery-contract.md" in text, \+ "skills/blog/SKILL.md must reference the delivery contract"+ assert re.search(r"\b6\.5\b|Step 6\.5", text), \+ "skills/blog/SKILL.md must declare Step 6.5 (Delivery Contract Enforcement)"+++def test_reviewer_emits_blocking_line() -> None:+ text = REVIEWER.read_text(encoding="utf-8")+ assert "BLOCKING:" in text, \+ "agents/blog-reviewer.md must emit a `BLOCKING:` line in its scorecard"+ assert "Blocking Decision" in text or "Blocking decision" in text, \+ "agents/blog-reviewer.md must document the blocking decision rules"+++def test_pyproject_declares_presentation_group() -> None:+ text = PYPROJECT.read_text(encoding="utf-8")+ assert "presentation" in text, \+ "pyproject.toml must declare an optional-deps `presentation` group"+ for dep in ("patchright", "weasyprint"):+ assert dep in text, \+ f"pyproject.toml `presentation` group must include {dep}"+++def test_installers_ship_all_new_scripts() -> None:+ """The 3 new v1.9.0 scripts must be uninstall-aware (install.sh uses a+ glob, but uninstall.sh enumerates explicitly)."""+ uninstall_sh = (ROOT / "uninstall.sh").read_text(encoding="utf-8")+ uninstall_ps1 = (ROOT / "uninstall.ps1").read_text(encoding="utf-8")+ for script in ("blog_preflight.py", "blog_render.py", "generate_hero.py"):+ assert script in uninstall_sh, f"uninstall.sh missing {script}"+ assert script in uninstall_ps1, f"uninstall.ps1 missing {script}"+++# ---------------------------------------------------------------------------+# Functional regression tests (v1.9.0 hostile-review fix D3).+# These tests actually invoke the scripts against synthesized fixtures and+# assert observable behaviour. They would have caught S1 (XSS), F1 (empty+# markdown), and F3 (H1 inline formatting) before review.+# ---------------------------------------------------------------------------++_VALID_FRONTMATTER = (+ '---\n'+ 'title: "Fixture"\n'+ 'description: "x"\n'+ 'date: 2026-05-17\n'+ 'author: "x"\n'+ '---\n'+)+++def _render(tmp_path: Path, md_body: str, title: str = "Fixture") -> tuple[int, str, str, list[Path]]:+ """Invoke blog_render.py against a synthesized .md; return+ (returncode, stdout, stderr, list-of-html-files-emitted)."""+ md = tmp_path / "fixture.md"+ md.write_text(+ f'---\ntitle: "{title}"\ndescription: "x"\ndate: 2026-05-17\nauthor: "x"\n---\n{md_body}',+ encoding="utf-8",+ )+ result = subprocess.run(+ [sys.executable, str(RENDER_PATH), "--md", str(md), "--out-dir", str(tmp_path),+ "--pdf-engine", "none"],+ capture_output=True, text=True, check=False,+ )+ htmls = list(tmp_path.glob("*.html"))+ return result.returncode, result.stdout, result.stderr, htmls+++def test_xss_via_jsonld_is_escaped(tmp_path: Path) -> None:+ """S1 regression: a frontmatter title containing </script> must NOT+ appear unescaped in the rendered HTML's JSON-LD block."""+ rc, stdout, stderr, htmls = _render(+ tmp_path, "body content",+ title='x</script><script>alert(1)</script>',+ )+ assert rc == 0, f"render failed: rc={rc} stderr={stderr}"+ assert len(htmls) == 1+ rendered = htmls[0].read_text(encoding="utf-8")+ assert "</script><script>alert" not in rendered, (+ "XSS regression: an unescaped </script> from frontmatter title broke "+ "out of the JSON-LD <script> block."+ )+ # And confirm the JSON-LD still parses to the original headline string.+ m = re.search(r'<script type="application/ld\+json">(.*?)</script>', rendered, re.DOTALL)+ assert m, "JSON-LD block not present"+ parsed = json.loads(m.group(1))+ assert parsed.get("headline") == 'x</script><script>alert(1)</script>', (+ "JSON-LD headline should round-trip the original string after HTML-safe escape"+ )+++def test_empty_md_is_rejected(tmp_path: Path) -> None:+ """F1 regression: empty markdown source must NOT produce empty HTML."""+ md = tmp_path / "empty.md"+ md.write_text("", encoding="utf-8")+ result = subprocess.run(+ [sys.executable, str(RENDER_PATH), "--md", str(md), "--out-dir", str(tmp_path),+ "--pdf-engine", "none"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode != 0, "empty .md must fail with non-zero exit"+ assert "required frontmatter" in result.stderr or "empty" in result.stderr.lower()+++def test_missing_frontmatter_keys_rejected(tmp_path: Path) -> None:+ """F2 regression: missing required frontmatter keys must fail loudly."""+ md = tmp_path / "partial.md"+ md.write_text('---\ntitle: "t"\n---\nbody\n', encoding="utf-8") # missing date/desc/author+ result = subprocess.run(+ [sys.executable, str(RENDER_PATH), "--md", str(md), "--out-dir", str(tmp_path),+ "--pdf-engine", "none"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode != 0+ assert "missing" in result.stderr.lower()+++def test_h1_strip_handles_inline_formatting(tmp_path: Path) -> None:+ """F3 regression: H1 with **bold** must still be deduplicated."""+ rc, _, stderr, htmls = _render(tmp_path, "# Title with **bold** word\nbody")+ assert rc == 0, f"render failed: {stderr}"+ rendered = htmls[0].read_text(encoding="utf-8")+ h1_count = len(re.findall(r"<h1\b", rendered))+ assert h1_count == 1, f"expected exactly 1 H1, got {h1_count}"+++def test_symlink_to_md_is_refused(tmp_path: Path) -> None:+ """S2 regression: renderer must refuse to follow symlinks."""+ real = tmp_path / "real.md"+ real.write_text(_VALID_FRONTMATTER + "body\n", encoding="utf-8")+ link = tmp_path / "link.md"+ try:+ link.symlink_to(real)+ except OSError:+ pytest.skip("symlinks not supported on this filesystem")+ result = subprocess.run(+ [sys.executable, str(RENDER_PATH), "--md", str(link), "--out-dir", str(tmp_path),+ "--pdf-engine", "none"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode != 0+ assert "symlink" in result.stderr.lower()+++def test_preflight_gate_2_blocks_on_missing_hero(tmp_path: Path) -> None:+ """Gate 2 regression: a draft folder without a hero.<ext> must FAIL+ Gate 2 (Format Completeness)."""+ (tmp_path / "post.md").write_text(_VALID_FRONTMATTER + "body\n", encoding="utf-8")+ (tmp_path / "post.html").write_text("<html></html>", encoding="utf-8")+ (tmp_path / "post.pdf").write_bytes(b"%PDF-1.4\n")+ # NOTE: no hero.<ext>+ result = subprocess.run(+ [sys.executable, str(PREFLIGHT_PATH), "--draft", str(tmp_path),+ "--gate", "2", "--no-strict"],+ capture_output=True, text=True, check=False,+ )+ assert "FAIL" in result.stdout and "Gate 2" in result.stdout+ assert "hero" in result.stdout.lower()+++def test_preflight_gate_5_flags_non_http_scheme_as_violation(tmp_path: Path) -> None:+ """S3 regression: Gate 5 must flag file://, javascript:, data: links as+ violations rather than silently skipping them."""+ (tmp_path / "post.md").write_text(_VALID_FRONTMATTER + "body\n", encoding="utf-8")+ (tmp_path / "post.html").write_text(+ '<!DOCTYPE html><html><head>'+ '<meta property="og:image" content="hero.png">'+ '<script type="application/ld+json">'+ '{"@type":"BlogPosting","headline":"x","image":"x","datePublished":"x",'+ '"author":{"name":"x"},"wordCount":1}'+ '</script></head><body><article>'+ '<a href="file:///etc/passwd">x</a>'+ '<a href="javascript:alert(1)">y</a>'+ 'word</article></body></html>',+ encoding="utf-8",+ )+ (tmp_path / "hero.png").write_bytes(b"\x89PNG\r\n\x1a\n")+ (tmp_path / "review.md").write_text("BLOCKING: false (test)", encoding="utf-8")+ result = subprocess.run(+ [sys.executable, str(PREFLIGHT_PATH), "--draft", str(tmp_path),+ "--gate", "5", "--no-strict"],+ capture_output=True, text=True, check=False,+ )+ assert "non-http(s) URL scheme" in result.stdout+ assert "file:///etc/passwd" in result.stdout+ assert "javascript:" in result.stdout+++# ---------------------------------------------------------------------------+# Coherence test for the reference count across redundant surfaces (v1.9.0+# hostile-review fix for C1 / C2). Same shape as test_version_coherence.+# ---------------------------------------------------------------------------++def test_reference_count_coherence() -> None:+ """The number declared in skills/blog/SKILL.md must agree with the+ actual count in skills/blog/references/, and with the count claimed in+ docs/ARCHITECTURE.md and CLAUDE.md."""+ refs_dir = ROOT / "skills" / "blog" / "references"+ actual = sum(1 for p in refs_dir.iterdir() if p.is_file() and p.suffix == ".md")++ skill_text = (ROOT / "skills" / "blog" / "SKILL.md").read_text(encoding="utf-8")+ m = re.search(r"Load on-demand as needed \((\d+) references", skill_text)+ assert m, "skills/blog/SKILL.md must declare reference count in the 'Load on-demand' line"+ declared_skill = int(m.group(1))+ assert declared_skill == actual, (+ f"skills/blog/SKILL.md says {declared_skill} references; filesystem has {actual}"+ )++ arch_text = (ROOT / "docs" / "ARCHITECTURE.md").read_text(encoding="utf-8")+ m = re.search(r"(\d+) references in `skills/blog/references/`", arch_text)+ assert m, "docs/ARCHITECTURE.md must declare reference count"+ declared_arch = int(m.group(1))+ assert declared_arch == actual, (+ f"docs/ARCHITECTURE.md says {declared_arch}; filesystem has {actual}"+ )++ claude_text = (ROOT / "CLAUDE.md").read_text(encoding="utf-8")+ m = re.search(r"(\d+) reference docs", claude_text)+ assert m, "CLAUDE.md must declare reference doc count"+ declared_claude = int(m.group(1))+ assert declared_claude == actual, (+ f"CLAUDE.md says {declared_claude}; filesystem has {actual}"+ )+++def test_render_wordcount_matches_gate5_semantics(tmp_path: Path) -> None:+ """blog_render.py's wordCount injected into JSON-LD must use the SAME+ counting algorithm as blog_preflight.py Gate 5 (exclude <code> and+ <pre> content). v1.9.0 audit caught a 18.4% drift on docs containing+ code samples because render counted code-block tokens as prose words+ but preflight excluded them. Mismatch caused Gate 5 to fire as a+ false-positive blocker on every doc with code fences.+ """+ md = tmp_path / "with-code.md"+ # NB: explicit `+` before the multiplied string prevents Python's implicit+ # adjacent-literal concatenation from greedy-grabbing the entire literal+ # block and multiplying it by 5 (which would duplicate the frontmatter).+ md.write_text(+ (+ "---\n"+ "title: \"WordCount Coherence Fixture\"\n"+ "description: \"Tests render/preflight wordCount agreement.\"\n"+ "date: \"2026-05-18\"\n"+ "author: \"Test\"\n"+ "---\n"+ "\n"+ )+ + ("This is a paragraph with ten ordinary prose words. " * 5)+ + (+ "\n\n"+ "```python\n"+ "# A code block with many tokens that must NOT be counted as prose.\n"+ "def excluded():\n"+ " return ['lots', 'of', 'tokens', 'inside', 'code', 'fences']\n"+ "```\n"+ "\n"+ "Closing prose paragraph.\n"+ ),+ encoding="utf-8",+ )+ out = tmp_path / "out"+ out.mkdir()+ result = subprocess.run(+ [sys.executable, str(RENDER_PATH), "--md", str(md),+ "--out-dir", str(out), "--pdf-engine", "none"],+ capture_output=True, text=True, check=False,+ )+ assert result.returncode == 0, f"render failed: {result.stderr}"+ html_path = out / "wordcount-coherence-fixture.html"+ assert html_path.exists(), f"render did not produce expected HTML: {list(out.iterdir())}"+ html = html_path.read_text(encoding="utf-8")+ m = re.search(r'"wordCount":\s*(\d+)', html)+ assert m, "JSON-LD must declare a wordCount"+ declared = int(m.group(1))+ # Hand-counted prose words in the fixture: 5 repetitions of an 11-word+ # sentence (55) + "Closing prose paragraph" (3) = 58. The code block must+ # NOT contribute. Allow generous slack for edge cases in tokenizing the+ # comment markers/punctuation; the only test is "didn't count the code".+ assert declared < 70, (+ f"declared wordCount={declared} suggests code-block content was "+ f"counted as prose. Expected ~58, max ~70."+ )+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/uninstall.ps1 b/uninstall.ps1index e61d21f..c46881b 100644--- a/uninstall.ps1+++ b/uninstall.ps1@@ -46,7 +46,8 @@ function Main {# Remove root-level scripts copied to ~/.claude/scripts/ by install.ps1# (v1.8.6: install.ps1 now copies all scripts/*.py to that location).$ClaudeScriptsDir = Join-Path $env:USERPROFILE ".claude\scripts"- $helperScripts = @("analyze_blog.py", "cognitive_load.py", "discourse_research.py",+ $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")foreach ($s in $helperScripts) {$scriptPath = Join-Path $ClaudeScriptsDir $sdiff --git a/uninstall.sh b/uninstall.shindex 451c24f..c1514bb 100755--- a/uninstall.sh+++ b/uninstall.sh@@ -39,8 +39,9 @@ main() {# Remove root-level scripts copied to ~/.claude/scripts/ by install.sh# (v1.8.6: install.sh now copies all scripts/*.py to that location).local helper_scripts=(- "analyze_blog.py" "cognitive_load.py" "discourse_research.py"- "load_untrusted_root.py" "lint_prose.py" "sync_flow.py"+ "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")for s in "${helper_scripts[@]}"; doif [ -f "${HOME}/.claude/scripts/${s}" ]; then