Skip to content

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

fix(scripts): harden the quality gate, renderer, hero ladder and setup

Agrici Danielf0480af5f174
diff --git a/README.md b/README.md
index 5ddd9f7..15d7f3a 100644
--- a/README.md
+++ b/README.md
@@ -314,7 +314,7 @@ Integrity is only as pinned as `CLAUDE_BLOG_REF`. What the digests cover:
each is the SHA-256 of that one file's bytes in this repository with CRLF line
endings normalized to LF, the form `raw.githubusercontent.com` serves
(`install.sh`: the digest above; `install.ps1`:
-`aa80fa99aaacc5dec3acabcbd714801b4a3e63635c09db9264041f8b8f48dd97`). A local
+`133d49c1ac5723605ee53ca140b9f17c30db9b980a712a3d1938f71cea17139a`). A local
copy with CRLF endings or edits will not match until normalized. They do not
cover the code that does the work: the wrapper clones the repository at
`CLAUDE_BLOG_REF` and hands over to that revision's own `install.sh`,
diff --git a/install.ps1 b/install.ps1
index 24396fb..4a56b30 100644
--- a/install.ps1
+++ b/install.ps1
@@ -157,6 +157,22 @@ function Test-Python311($PythonCommand) {
} catch { return $false }
}
+function Find-Python311 {
+ # Windows ships python.exe and python3.exe Microsoft Store stubs that sit on
+ # PATH but are not Python. Take the first candidate that really runs
+ # Python 3.11+; if none does, return the first one found so the caller can
+ # report its version (or the missing interpreter) as before. The py launcher
+ # is last and runs the default Python 3 install.
+ $first = $null
+ foreach ($name in @("python", "python3", "py")) {
+ foreach ($candidate in @(Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue)) {
+ if (-not $first) { $first = $candidate }
+ if (Test-Python311 $candidate) { return $candidate }
+ }
+ }
+ return $first
+}
+
function Test-PythonHasPip($PythonCommand) {
try {
& $PythonCommand.Source -m pip --version *> $null
@@ -263,8 +279,7 @@ function Main {
if (-not (Test-Path -LiteralPath $LegacyInventory -PathType Leaf)) { throw "Reviewed legacy ownership inventory is missing: $LegacyInventory" }
. $OwnershipHelper
- $PythonCmd = Get-Command python3 -ErrorAction SilentlyContinue
- if (-not $PythonCmd) { $PythonCmd = Get-Command python -ErrorAction SilentlyContinue }
+ $PythonCmd = Find-Python311
if (-not $PythonCmd) {
Write-Color Yellow "WARNING: Python not found. The scripts require Python 3.11+."
} elseif (-not (Test-Python311 $PythonCmd)) {
diff --git a/scripts/blog_render.py b/scripts/blog_render.py
index 2baa711..1bab18f 100644
--- a/scripts/blog_render.py
+++ b/scripts/blog_render.py
@@ -501,12 +501,18 @@ def _build_json_ld(fm: dict, word_count: int, og_image_url: str) -> str:
}
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("</", "<\\/")
+ # HTML-safe JSON encoding: escape "<", ">" and "&" as \u003c, \u003e and
+ # \u0026 so an attacker who controls a frontmatter value (e.g. title)
+ # cannot inject "</script>" or "<!--<script>" and break out of (or
+ # confuse the HTML parser inside) the surrounding
+ # <script type="application/ld+json"> block. These are valid JSON string
+ # escapes, so the embedded JSON stays semantically identical for any parser.
+ return (
+ json.dumps(data, ensure_ascii=False)
+ .replace("<", "\\u003c")
+ .replace(">", "\\u003e")
+ .replace("&", "\\u0026")
+ )
def _read_md_bytes_safely(path: Path) -> bytes:
@@ -515,7 +521,10 @@ def _read_md_bytes_safely(path: Path) -> bytes:
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)
+ # O_NOFOLLOW is missing on Windows; refuse symlinks with an lstat check there.
+ if path.is_symlink():
+ raise ValueError(f"refusing to follow symlink: {path}")
+ fd = os.open(str(path), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
except OSError as e:
if e.errno in (errno.ELOOP, errno.EMLINK):
raise ValueError(f"refusing to follow symlink: {path}")
@@ -694,6 +703,14 @@ def _validate_frontmatter(fm: dict, body: str) -> None:
f"missing or empty required frontmatter key(s): {missing}. "
f"Required: {list(REQUIRED_FRONTMATTER_KEYS)}."
)
+ canonical = str(fm.get("canonical", "")).strip()
+ if canonical:
+ parsed = urllib.parse.urlsplit(canonical)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise ValueError(
+ f"frontmatter `canonical` must be a full http(s) URL with a host, got {canonical!r}. "
+ "Example: https://example.com/blog/my-post/"
+ )
_resolve_modified(fm)
if not body.strip():
raise ValueError(
diff --git a/scripts/check_google_currentness.py b/scripts/check_google_currentness.py
index bdb582d..4f83949 100644
--- a/scripts/check_google_currentness.py
+++ b/scripts/check_google_currentness.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import argparse
import json
import sys
+import time
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
@@ -24,22 +25,39 @@ AUTOMATED_SOURCES = {
}
+RETRY_DELAY_SECONDS = 1.0
+
+
def _fetch(url: str, timeout: float) -> bytes:
request = urllib.request.Request(
url,
headers={"User-Agent": "claude-blog-currentness-check/1.0"},
)
- with urllib.request.urlopen(request, timeout=timeout) as response:
- return response.read()
+ # One retry on a network error absorbs a transient blip without hiding an outage.
+ for attempt in range(2):
+ try:
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ return response.read()
+ except urllib.error.URLError:
+ if attempt == 1:
+ raise
+ time.sleep(RETRY_DELAY_SECONDS)
+ raise AssertionError("unreachable")
def latest_ranking_incident(payload: bytes) -> date:
- incidents = json.loads(payload)
- dates = [
- datetime.fromisoformat(item["begin"]).date()
- for item in incidents
- if item.get("service_name") == "Ranking" and item.get("begin")
- ]
+ try:
+ incidents = json.loads(payload)
+ dates = [
+ datetime.fromisoformat(item["begin"]).date()
+ for item in incidents
+ if item.get("service_name") == "Ranking" and item.get("begin")
+ ]
+ except (AttributeError, KeyError, TypeError) as exc:
+ raise ValueError(
+ "official status feed has an unexpected shape "
+ f"(expected a JSON list of incident objects): {type(exc).__name__}: {exc}"
+ ) from exc
if not dates:
raise ValueError("official status feed has no Ranking incidents")
return max(dates)
@@ -47,11 +65,17 @@ def latest_ranking_incident(payload: bytes) -> date:
def latest_documentation_update(payload: bytes) -> date:
root = ET.fromstring(payload)
- dates = [
- parsedate_to_datetime(item.text).date()
- for item in root.findall("./channel/item/pubDate")
- if item.text
- ]
+ try:
+ dates = [
+ parsedate_to_datetime(item.text).date()
+ for item in root.findall("./channel/item/pubDate")
+ if item.text
+ ]
+ except (AttributeError, KeyError, TypeError) as exc:
+ raise ValueError(
+ "official documentation feed has an unexpected shape "
+ f"(expected RSS items with an RFC 2822 pubDate): {type(exc).__name__}: {exc}"
+ ) from exc
if not dates:
raise ValueError("official documentation feed has no dated items")
return max(dates)
@@ -158,6 +182,7 @@ def main() -> int:
source_dates=source_dates,
)
except (
+ AttributeError,
FileNotFoundError,
json.JSONDecodeError,
KeyError,
diff --git a/scripts/generate_hero.py b/scripts/generate_hero.py
index a921fe9..daaaf6d 100644
--- a/scripts/generate_hero.py
+++ b/scripts/generate_hero.py
@@ -1,21 +1,29 @@
#!/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`
+Implements the v1.9.0 Blog Delivery Contract hero-image ladder. Banana MCP
+is step 1 of the contract, but it runs in the orchestrator before this script
+is called and this script never calls it. The script itself starts at step 2
+(direct Gemini API) and produces the final `hero.<ext>` + `hero-credit.txt`
in the requested output directory.
Ladder:
- 1. (Orchestrator only) Banana MCP via nanobanana-mcp
+ 1. (Orchestrator only, not run by this script) Banana MCP via nanobanana-mcp
2. Direct Gemini API via google-genai SDK (requires GOOGLE_AI_API_KEY or GEMINI_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
+A hero already in the output directory (`hero.png`, `.jpg`, `.jpeg` or
+`.webp`, for example one the user placed by hand) is kept and reported with
+source `existing`; no provider runs. `--replace` generates a new one instead.
+A downloaded or generated image that cannot be decoded (corrupt, truncated,
+oversized) is skipped and the next step runs. A successful write removes any
+stale `hero.*` file of another extension so the renderer cannot pick it.
+
Usage:
python3 scripts/generate_hero.py --topic "<title>" --tags "a,b,c" \\
- --out <draft-folder> [--width 1200] [--height 630] [--json]
+ --out <draft-folder> [--width 1200] [--height 630] [--replace] [--json]
Returns 0 on success (hero.<ext> + hero-credit.txt written). Returns 1
when every ladder step is exhausted with no successful generation.
@@ -332,24 +340,64 @@ def _validate_dimensions(width: int, height: int) -> tuple[bool, str | None]:
return True, None
+class _ImageUnusable(RuntimeError):
+ """The image bytes could not be decoded or resized; the caller moves to the next source."""
+
+
def _fit_image_bytes(data: bytes, width: int, height: int) -> bytes:
- """Resize and center-crop image bytes to exact output dimensions."""
+ """Resize and center-crop image bytes to exact output dimensions.
+
+ Raises RuntimeError when Pillow is missing and its subclass _ImageUnusable
+ when the bytes cannot be decoded (corrupt, truncated, decompression bomb).
+ Both make the ladder skip this source; neither is a write error.
+ """
try:
from PIL import Image, ImageOps # type: ignore
except ImportError as e:
raise RuntimeError("Pillow is required to enforce --width/--height") from e
- with Image.open(io.BytesIO(data)) as img:
- fmt = (img.format or "PNG").upper()
- fitted = ImageOps.fit(img, (width, height), method=Image.Resampling.LANCZOS)
- if fmt in {"JPEG", "JPG"} and fitted.mode in {"RGBA", "LA", "P"}:
- fitted = fitted.convert("RGB")
- out = io.BytesIO()
- save_format = "JPEG" if fmt == "JPG" else fmt
- if save_format not in {"JPEG", "PNG", "WEBP"}:
- save_format = "PNG"
- fitted.save(out, format=save_format)
- return out.getvalue()
+ try:
+ with Image.open(io.BytesIO(data)) as img:
+ fmt = (img.format or "PNG").upper()
+ fitted = ImageOps.fit(img, (width, height), method=Image.Resampling.LANCZOS)
+ if fmt in {"JPEG", "JPG"} and fitted.mode in {"RGBA", "LA", "P"}:
+ fitted = fitted.convert("RGB")
+ out = io.BytesIO()
+ save_format = "JPEG" if fmt == "JPG" else fmt
+ if save_format not in {"JPEG", "PNG", "WEBP"}:
+ save_format = "PNG"
+ fitted.save(out, format=save_format)
+ return out.getvalue()
+ except Exception as e: # PIL raises OSError, ValueError, SyntaxError, DecompressionBombError, ...
+ raise _ImageUnusable(f"image could not be decoded ({type(e).__name__}: {e})") from e
+
+
+HERO_EXTENSIONS = (".png", ".jpg", ".jpeg", ".webp")
+
+
+def _existing_hero(out_dir: Path) -> Optional[Path]:
+ """Return the hero file already in out_dir, if any (symlinks do not count)."""
+ for extension in HERO_EXTENSIONS:
+ candidate = out_dir / f"{OUTPUT_FILE_PREFIX}{extension}"
+ if candidate.is_file() and not candidate.is_symlink():
+ return candidate
+ return None
+
+
+def _write_hero(out_dir: Path, img_bytes: bytes) -> Path:
+ """Write hero.<ext> and remove stale hero.* siblings of other extensions.
+
+ scripts/blog_render.py prefers hero.png, so an older hero.png left beside a
+ fresh hero.jpg would silently win. Cleanup runs only after the write
+ succeeded, and never touches the file just written.
+ """
+ hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{_image_ext(img_bytes)}"
+ _atomic_write_bytes(hero_path, img_bytes)
+ for extension in HERO_EXTENSIONS:
+ stale = out_dir / f"{OUTPUT_FILE_PREFIX}{extension}"
+ if stale != hero_path and (stale.is_symlink() or stale.is_file()):
+ stale.unlink()
+ return hero_path
def _build_prompt(topic: str, tags: list[str], width: int, height: int) -> str:
@@ -472,8 +520,7 @@ def _try_gemini(topic: str, tags: list[str], out_dir: Path, width: int, height:
except RuntimeError as e:
print(f"[image] {e}", file=sys.stderr)
return None
- hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{_image_ext(img_bytes)}"
- _atomic_write_bytes(hero_path, img_bytes)
+ hero_path = _write_hero(out_dir, img_bytes)
_atomic_write_text(
out_dir / "hero-credit.txt",
f"AI-generated via {used_model}. No attribution required.\nPrompt: {prompt}\n",
@@ -503,8 +550,7 @@ def _try_unsplash(query: str, out_dir: Path, width: int, height: int) -> Optiona
except RuntimeError as e:
print(f"[image] {e}", file=sys.stderr)
return None
- hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{_image_ext(img_bytes)}"
- _atomic_write_bytes(hero_path, img_bytes)
+ hero_path = _write_hero(out_dir, img_bytes)
user = item.get("user", {})
credit = (
f'Photo by {user.get("name", "Unsplash contributor")} on Unsplash\n'
@@ -535,8 +581,7 @@ def _try_pexels(query: str, out_dir: Path, width: int, height: int) -> Optional[
except RuntimeError as e:
print(f"[image] {e}", file=sys.stderr)
return None
- hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{_image_ext(img_bytes)}"
- _atomic_write_bytes(hero_path, img_bytes)
+ hero_path = _write_hero(out_dir, img_bytes)
credit = (
f'Photo by {item.get("photographer", "Pexels contributor")} on Pexels\n'
f'License: Pexels License (free for commercial use)\n'
@@ -569,8 +614,7 @@ def _try_pixabay(query: str, out_dir: Path, width: int, height: int) -> Optional
except RuntimeError as e:
print(f"[image] {e}", file=sys.stderr)
return None
- hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{_image_ext(img_bytes)}"
- _atomic_write_bytes(hero_path, img_bytes)
+ hero_path = _write_hero(out_dir, img_bytes)
credit = (
f'Image by {item.get("user", "Pixabay contributor")} on Pixabay\n'
f'License: Pixabay Content License (free for commercial use)\n'
@@ -636,9 +680,7 @@ def _try_openverse(topic: str, tags: list[str], out_dir: Path, width: int, heigh
print(f"[image] {e}", file=sys.stderr)
return None
- ext = _image_ext(img_bytes)
- hero_path = out_dir / f"{OUTPUT_FILE_PREFIX}{ext}"
- _atomic_write_bytes(hero_path, img_bytes)
+ hero_path = _write_hero(out_dir, img_bytes)
title = item.get("title") or "untitled"
creator = item.get("creator") or "Unknown"
@@ -660,6 +702,11 @@ def main() -> int:
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(
+ "--replace",
+ action="store_true",
+ help="Generate a new hero even when the output directory already has one (default: keep it)",
+ )
parser.add_argument("--json", action="store_true", help="Emit JSON result to stdout")
args = parser.parse_args()
@@ -698,6 +745,16 @@ def main() -> int:
else:
print(msg, file=sys.stderr)
return 1
+ existing = _existing_hero(out_dir)
+ if existing is not None and not args.replace:
+ # Never overwrite or delete a hero that is already there (the contract
+ # lets the user place one by hand), and never spend on a second one.
+ result = {"source": "existing", "path": str(existing)}
+ if args.json:
+ print(json.dumps(result))
+ else:
+ print(f"OK: kept existing hero {existing} (pass --replace to generate a new one)")
+ return 0
tags = [t.strip() for t in args.tags.split(",") if t.strip()]
ladder: list[tuple[str, Callable[[], Optional[dict]]]] = [
diff --git a/scripts/quality_gate.py b/scripts/quality_gate.py
index c7c4d5d..a92afdf 100644
--- a/scripts/quality_gate.py
+++ b/scripts/quality_gate.py
@@ -15,9 +15,16 @@ Path handling is deliberately strict:
description or date) fails, and a file inside docs/, skills/, tests/,
templates/ or references/ is still analyzed.
- A directory named on the command line is scanned recursively. The scan skips
- those non-post directories and files without blog frontmatter.
+ files without blog frontmatter, and skips the docs/, skills/, tests/,
+ templates/ and references/ trees of the claude-blog repository itself.
- Hook mode (``--select``) and ``--staged`` receive every changed Markdown file
from Git or pre-commit, so they apply the filter and skip non-posts.
+- The docs/, skills/, tests/, templates/ and references/ exclusion applies only
+ inside a checkout of claude-blog (a ``.claude-plugin/plugin.json`` named
+ ``claude-blog`` above the file). In any other repository a post under docs/
+ is gated like any other post.
+- Whatever is skipped is counted in the output, so a pass is never silent
+ about what it did not check.
Exit codes: 0 pass, 1 a post failed the gate, 2 usage error or a path that is
missing or not a file.
@@ -48,19 +55,44 @@ MISSING_FRONTMATTER = (
)
-def _path_for_policy(path: Path, root: Path | None = None) -> Path:
- """Return a lexical path relative to root when possible for directory checks."""
- root = Path(os.path.abspath(os.fspath(root or Path.cwd())))
- absolute_path = Path(os.path.abspath(os.fspath(path)))
+def _is_claude_blog_root(directory: Path) -> bool:
+ """Return True when directory is the root of a claude-blog checkout."""
+ manifest = directory / ".claude-plugin" / "plugin.json"
try:
- return absolute_path.relative_to(root)
- except ValueError:
- return absolute_path
+ data = json.loads(manifest.read_text(encoding="utf-8"))
+ except (OSError, UnicodeDecodeError, ValueError):
+ return False
+ return isinstance(data, dict) and data.get("name") == "claude-blog"
+
+
+def _find_claude_blog_root(path: Path) -> Path | None:
+ """Return the claude-blog checkout root above path (lexically), if any."""
+ absolute_path = Path(os.path.abspath(os.fspath(path)))
+ for parent in absolute_path.parents:
+ if _is_claude_blog_root(parent):
+ return parent
+ return None
def is_excluded_path(file_path: str | Path, root: Path | None = None) -> bool:
- """Return True when the path is inside a non-post content tree."""
- policy_path = _path_for_policy(Path(file_path), root)
+ """Return True when the path is inside one of claude-blog's own non-post trees.
+
+ The exclusion applies only when the file sits in a claude-blog checkout:
+ ``root`` (when given) or the nearest ancestor holding a claude-blog
+ ``.claude-plugin/plugin.json``. Everywhere else nothing is excluded.
+ """
+ absolute_path = Path(os.path.abspath(os.fspath(file_path)))
+ if root is None:
+ repo_root = _find_claude_blog_root(absolute_path)
+ else:
+ candidate = Path(os.path.abspath(os.fspath(root)))
+ repo_root = candidate if _is_claude_blog_root(candidate) else None
+ if repo_root is None:
+ return False
+ try:
+ policy_path = absolute_path.relative_to(repo_root)
+ except ValueError:
+ return False
parent_parts = {part.lower() for part in policy_path.parts[:-1]}
return bool(parent_parts & EXCLUDED_DIRS)
@@ -78,33 +110,58 @@ def has_blog_frontmatter(file_path: str | Path) -> bool:
)
-def is_blog_post(file_path: str | Path, root: Path | None = None) -> bool:
- """Return True when a path should be gated as a blog post."""
+def skip_reason(file_path: str | Path, root: Path | None = None) -> str | None:
+ """Return why a path is not gated as a blog post, or None when it is one."""
path = Path(file_path)
if path.suffix.lower() not in BLOG_SUFFIXES:
- return False
+ return "not a Markdown file"
if is_excluded_path(path, root):
- return False
+ return "inside a claude-blog docs, skills, tests, templates or references tree"
if not path.is_file():
- return False
+ return "not a regular file"
try:
- return has_blog_frontmatter(path)
+ if not has_blog_frontmatter(path):
+ return "no blog frontmatter"
except (OSError, UnicodeDecodeError):
- return True
+ return None
+ return None
-def _staged_files() -> list[str]:
- """Read staged file names from Git (deleted files are not gate inputs)."""
+def is_blog_post(file_path: str | Path, root: Path | None = None) -> bool:
+ """Return True when a path should be gated as a blog post."""
+ return skip_reason(file_path, root) is None
+
+
+def _git(*args: str) -> bytes:
+ """Run git and return stdout bytes, raising RuntimeError on failure."""
result = subprocess.run(
- ["git", "diff", "--cached", "--name-only", "--diff-filter=ACMR"],
- check=False,
- capture_output=True,
- text=True,
+ ["git", *args], check=False, capture_output=True
)
if result.returncode != 0:
- message = result.stderr.strip() or "Unable to read staged files"
- raise RuntimeError(message)
- return [line.strip() for line in result.stdout.splitlines() if line.strip()]
+ message = result.stderr.decode("utf-8", "replace").strip()
+ raise RuntimeError(message or "Unable to read staged files")
+ return result.stdout
+
+
+def _staged_files() -> list[str]:
+ """Read staged file paths from Git (deleted files are not gate inputs).
+
+ Uses NUL-separated output so names with spaces or non-ASCII characters are
+ not quoted, and resolves each name against the repository top level, since
+ Git prints paths relative to it whatever the current directory is.
+ """
+ toplevel = Path(_git("rev-parse", "--show-toplevel").decode("utf-8", "replace").strip())
+ raw = _git("diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR")
+ names = [item for item in raw.decode("utf-8", "surrogateescape").split("\0") if item]
+ return [_display_path(toplevel / name) for name in names]
+
+
+def _display_path(path: Path) -> str:
+ """Prefer a path relative to the current directory; keep it absolute if that fails."""
+ try:
+ return os.path.relpath(path)
+ except ValueError:
+ return str(path)
def _input_error(path: str, reason: str) -> dict[str, Any]:
@@ -185,11 +242,27 @@ def analyze_post(file_path: str | Path, threshold: int) -> dict[str, Any]:
return output
-def _format_text(results: list[dict[str, Any]], failures: list[dict[str, Any]], threshold: int) -> str:
+def _skipped_summary(skipped: dict[str, str]) -> str:
+ """Describe skipped files, grouped by reason, for the text output."""
+ reasons: dict[str, int] = {}
+ for reason in skipped.values():
+ reasons[reason] = reasons.get(reason, 0) + 1
+ detail = "; ".join(f"{count} {reason}" for reason, count in sorted(reasons.items()))
+ return f"{len(skipped)} file(s) skipped ({detail})."
+
+
+def _format_text(
+ results: list[dict[str, Any]],
+ failures: list[dict[str, Any]],
+ threshold: int,
+ skipped: dict[str, str] | None = None,
+) -> str:
+ skipped = skipped or {}
+ note = f"\n{_skipped_summary(skipped)}" if skipped else ""
if not failures:
if results:
- return f"Blog quality gate passed: {len(results)} post(s) checked."
- return "Blog quality gate passed: no blog posts to check."
+ return f"Blog quality gate passed: {len(results)} post(s) checked.{note}"
+ return f"Blog quality gate passed: no blog posts to check.{note}"
lines = [
f"Blog quality gate failed: {len(failures)} post(s) below score {threshold}.",
@@ -206,17 +279,25 @@ def _format_text(results: list[dict[str, Any]], failures: list[dict[str, Any]],
)
else:
lines.append(" No high severity issues reported.")
+ if skipped:
+ lines.append(_skipped_summary(skipped))
return "\n".join(lines)
def _format_json(
- results: list[dict[str, Any]], failures: list[dict[str, Any]], threshold: int
+ results: list[dict[str, Any]],
+ failures: list[dict[str, Any]],
+ threshold: int,
+ skipped: dict[str, str] | None = None,
) -> str:
errors = [result["error"] for result in results if result.get("error")]
payload = {
"threshold": threshold,
"checked": results,
"failures": failures,
+ "skipped": [
+ {"file": path, "reason": reason} for path, reason in (skipped or {}).items()
+ ],
}
if errors:
payload["error"] = "; ".join(errors)
@@ -237,14 +318,12 @@ def _threshold_arg(value: str) -> int:
def expand_directory(directory: Path) -> list[str]:
- """Scan a directory for posts, skipping non-post trees and non-post files."""
- found: list[str] = []
- for candidate in sorted(directory.rglob("*")):
- if candidate.suffix.lower() in BLOG_SUFFIXES and is_blog_post(
- candidate, root=directory
- ):
- found.append(str(candidate))
- return found
+ """List every Markdown candidate under a directory; main() filters and counts skips."""
+ return [
+ str(candidate)
+ for candidate in sorted(directory.rglob("*"))
+ if candidate.suffix.lower() in BLOG_SUFFIXES
+ ]
def build_parser() -> argparse.ArgumentParser:
@@ -329,18 +408,22 @@ def main(argv: list[str] | None = None) -> int:
parser.error("no files given: name Markdown files or directories, or pass --staged")
selected = list(explicit)
- selected.extend(
- path for path in candidates if is_blog_post(path, root=Path.cwd())
- )
+ skipped: dict[str, str] = {}
+ for path in candidates:
+ reason = skip_reason(path)
+ if reason is None:
+ selected.append(path)
+ else:
+ skipped[path] = reason
selected = _dedupe(selected)
results = [analyze_post(path, args.threshold) for path in selected]
results.extend(problems)
failures = [result for result in results if not result["passed"]]
if args.format == "json":
- print(_format_json(results, failures, args.threshold))
+ print(_format_json(results, failures, args.threshold, skipped))
else:
- print(_format_text(results, failures, args.threshold))
+ print(_format_text(results, failures, args.threshold, skipped))
if problems:
return 2
diff --git a/skills/blog-audio/scripts/setup_environment.py b/skills/blog-audio/scripts/setup_environment.py
index da3c741..5043ca4 100644
--- a/skills/blog-audio/scripts/setup_environment.py
+++ b/skills/blog-audio/scripts/setup_environment.py
@@ -17,6 +17,16 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from runtime_paths import resolve_runtime_paths
+PIP_TIMEOUT_SECONDS = 900 # a hung index or build should fail, not block setup forever
+
+
+def _output_tail(text: str | bytes | None, lines: int = 20) -> str:
+ """Return the last few lines of captured process output."""
+ if isinstance(text, bytes):
+ text = text.decode("utf-8", "replace")
+ return "\n".join((text or "").strip().splitlines()[-lines:])
+
+
class SkillEnvironment:
"""Manages skill-specific virtual environment"""
@@ -70,11 +80,19 @@ class SkillEnvironment:
subprocess.run(
[str(self.venv_pip)] + install_args,
check=True, capture_output=True, text=True,
+ timeout=PIP_TIMEOUT_SECONDS,
)
self.say("Dependencies installed")
return True
+ except subprocess.TimeoutExpired:
+ self.say(f"Failed to install dependencies: pip did not finish within {PIP_TIMEOUT_SECONDS} seconds")
+ return False
except subprocess.CalledProcessError as e:
self.say(f"Failed to install dependencies: {e}")
+ tail = _output_tail(e.stderr)
+ if tail:
+ # stderr keeps --json output on stdout machine-readable.
+ print(f"pip said:\n{tail}", file=sys.stderr)
return False
def is_in_skill_venv(self) -> bool:
diff --git a/skills/blog-google/scripts/google_auth.py b/skills/blog-google/scripts/google_auth.py
index cb3f8b4..9098f48 100644
--- a/skills/blog-google/scripts/google_auth.py
+++ b/skills/blog-google/scripts/google_auth.py
@@ -190,7 +190,10 @@ def _write_secret_atomic(path: str, content: str) -> None:
os.makedirs(parent, mode=0o700, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-")
try:
- os.fchmod(fd, 0o600)
+ if hasattr(os, "fchmod"):
+ os.fchmod(fd, 0o600)
+ else: # Windows has no fchmod; mkstemp already creates the file owner-only.
+ os.chmod(tmp, 0o600)
with os.fdopen(fd, "w") as f:
f.write(content)
os.replace(tmp, path)
@@ -517,6 +520,72 @@ def get_oauth_credentials(scopes: list):
return get_service_account_credentials(scopes)
+def _open_browser(url: str) -> None:
+ import webbrowser
+
+ try:
+ webbrowser.open(url)
+ except Exception:
+ pass
+
+
+def _listen_for_oauth_code(
+ state_token: str,
+ timeout: float = 300.0,
+ host: str = "127.0.0.1",
+ port: int = 8085,
+ webbrowser_open=None,
+) -> Optional[str]:
+ """Serve the loopback redirect until a request carries a valid code or time runs out.
+
+ Requests with a wrong state or no code (browser favicon fetches, scanners,
+ a forged callback) are answered and ignored; the loop keeps waiting until
+ the deadline. Raises OSError when the port cannot be bound.
+ """
+ import http.server
+ import urllib.parse
+
+ auth_code = [None]
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
+ received_state = params.get("state", [""])[0]
+ if not secrets.compare_digest(received_state.encode(), state_token.encode()):
+ self.send_response(403)
+ self.send_header("Content-Type", "text/plain")
+ self.end_headers()
+ self.wfile.write(b"State mismatch - possible CSRF. Aborted.")
+ return
+ if "code" in params:
+ auth_code[0] = params["code"][0]
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(b"<html><body><h1>Authorization complete.</h1>You can close this tab.</body></html>")
+ else:
+ self.send_response(400)
+ self.end_headers()
+
+ def log_message(self, *a):
+ pass
+
+ server = http.server.HTTPServer((host, port), Handler)
+ try:
+ if webbrowser_open:
+ webbrowser_open()
+ deadline = time.monotonic() + timeout
+ while auth_code[0] is None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ server.timeout = remaining
+ server.handle_request()
+ finally:
+ server.server_close()
+ return auth_code[0]
+
+
def run_oauth_flow(creds_path: str, services: list = None):
"""
Run OAuth browser-based authentication flow.
@@ -529,10 +598,7 @@ def run_oauth_flow(creds_path: str, services: list = None):
services: Optional list of scope service keys (see SCOPES). Defaults to
the read-only set built by `_scopes_for(None)`.
"""
- import http.server
import urllib.parse
- import urllib.request
- import webbrowser
client = _load_oauth_client(creds_path)
if not client:
@@ -557,45 +623,20 @@ def run_oauth_flow(creds_path: str, services: list = None):
f"?{urllib.parse.urlencode(auth_params)}"
)
- auth_code = [None]
-
- class Handler(http.server.BaseHTTPRequestHandler):
- def do_GET(self):
- params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
- received_state = params.get("state", [""])[0]
- if received_state != state_token:
- self.send_response(403)
- self.send_header("Content-Type", "text/plain")
- self.end_headers()
- self.wfile.write(b"State mismatch - possible CSRF. Aborted.")
- return
- if "code" in params:
- auth_code[0] = params["code"][0]
- self.send_response(200)
- self.send_header("Content-Type", "text/html")
- self.end_headers()
- self.wfile.write(b"<html><body><h1>Authorization complete.</h1>You can close this tab.</body></html>")
- else:
- self.send_response(400)
- self.end_headers()
- def log_message(self, *a):
- pass
-
- server = http.server.HTTPServer(("127.0.0.1", 8085), Handler)
- server.timeout = 300
-
print(f"\nOpen this URL in your browser:\n\n{auth_url}\n")
print("Waiting up to 5 minutes for authentication...")
try:
- webbrowser.open(auth_url)
- except Exception:
- pass
-
- server.handle_request()
- server.server_close()
+ auth_code = _listen_for_oauth_code(state_token, webbrowser_open=lambda: _open_browser(auth_url))
+ except OSError as exc:
+ print(
+ f"\nError: could not listen on {OAUTH_REDIRECT_URI} ({exc}). "
+ "Another process is probably using port 8085; stop it and retry.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
- if not auth_code[0]:
+ if not auth_code:
print("\nAuthentication failed or timed out.", file=sys.stderr)
print("If the browser showed '127.0.0.1 refused to connect', copy the full URL")
print("from the browser address bar and run:")
@@ -603,7 +644,7 @@ def run_oauth_flow(creds_path: str, services: list = None):
sys.exit(1)
# Exchange code for tokens
- _exchange_code(client, auth_code[0], creds_path=creds_path)
+ _exchange_code(client, auth_code, creds_path=creds_path)
def _exchange_code(client: dict, code: str, creds_path: str | None = None):
diff --git a/skills/blog-google/scripts/setup_environment.py b/skills/blog-google/scripts/setup_environment.py
index e830ebd..b700d08 100644
--- a/skills/blog-google/scripts/setup_environment.py
+++ b/skills/blog-google/scripts/setup_environment.py
@@ -17,6 +17,16 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from runtime_paths import resolve_runtime_paths
+PIP_TIMEOUT_SECONDS = 900 # a hung index or build should fail, not block setup forever
+
+
+def _output_tail(text: str | bytes | None, lines: int = 20) -> str:
+ """Return the last few lines of captured process output."""
+ if isinstance(text, bytes):
+ text = text.decode("utf-8", "replace")
+ return "\n".join((text or "").strip().splitlines()[-lines:])
+
+
class SkillEnvironment:
"""Manages skill-specific virtual environment"""
@@ -67,12 +77,19 @@ class SkillEnvironment:
subprocess.run(
[str(self.venv_pip)] + install_args,
check=True, capture_output=True, text=True,
+ timeout=PIP_TIMEOUT_SECONDS,
)
self.write_dependency_stamp()
print("Dependencies installed")
return True
+ except subprocess.TimeoutExpired:
+ print(f"Failed to install dependencies: pip did not finish within {PIP_TIMEOUT_SECONDS} seconds")
+ return False
except subprocess.CalledProcessError as e:
print(f"Failed to install dependencies: {e}")
+ tail = _output_tail(e.stderr)
+ if tail:
+ print(f"pip said:\n{tail}")
return False
def is_in_skill_venv(self) -> bool:
diff --git a/skills/blog-image/scripts/setup_image_mcp.py b/skills/blog-image/scripts/setup_image_mcp.py
index ca706ff..4ea580c 100644
--- a/skills/blog-image/scripts/setup_image_mcp.py
+++ b/skills/blog-image/scripts/setup_image_mcp.py
@@ -223,7 +223,10 @@ def save_config(path: Path, config: dict, quiet: bool = False) -> None:
_verify_not_symlink(path)
fd, tmp_path = _open_temp_no_follow(path)
try:
- os.fchmod(fd, 0o600)
+ if hasattr(os, "fchmod"):
+ os.fchmod(fd, 0o600)
+ else: # Windows has no fchmod; the temp file is created with mode 0o600 already.
+ os.chmod(tmp_path, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(config, f, indent=2)
f.write("\n")
diff --git a/skills/blog-notebooklm/scripts/setup_environment.py b/skills/blog-notebooklm/scripts/setup_environment.py
index 884714f..11675ae 100644
--- a/skills/blog-notebooklm/scripts/setup_environment.py
+++ b/skills/blog-notebooklm/scripts/setup_environment.py
@@ -17,6 +17,16 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from runtime_paths import resolve_runtime_paths
+PIP_TIMEOUT_SECONDS = 900 # a hung index or build should fail, not block setup forever
+
+
+def _output_tail(text: str | bytes | None, lines: int = 20) -> str:
+ """Return the last few lines of captured process output."""
+ if isinstance(text, bytes):
+ text = text.decode("utf-8", "replace")
+ return "\n".join((text or "").strip().splitlines()[-lines:])
+
+
class SkillEnvironment:
"""Manages skill-specific virtual environment"""
@@ -76,7 +86,8 @@ class SkillEnvironment:
[str(self.venv_pip)] + install_args,
check=True,
capture_output=True,
- text=True
+ text=True,
+ timeout=PIP_TIMEOUT_SECONDS,
)
self.write_dependency_stamp()
print("✅ Dependencies installed")
@@ -90,18 +101,26 @@ class SkillEnvironment:
[str(self.venv_python), "-m", "patchright", "install", "chrome"],
check=True,
capture_output=True,
- text=True
+ text=True,
+ timeout=PIP_TIMEOUT_SECONDS,
)
print("✅ Chrome installed")
+ except subprocess.TimeoutExpired:
+ print(f"⚠️ Warning: Chrome install did not finish within {PIP_TIMEOUT_SECONDS} seconds")
+ print(" You may need to run manually: python3 -m patchright install chrome")
except subprocess.CalledProcessError as e:
print(f"⚠️ Warning: Failed to install Chrome: {e}")
print(" You may need to run manually: python3 -m patchright install chrome")
print(" Chrome is required (not Chromium) for reliability!")
return True
+ except subprocess.TimeoutExpired:
+ print(f"❌ Failed to install dependencies: pip did not finish within {PIP_TIMEOUT_SECONDS} seconds")
+ return False
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install dependencies: {e}")
- print(f" Output: {e.output if hasattr(e, 'output') else 'No output'}")
+ tail = _output_tail(e.stderr)
+ print(f" pip said:\n{tail}" if tail else " pip printed nothing on stderr")
return False
else:
print("⚠️ No requirements.txt found, skipping dependency installation")
diff --git a/tests/test_currentness_hardening.py b/tests/test_currentness_hardening.py
new file mode 100644
index 0000000..1ddb3bb
--- /dev/null
+++ b/tests/test_currentness_hardening.py
@@ -0,0 +1,139 @@
+"""check_google_currentness: wrong-shape feeds exit 3 cleanly, fetches retry once (no network)."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import urllib.error
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+SPEC = importlib.util.spec_from_file_location(
+ "currentness_hardening", ROOT / "scripts" / "check_google_currentness.py"
+)
+MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MODULE)
+
+GOOD_STATUS = json.dumps([{"service_name": "Ranking", "begin": "2026-10-01T00:00:00+00:00"}]).encode()
+GOOD_RSS = (
+ b"<rss><channel><item><pubDate>Mon, 05 Oct 2026 10:00:00 GMT</pubDate></item></channel></rss>"
+)
+
+
+def _ledger(root: Path) -> None:
+ (root / "data").mkdir()
+ (root / "data" / "google-updates.json").write_text(
+ json.dumps(
+ {
+ "last_verified": "2026-10-20",
+ "source_watch": [
+ {"id": key, "url": url, "review_mode": "automated"}
+ for key, url in MODULE.AUTOMATED_SOURCES.items()
+ ],
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+ "payload",
+ [b'{"incidents": []}', b'["not an object"]', b'[{"service_name": "Ranking", "begin": 5}]', b"[1, 2]"],
+)
+def test_status_feed_with_wrong_shape_raises_a_clear_value_error(payload):
+ with pytest.raises(ValueError, match="official status feed"):
+ MODULE.latest_ranking_incident(payload)
+
+
+def test_rss_with_unparseable_date_raises_a_clear_value_error():
+ payload = b"<rss><channel><item><pubDate>not a date</pubDate></item></channel></rss>"
+ with pytest.raises(ValueError):
+ MODULE.latest_documentation_update(payload)
+
+
+def test_good_payloads_still_parse():
+ assert MODULE.latest_ranking_incident(GOOD_STATUS).isoformat() == "2026-10-01"
+ assert MODULE.latest_documentation_update(GOOD_RSS).isoformat() == "2026-10-05"
+
+
+def _run_main(monkeypatch, tmp_path, capsys, fetch, *extra):
+ _ledger(tmp_path)
+ monkeypatch.setattr(MODULE, "_fetch", fetch)
+ monkeypatch.setattr(
+ "sys.argv",
+ ["check_google_currentness.py", "--root", str(tmp_path), "--as-of", "2026-10-25", *extra],
+ )
+ code = MODULE.main()
+ return code, capsys.readouterr()
+
+
+def test_main_exits_3_with_a_message_on_a_wrong_shape_payload(monkeypatch, tmp_path, capsys):
+ def fetch(url, timeout):
+ return b'{"unexpected": true}' if "incidents" in url else GOOD_RSS
+
+ code, out = _run_main(monkeypatch, tmp_path, capsys, fetch)
+ assert code == 3
+ assert "unavailable" in out.err and "unexpected shape" in out.err
+ assert "Traceback" not in out.err
+
+
+def test_main_json_reports_unavailable_for_wrong_shape(monkeypatch, tmp_path, capsys):
+ def fetch(url, timeout):
+ return GOOD_STATUS if "incidents" in url else b"<rss><channel><item><pubDate>nope</pubDate></item></channel></rss>"
+
+ code, out = _run_main(monkeypatch, tmp_path, capsys, fetch, "--json")
+ assert code == 3
+ assert json.loads(out.out)["status"] == "unavailable"
+
+
+def test_main_is_current_with_good_payloads(monkeypatch, tmp_path, capsys):
+ code, out = _run_main(
+ monkeypatch, tmp_path, capsys, lambda url, timeout: GOOD_STATUS if "incidents" in url else GOOD_RSS
+ )
+ assert code == 0
+ assert "current" in out.out
+
+
+class _Response:
+ def __init__(self, body: bytes):
+ self._body = body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def read(self):
+ return self._body
+
+
+def test_fetch_retries_once_after_a_url_error(monkeypatch):
+ calls = []
+
+ def urlopen(request, timeout):
+ calls.append(request.full_url)
+ if len(calls) == 1:
+ raise urllib.error.URLError("temporary failure")
+ return _Response(b"ok")
+
+ monkeypatch.setattr(MODULE.urllib.request, "urlopen", urlopen)
+ monkeypatch.setattr(MODULE.time, "sleep", lambda _seconds: None)
+ assert MODULE._fetch("https://example.test/feed", 1.0) == b"ok"
+ assert len(calls) == 2
+
+
+def test_fetch_gives_up_after_the_second_url_error(monkeypatch):
+ calls = []
+
+ def urlopen(request, timeout):
+ calls.append(1)
+ raise urllib.error.URLError("down")
+
+ monkeypatch.setattr(MODULE.urllib.request, "urlopen", urlopen)
+ monkeypatch.setattr(MODULE.time, "sleep", lambda _seconds: None)
+ with pytest.raises(urllib.error.URLError):
+ MODULE._fetch("https://example.test/feed", 1.0)
+ assert len(calls) == 2
diff --git a/tests/test_google_auth_hardening.py b/tests/test_google_auth_hardening.py
new file mode 100644
index 0000000..07dee6b
--- /dev/null
+++ b/tests/test_google_auth_hardening.py
@@ -0,0 +1,108 @@
+"""google_auth hardening: portable chmod and a robust loopback OAuth callback (no network)."""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import socket
+import stat
+import threading
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = ROOT / "skills" / "blog-google" / "scripts"
+
+
+def auth(monkeypatch):
+ monkeypatch.syspath_prepend(str(SCRIPTS))
+ spec = importlib.util.spec_from_file_location("hardening_google_auth", SCRIPTS / "google_auth.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _free_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def _get(port: int, query: str) -> int:
+ try:
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/?{query}", timeout=5) as resp:
+ return resp.status
+ except urllib.error.HTTPError as exc:
+ return exc.code
+
+
+def _listen_in_thread(auth, state, port, timeout=10.0):
+ box = {}
+
+ def run():
+ box["code"] = auth._listen_for_oauth_code(state, timeout=timeout, port=port)
+
+ thread = threading.Thread(target=run)
+ thread.start()
+ for _ in range(100): # wait until the server accepts connections
+ with socket.socket() as probe:
+ if probe.connect_ex(("127.0.0.1", port)) == 0:
+ break
+ time.sleep(0.05)
+ return thread, box
+
+
+def test_write_secret_atomic_works_without_fchmod(auth, tmp_path, monkeypatch):
+ monkeypatch.delattr(os, "fchmod", raising=False)
+ target = tmp_path / "cfg" / "token.json"
+ auth._write_secret_atomic(str(target), '{"a": 1}')
+ assert target.read_text() == '{"a": 1}'
+ if os.name == "posix":
+ assert stat.S_IMODE(target.stat().st_mode) == 0o600
+
+
+def test_callback_ignores_bad_requests_and_waits_for_the_valid_code(auth):
+ port = _free_port()
+ thread, box = _listen_in_thread(auth, "good-state", port)
+ assert _get(port, "state=wrong&code=evil") == 403
+ assert _get(port, "state=good-state") == 400 # valid state but no code: keep waiting
+ assert _get(port, "") == 403
+ assert thread.is_alive()
+ assert _get(port, "state=good-state&code=the-code") == 200
+ thread.join(timeout=10)
+ assert box["code"] == "the-code"
+
+
+def test_callback_returns_none_at_the_deadline(auth):
+ port = _free_port()
+ started = time.monotonic()
+ assert auth._listen_for_oauth_code("s", timeout=0.3, port=port) is None
+ assert time.monotonic() - started < 5
+
+
+def test_callback_reports_a_busy_port_as_oserror(auth):
+ with socket.socket() as holder:
+ holder.bind(("127.0.0.1", 0))
+ holder.listen(1)
+ with pytest.raises(OSError):
+ auth._listen_for_oauth_code("s", timeout=0.2, port=holder.getsockname()[1])
+
+
+def test_run_oauth_flow_prints_a_clear_message_when_the_port_is_busy(auth, tmp_path, monkeypatch, capsys):
+ monkeypatch.setattr(auth, "_load_oauth_client", lambda _path: {"client_id": "id", "client_secret": "s"})
+ monkeypatch.setattr(auth, "_open_browser", lambda _url: None)
+
+ def busy(*_args, **_kwargs):
+ raise OSError(98, "Address already in use")
+
+ monkeypatch.setattr(auth, "_listen_for_oauth_code", busy)
+ with pytest.raises(SystemExit) as exc:
+ auth.run_oauth_flow("client.json")
+ assert exc.value.code == 1
+ err = capsys.readouterr().err
+ assert "8085" in err and "Address already in use" in err
diff --git a/tests/test_hero_hardening.py b/tests/test_hero_hardening.py
new file mode 100644
index 0000000..c925963
--- /dev/null
+++ b/tests/test_hero_hardening.py
@@ -0,0 +1,199 @@
+"""generate_hero: undecodable images skip to the next provider; an existing hero is kept unless --replace."""
+
+from __future__ import annotations
+
+import importlib.util
+import io
+import sys
+from pathlib import Path
+
+import pytest
+
+PIL = pytest.importorskip("PIL")
+from PIL import Image # noqa: E402
+
+ROOT = Path(__file__).resolve().parent.parent
+HERO = ROOT / "scripts" / "generate_hero.py"
+PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
+
+
+def _png(width=40, height=30, color=(10, 120, 200)) -> bytes:
+ out = io.BytesIO()
+ Image.new("RGB", (width, height), color).save(out, format="PNG")
+ return out.getvalue()
+
+
+def _jpeg() -> bytes:
+ out = io.BytesIO()
+ Image.new("RGB", (40, 30), (200, 20, 20)).save(out, format="JPEG")
+ return out.getvalue()
+
+
+def hero(monkeypatch):
+ for name in (
+ "GOOGLE_AI_API_KEY", "GEMINI_API_KEY", "UNSPLASH_ACCESS_KEY", "PEXELS_API_KEY", "PIXABAY_API_KEY",
+ "NANOBANANA_MODEL",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ spec = importlib.util.spec_from_file_location("hero_hardening", HERO)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+CORRUPT_PNG = PNG_MAGIC + b"this is not a real png stream" * 4
+
+
+def test_corrupt_bytes_raise_a_skippable_error(hero):
+ with pytest.raises(RuntimeError):
+ hero._fit_image_bytes(CORRUPT_PNG, 120, 63)
+ with pytest.raises(hero._ImageUnusable):
+ hero._fit_image_bytes(CORRUPT_PNG, 120, 63)
+
+
+def test_truncated_image_raises_a_skippable_error(hero):
+ with pytest.raises(hero._ImageUnusable):
+ hero._fit_image_bytes(_png(400, 300)[:60], 120, 63)
+
+
+def test_decompression_bomb_is_skippable(hero, monkeypatch):
+ monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
+ with pytest.raises(hero._ImageUnusable, match="DecompressionBombError"):
+ hero._fit_image_bytes(_png(400, 300), 120, 63)
+
+
+def test_good_image_is_fitted_to_the_requested_size(hero):
+ fitted = hero._fit_image_bytes(_png(), 120, 63)
+ assert Image.open(io.BytesIO(fitted)).size == (120, 63)
+
+
+def _run_main(hero, monkeypatch, tmp_path, capsys, extra=()):
+ monkeypatch.setattr(
+ sys, "argv",
+ ["generate_hero.py", "--topic", "Topic", "--tags", "a,b", "--out", str(tmp_path / "out"),
+ "--width", "120", "--height", "63", "--json", *extra],
+ )
+ code = hero.main()
+ return code, capsys.readouterr()
+
+
+def test_corrupt_stock_image_skips_to_the_next_provider(hero, monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("UNSPLASH_ACCESS_KEY", "fake")
+
+ def fake_json(url, headers=None):
+ if url.startswith(hero.UNSPLASH_API):
+ return {"results": [{"urls": {"regular": "https://img.example/bad"}, "user": {"name": "U"}}]}
+ if url.startswith(hero.OPENVERSE_API):
+ return {"results": [{"url": "https://img.example/good", "title": "T", "creator": "C", "license": "by"}]}
+ return None
+
+ monkeypatch.setattr(hero, "_http_get_json", fake_json)
+ monkeypatch.setattr(hero, "_download_image", lambda url: CORRUPT_PNG if url.endswith("bad") else _png())
+
+ code, out = _run_main(hero, monkeypatch, tmp_path, capsys)
+
+ assert code == 0, out.out + out.err
+ assert '"source": "openverse"' in out.out
+ assert "decoded" in out.err or "image" in out.err
+ assert (tmp_path / "out" / "hero.png").is_file()
+ assert "Unsplash" not in (tmp_path / "out" / "hero-credit.txt").read_text()
+
+
+def test_every_provider_corrupt_exits_1_with_the_setup_message_not_write_refused(hero, monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("UNSPLASH_ACCESS_KEY", "fake")
+ monkeypatch.setattr(
+ hero, "_http_get_json",
+ lambda url, headers=None: {"results": [{"urls": {"regular": "https://img.example/bad"}, "url": "https://img.example/bad"}]},
+ )
+ monkeypatch.setattr(hero, "_download_image", lambda url: CORRUPT_PNG)
+
+ code, out = _run_main(hero, monkeypatch, tmp_path, capsys)
+
+ assert code == 1
+ assert "no-image-gen-path" in out.out
+ assert "output-write-refused" not in out.out
+
+
+def test_write_errors_are_still_reported_as_write_refused(hero, monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("UNSPLASH_ACCESS_KEY", "fake")
+ monkeypatch.setattr(
+ hero, "_http_get_json",
+ lambda url, headers=None: {"results": [{"urls": {"regular": "https://img.example/good"}, "user": {}}]},
+ )
+ monkeypatch.setattr(hero, "_download_image", lambda url: _png())
+
+ def refuse(path, data):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(hero, "_atomic_write_bytes", refuse)
+ code, out = _run_main(hero, monkeypatch, tmp_path, capsys)
+
+ assert code == 1
+ assert "output-write-refused" in out.out
+
+
+def test_successful_write_removes_stale_sibling_heroes(hero, tmp_path):
+ for name in ("hero.png", "hero.jpeg", "hero.webp"):
+ (tmp_path / name).write_bytes(b"stale")
+ other = tmp_path / "hero-credit.txt"
+ other.write_text("keep")
+ unrelated = tmp_path / "hero2.png"
+ unrelated.write_bytes(b"keep")
+
+ path = hero._write_hero(tmp_path, _jpeg())
+
+ assert path == tmp_path / "hero.jpg"
+ assert sorted(p.name for p in tmp_path.iterdir()) == ["hero-credit.txt", "hero.jpg", "hero2.png"]
+
+
+def test_failed_write_keeps_the_existing_hero(hero, monkeypatch, tmp_path):
+ (tmp_path / "hero.png").write_bytes(b"existing")
+
+ def refuse(path, data):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(hero, "_atomic_write_bytes", refuse)
+ with pytest.raises(OSError):
+ hero._write_hero(tmp_path, _jpeg())
+ assert (tmp_path / "hero.png").read_bytes() == b"existing"
+
+
+def test_rewriting_the_same_extension_replaces_in_place(hero, tmp_path):
+ (tmp_path / "hero.png").write_bytes(b"old")
+ path = hero._write_hero(tmp_path, _png())
+ assert path == tmp_path / "hero.png"
+ assert path.read_bytes() == _png()
+
+
+def test_a_hero_already_in_the_folder_is_kept_and_no_provider_runs(hero, monkeypatch, tmp_path, capsys):
+ out_dir = tmp_path / "out"
+ out_dir.mkdir()
+ (out_dir / "hero.png").write_bytes(b"placed by the user")
+ monkeypatch.setenv("UNSPLASH_ACCESS_KEY", "fake")
+ monkeypatch.setattr(hero, "_http_get_json", lambda *a, **k: pytest.fail("no provider may run"))
+
+ code, out = _run_main(hero, monkeypatch, tmp_path, capsys)
+
+ assert code == 0
+ assert '"source": "existing"' in out.out
+ assert (out_dir / "hero.png").read_bytes() == b"placed by the user"
+ assert sorted(p.name for p in out_dir.iterdir()) == ["hero.png"]
+
+
+def test_replace_generates_a_new_hero_and_removes_the_old_one(hero, monkeypatch, tmp_path, capsys):
+ out_dir = tmp_path / "out"
+ out_dir.mkdir()
+ (out_dir / "hero.webp").write_bytes(b"old")
+ monkeypatch.setattr(
+ hero, "_http_get_json",
+ lambda url, headers=None: {"results": [{"url": "https://img.example/good", "title": "T", "creator": "C", "license": "by"}]},
+ )
+ monkeypatch.setattr(hero, "_download_image", lambda url: _png())
+
+ code, out = _run_main(hero, monkeypatch, tmp_path, capsys, extra=("--replace",))
+
+ assert code == 0, out.out + out.err
+ assert '"source": "openverse"' in out.out
+ assert (out_dir / "hero.png").is_file() and not (out_dir / "hero.webp").exists()
diff --git a/tests/test_install_ps1_python_detection.py b/tests/test_install_ps1_python_detection.py
new file mode 100644
index 0000000..59d6106
--- /dev/null
+++ b/tests/test_install_ps1_python_detection.py
@@ -0,0 +1,30 @@
+"""install.ps1 must not accept the first python on PATH blindly (Microsoft Store stubs)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+INSTALL = (ROOT / "install.ps1").read_text(encoding="utf-8")
+
+
+def _function(name: str) -> str:
+ start = INSTALL.index(f"function {name}")
+ end = INSTALL.find("\nfunction ", start + 1)
+ return INSTALL[start:] if end < 0 else INSTALL[start:end]
+
+
+def test_main_uses_the_validating_finder_not_a_bare_get_command() -> None:
+ main = _function("Main")
+ assert "$PythonCmd = Find-Python311" in main
+ assert "Get-Command python3" not in main
+ assert "Get-Command python " not in main
+
+
+def test_finder_tries_python_python3_and_py_and_tests_each() -> None:
+ finder = _function("Find-Python311")
+ assert '@("python", "python3", "py")' in finder
+ assert "Test-Python311 $candidate" in finder
+ assert "-CommandType Application" in finder
+ # Falls back to the first candidate so the existing warning paths still work.
+ assert "return $first" in finder
diff --git a/tests/test_quality_gate.py b/tests/test_quality_gate.py
index affb133..fb5dfb9 100644
--- a/tests/test_quality_gate.py
+++ b/tests/test_quality_gate.py
@@ -23,6 +23,22 @@ def _copy_fixture(name: str, tmp_path: Path) -> Path:
return target
+def _make_claude_blog_root(root: Path) -> None:
+ manifest = root / ".claude-plugin" / "plugin.json"
+ manifest.parent.mkdir(parents=True, exist_ok=True)
+ manifest.write_text(json.dumps({"name": "claude-blog"}), encoding="utf-8")
+
+
+def _git(cwd: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)
+
+
+def _git_repo(root: Path) -> None:
+ _git(root, "init", "-q", ".")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "Test")
+
+
def test_passing_post_exits_zero(tmp_path, capsys):
post = _copy_fixture("blog_pass.md", tmp_path)
score = analyze_blog.analyze_file(str(post))["score"]["total"]
@@ -43,6 +59,7 @@ def test_failing_post_exits_one(tmp_path, capsys):
def test_selection_skips_non_blog_paths(tmp_path):
+ _make_claude_blog_root(tmp_path)
skill_file = tmp_path / "skills" / "blog" / "SKILL.md"
skill_file.parent.mkdir(parents=True)
skill_file.write_text(
@@ -92,6 +109,7 @@ def test_selection_skips_non_blog_paths(tmp_path):
def test_selection_uses_lexical_path_for_symlinks(tmp_path):
+ _make_claude_blog_root(tmp_path)
docs_dir = tmp_path / "docs"
posts_dir = tmp_path / "posts"
docs_dir.mkdir()
@@ -168,3 +186,105 @@ def test_invalid_utf8_returns_structured_json_error(tmp_path):
assert "error" in payload
assert "Could not analyze" in payload["error"]
assert "Traceback" not in result.stderr
+
+
+def test_docs_post_is_gated_outside_a_claude_blog_checkout(tmp_path):
+ post = tmp_path / "docs" / "post.md"
+ post.parent.mkdir()
+ post.write_text((FIXTURES / "blog_fail.md").read_text(encoding="utf-8"), encoding="utf-8")
+
+ assert not quality_gate.is_excluded_path(post, root=tmp_path)
+ assert not quality_gate.is_excluded_path(post)
+ assert quality_gate.is_blog_post(post, root=tmp_path)
+
+
+def test_exclusion_needs_the_claude_blog_manifest_name(tmp_path):
+ manifest = tmp_path / ".claude-plugin" / "plugin.json"
+ manifest.parent.mkdir()
+ manifest.write_text(json.dumps({"name": "someone-elses-plugin"}), encoding="utf-8")
+ post = tmp_path / "docs" / "post.md"
+ post.parent.mkdir()
+ post.write_text("---\ntitle: T\ndescription: D\n---\n", encoding="utf-8")
+
+ assert not quality_gate.is_excluded_path(post, root=tmp_path)
+ manifest.write_text("not json", encoding="utf-8")
+ assert not quality_gate.is_excluded_path(post, root=tmp_path)
+
+
+def test_exclusion_applies_inside_a_claude_blog_checkout_without_a_root_argument(tmp_path):
+ _make_claude_blog_root(tmp_path)
+ inside = tmp_path / "skills" / "x" / "SKILL.md"
+ outside = tmp_path / "posts" / "post.md"
+
+ assert quality_gate.is_excluded_path(inside)
+ assert not quality_gate.is_excluded_path(outside)
+
+
+def test_failing_post_staged_under_docs_is_gated(tmp_path):
+ """Regression: a failing post under docs/ in a normal repo used to pass silently."""
+ _git_repo(tmp_path)
+ post = tmp_path / "docs" / "post.md"
+ post.parent.mkdir()
+ post.write_text((FIXTURES / "blog_fail.md").read_text(encoding="utf-8"), encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+
+ result = subprocess.run(
+ [sys.executable, str(SCRIPT), "--select", "--staged"],
+ cwd=tmp_path, capture_output=True, text=True, check=False,
+ )
+
+ assert result.returncode == 1, result.stdout + result.stderr
+ assert "docs/post.md" in result.stdout
+
+
+def test_staged_files_use_nul_separation_and_the_repo_top_level(tmp_path, monkeypatch):
+ """Regression: names with spaces or accents were quoted, and subdirectory runs lost the prefix."""
+ _git_repo(tmp_path)
+ sub = tmp_path / "sub"
+ sub.mkdir()
+ fail = (FIXTURES / "blog_fail.md").read_text(encoding="utf-8")
+ (tmp_path / "caf\u00e9 post.md").write_text(fail, encoding="utf-8")
+ (sub / "in sub.md").write_text(fail, encoding="utf-8")
+ (tmp_path / "gone.md").write_text(fail, encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "-c", "core.quotepath=true", "commit", "-q", "-m", "seed")
+ (tmp_path / "gone.md").unlink()
+ _git(tmp_path, "rm", "-q", "--cached", "gone.md")
+ (tmp_path / "new post.md").write_text(fail, encoding="utf-8")
+ (tmp_path / "caf\u00e9 post.md").write_text(fail + "\nchange\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+
+ monkeypatch.chdir(sub)
+ staged = {Path(item).resolve() for item in quality_gate._staged_files()}
+
+ assert staged == {
+ (tmp_path / "new post.md").resolve(),
+ (tmp_path / "caf\u00e9 post.md").resolve(),
+ }
+
+
+def test_skipped_files_are_counted_in_text_and_json(tmp_path, capsys):
+ _make_claude_blog_root(tmp_path)
+ skipped_doc = tmp_path / "docs" / "guide.md"
+ skipped_doc.parent.mkdir()
+ skipped_doc.write_text("---\ntitle: T\ndescription: D\n---\n", encoding="utf-8")
+ notes = tmp_path / "notes.md"
+ notes.write_text("# no frontmatter\n", encoding="utf-8")
+ post = _copy_fixture("blog_pass.md", tmp_path)
+
+ assert quality_gate.main(["--select", str(skipped_doc), str(notes), str(post)]) == 0
+ text = capsys.readouterr().out
+ assert "1 post(s) checked" in text
+ assert "2 file(s) skipped" in text
+
+ assert quality_gate.main(["--select", "--format", "json", str(skipped_doc), str(notes), str(post)]) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert {Path(item["file"]).name for item in payload["skipped"]} == {"guide.md", "notes.md"}
+ assert all(item["reason"] for item in payload["skipped"])
+
+
+def test_nothing_skipped_prints_no_skip_line(tmp_path, capsys):
+ post = _copy_fixture("blog_pass.md", tmp_path)
+
+ assert quality_gate.main([str(post)]) == 0
+ assert "skipped" not in capsys.readouterr().out
diff --git a/tests/test_render_hardening.py b/tests/test_render_hardening.py
new file mode 100644
index 0000000..06ebea3
--- /dev/null
+++ b/tests/test_render_hardening.py
@@ -0,0 +1,91 @@
+"""Renderer hardening: portable symlink refusal, HTML-safe JSON-LD, canonical validation."""
+
+import importlib.util
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+SCRIPT = ROOT / "scripts" / "blog_render.py"
+SPEC = importlib.util.spec_from_file_location("render_hardening", SCRIPT)
+RENDER = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(RENDER)
+
+
+def _source(title="Hardening Post", canonical="https://example.com/blog/hardening/"):
+ return (
+ f"---\ntitle: {title}\ndescription: A short description of the post.\n"
+ f"date: 2026-10-10\nauthor: Alex Rivera\ncanonical: {canonical}\nslug: hardening\n---\n\n"
+ "Body text for the hardening post.\n"
+ )
+
+
+def _run(tmp_path, text):
+ source = tmp_path / "hardening.md"
+ source.write_bytes(text.encode("utf-8"))
+ result = subprocess.run(
+ [sys.executable, str(SCRIPT), "--md", str(source), "--out-dir", str(tmp_path), "--pdf-engine", "none"],
+ capture_output=True, text=True,
+ )
+ return result
+
+
+def test_read_works_without_o_nofollow(monkeypatch, tmp_path):
+ """Windows has no os.O_NOFOLLOW; the reader must still work and still refuse symlinks."""
+ monkeypatch.delattr(os, "O_NOFOLLOW", raising=False)
+ plain = tmp_path / "plain.md"
+ plain.write_text("hello", encoding="utf-8")
+ assert RENDER._read_md_bytes_safely(plain) == b"hello"
+ link = tmp_path / "link.md"
+ try:
+ link.symlink_to(plain)
+ except OSError:
+ pytest.skip("symlinks unavailable")
+ with pytest.raises(ValueError, match="symlink"):
+ RENDER._read_md_bytes_safely(link)
+
+
+def test_read_refuses_symlink_with_o_nofollow(tmp_path):
+ plain = tmp_path / "plain.md"
+ plain.write_text("hello", encoding="utf-8")
+ link = tmp_path / "link.md"
+ try:
+ link.symlink_to(plain)
+ except OSError:
+ pytest.skip("symlinks unavailable")
+ with pytest.raises(ValueError, match="symlink"):
+ RENDER._read_md_bytes_safely(link)
+
+
+def test_json_ld_escapes_html_significant_characters():
+ fm = {"title": "<!--<script>alert(1)</script> & more", "author": "A", "date": "2026-10-10"}
+ out = RENDER._build_json_ld(fm, 10, "https://example.com/hero.png")
+ assert "<" not in out and ">" not in out and "&" not in out
+ assert json.loads(out)["headline"] == fm["title"]
+
+
+def test_rendered_page_keeps_hostile_title_inert(tmp_path):
+ result = _run(tmp_path, _source(title='"<!--<script>x</script> & y"'))
+ assert result.returncode == 0, result.stderr
+ page = (tmp_path / "hardening.html").read_text(encoding="utf-8")
+ block = re.search(r'<script type="application/ld\+json">(.*?)</script>', page, re.DOTALL).group(1)
+ assert "<!--" not in block and "<script" not in block
+ assert json.loads(block)["headline"] == "<!--<script>x</script> & y"
+
+
[email protected]("canonical", ["http:", "https://", "ftp://example.com/x", "/relative/path", "example.com/post"])
+def test_bad_canonical_gives_a_clear_error_not_a_traceback(tmp_path, canonical):
+ result = _run(tmp_path, _source(canonical=f'"{canonical}"'))
+ assert result.returncode == 1
+ assert "canonical" in result.stderr
+ assert "Traceback" not in result.stderr and "IndexError" not in result.stderr
+
+
+def test_valid_canonical_still_renders(tmp_path):
+ result = _run(tmp_path, _source())
+ assert result.returncode == 0, result.stderr
diff --git a/tests/test_runtime_fixes.py b/tests/test_runtime_fixes.py
index cf0cef0..c3bfb8e 100644
--- a/tests/test_runtime_fixes.py
+++ b/tests/test_runtime_fixes.py
@@ -444,7 +444,6 @@ Reader-visible evidence.
"breakdown"
]["schema"]
assert schema_points == 4
- assert schema_points <= 4
def test_indonesian_profile_is_declared_only_and_recognizes_supported_signals(
@@ -476,7 +475,9 @@ Lihat [tentang kami](/tentang-kami) dan [hubungi kami](/kontak).
result = analyzer.analyze_file(str(declared))
assert result["language"] == "id"
- assert result["readability"]["reading_model"] == "flesch"
+ expected_model = "flesch" if analyzer.HAS_TEXTSTAT else "flesch-estimate"
+ assert result["readability"]["reading_model"] == expected_model
+ assert result["readability"]["estimated"] is (not analyzer.HAS_TEXTSTAT)
assert result["ai_citation_readiness"]["has_tldr"] is True
assert result["ai_citation_readiness"]["entity_definitions"] >= 1
assert result["originality"]["methodology_count"] >= 1
@@ -484,6 +485,24 @@ Lihat [tentang kami](/tentang-kami) dan [hubungi kami](/kontak).
assert analyzer.analyze_file(str(undeclared))["language"] == "en"
+def test_readability_falls_back_to_estimate_without_textstat(
+ monkeypatch, tmp_path: Path
+) -> None:
+ analyzer = _load("runtime_no_textstat", "scripts/analyze_blog.py")
+ monkeypatch.setattr(analyzer, "HAS_TEXTSTAT", False)
+ post = tmp_path / "post.md"
+ post.write_text(
+ "---\ntitle: Plain Post\nauthor: Jane Doe\n---\n"
+ "# Plain Post\n\nShort sentences read well. Readers like that.\n",
+ encoding="utf-8",
+ )
+
+ readability = analyzer.analyze_file(str(post))["readability"]
+
+ assert readability["reading_model"] == "flesch-estimate"
+ assert readability["estimated"] is True
+
+
def test_runtime_wrappers_require_explicit_setup_without_installing(
monkeypatch, tmp_path: Path
) -> None:
diff --git a/tests/test_scripts_wave3_gate.py b/tests/test_scripts_wave3_gate.py
index e4ea72d..0b69da1 100644
--- a/tests/test_scripts_wave3_gate.py
+++ b/tests/test_scripts_wave3_gate.py
@@ -58,7 +58,10 @@ def test_explicit_file_in_excluded_dir_is_still_checked(tmp_path, subdir):
assert "post.md" in result.stdout
-def test_directory_scan_still_skips_excluded_dirs_and_non_posts(tmp_path):
+def test_directory_scan_skips_claude_blog_own_trees_and_non_posts(tmp_path):
+ manifest = tmp_path / ".claude-plugin" / "plugin.json"
+ manifest.parent.mkdir()
+ manifest.write_text(json.dumps({"name": "claude-blog"}), encoding="utf-8")
good = tmp_path / "posts" / "a.md"
good.parent.mkdir()
good.write_text((FIXTURES / "blog_pass.md").read_text(encoding="utf-8"), encoding="utf-8")
@@ -69,9 +72,20 @@ def test_directory_scan_still_skips_excluded_dirs_and_non_posts(tmp_path):
result = _run(str(tmp_path), "--format", "json", cwd=tmp_path)
payload = json.loads(result.stdout)
assert [Path(item["file"]).name for item in payload["checked"]] == ["a.md"]
+ assert {Path(item["file"]).name for item in payload["skipped"]} == {"b.md", "notes.md"}
assert result.returncode == 0
+def test_directory_scan_gates_docs_posts_outside_a_claude_blog_checkout(tmp_path):
+ failing = tmp_path / "docs" / "b.md"
+ failing.parent.mkdir()
+ failing.write_text((FIXTURES / "blog_fail.md").read_text(encoding="utf-8"), encoding="utf-8")
+ result = _run(str(tmp_path), "--format", "json", cwd=tmp_path)
+ payload = json.loads(result.stdout)
+ assert [Path(item["file"]).name for item in payload["checked"]] == ["b.md"]
+ assert result.returncode == 1
+
+
def test_select_mode_skips_non_posts_for_the_pre_commit_hook(tmp_path):
readme = tmp_path / "README.md"
readme.write_text("# readme\n", encoding="utf-8")
diff --git a/tests/test_scripts_wave3_image.py b/tests/test_scripts_wave3_image.py
index bb7eeb1..ae67f26 100644
--- a/tests/test_scripts_wave3_image.py
+++ b/tests/test_scripts_wave3_image.py
@@ -173,3 +173,13 @@ def test_setup_rejects_a_multiline_key_passed_directly(setup, tmp_path, monkeypa
with pytest.raises(SystemExit):
setup.setup_mcp(f"{GOOGLE_KEY}\nOPENAI_API_KEY={OTHER_KEY}", True, True)
assert not (tmp_path / "settings.json").exists()
+
+
+def test_save_config_works_without_fchmod(setup, tmp_path, monkeypatch):
+ """Windows has no os.fchmod; the config must still be written with a private mode."""
+ monkeypatch.delattr(os, "fchmod", raising=False)
+ target = tmp_path / "settings.json"
+ setup.save_config(target, {"k": "v"}, quiet=True)
+ assert json.loads(target.read_text()) == {"k": "v"}
+ if os.name == "posix":
+ assert stat.S_IMODE(target.stat().st_mode) == 0o600
diff --git a/tests/test_setup_environment_hardening.py b/tests/test_setup_environment_hardening.py
new file mode 100644
index 0000000..f590bd8
--- /dev/null
+++ b/tests/test_setup_environment_hardening.py
@@ -0,0 +1,78 @@
+"""setup_environment scripts: pip failures show pip's stderr tail, and pip has a timeout."""
+
+from __future__ import annotations
+
+import importlib.util
+import subprocess
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+SKILLS = ("blog-google", "blog-audio", "blog-notebooklm")
+
+
+def _env(skill: str, tmp_path: Path, monkeypatch):
+ scripts = ROOT / "skills" / skill / "scripts"
+ monkeypatch.syspath_prepend(str(scripts))
+ spec = importlib.util.spec_from_file_location(f"setup_env_{skill}", scripts / "setup_environment.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ env = module.SkillEnvironment()
+ venv_dir = tmp_path / "venv"
+ venv_dir.mkdir()
+ env.venv_dir = venv_dir
+ env.venv_pip = venv_dir / "pip"
+ env.venv_python = venv_dir / "python"
+ return module, env
+
+
[email protected]("skill", SKILLS)
+def test_pip_failure_prints_the_stderr_tail(skill, tmp_path, monkeypatch, capsys):
+ module, env = _env(skill, tmp_path, monkeypatch)
+ stderr = "\n".join(f"noise {i}" for i in range(50)) + "\nERROR: No matching distribution found for nothing"
+
+ def fail(cmd, **kwargs):
+ raise subprocess.CalledProcessError(1, cmd, output="", stderr=stderr)
+
+ monkeypatch.setattr(module.subprocess, "run", fail)
+ assert env.ensure_venv() is False
+ captured = capsys.readouterr()
+ text = captured.out + captured.err
+ assert "No matching distribution found for nothing" in text
+ assert "noise 0\n" not in text # only the tail, not the whole log
+
+
[email protected]("skill", SKILLS)
+def test_pip_runs_with_a_timeout_and_a_timeout_is_a_clean_failure(skill, tmp_path, monkeypatch, capsys):
+ module, env = _env(skill, tmp_path, monkeypatch)
+ seen = []
+
+ def hang(cmd, **kwargs):
+ seen.append(kwargs.get("timeout"))
+ raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))
+
+ monkeypatch.setattr(module.subprocess, "run", hang)
+ assert env.ensure_venv() is False
+ assert seen and seen[0] == module.PIP_TIMEOUT_SECONDS
+ captured = capsys.readouterr()
+ assert "did not finish" in captured.out + captured.err
+ assert "Traceback" not in captured.out + captured.err
+
+
+def test_output_tail_handles_none_bytes_and_long_text():
+ spec = importlib.util.spec_from_file_location(
+ "setup_env_tail", ROOT / "skills" / "blog-google" / "scripts" / "setup_environment.py"
+ )
+ # runtime_paths sits beside the script and is imported by it
+ import sys
+
+ sys.path.insert(0, str(ROOT / "skills" / "blog-google" / "scripts"))
+ try:
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ finally:
+ sys.path.remove(str(ROOT / "skills" / "blog-google" / "scripts"))
+ assert module._output_tail(None) == ""
+ assert module._output_tail(b"a\nb") == "a\nb"
+ assert module._output_tail("\n".join(str(i) for i in range(100)), lines=3) == "97\n98\n99"