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
fix(hero): make paid generation opt-in and protect existing heroes
Agrici Daniel6f2d815ab257
diff --git a/scripts/generate_hero.py b/scripts/generate_hero.pyindex daaaf6d..fc808f4 100644--- a/scripts/generate_hero.py+++ b/scripts/generate_hero.py@@ -9,21 +9,37 @@ in the requested output directory.Ladder: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)+ 2. Direct Gemini API via google-genai SDK. Paid: runs only with+ `--allow-paid` AND GOOGLE_AI_API_KEY or GEMINI_API_KEY. Without the flag a+ set key is ignored, stderr says so once, and the JSON result carries+ `"paid_gemini_skipped": true`. Pass the flag only after the user approves+ the cost.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 instructionsA 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.+source `existing`; no provider runs. It counts only when it is a regular,+non-empty file whose header matches its extension's format and is at least+1200x630, the minimum delivery Gates 1 and 2 enforce. The first valid one in+renderer order is kept and invalid siblings are removed; with no valid one, a+new hero replaces the invalid files. Either way the JSON result lists the+invalid files under `replaced_invalid`. `--replace` generates a new one+instead. A symlinked `hero.*` stops the run with nothing written or deleted,+and every write target (each `hero.*` and `hero-credit.txt`) is checked+before any provider runs.+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.+oversized) is skipped and the next step runs. The new image and+`hero-credit.txt` are staged as temp files and renamed into place together;+only then is any stale `hero.*` file of another extension removed, so the+renderer cannot pick it. A refused credit write leaves the old files alone.Usage:python3 scripts/generate_hero.py --topic "<title>" --tags "a,b,c" \\- --out <draft-folder> [--width 1200] [--height 630] [--replace] [--json]+ --out <draft-folder> [--width 1200] [--height 630] [--replace] \\+ [--allow-paid] [--json]Returns 0 on success (hero.<ext> + hero-credit.txt written). Returns 1when every ladder step is exhausted with no successful generation.@@ -39,6 +55,7 @@ import jsonimport osimport reimport socket+import statimport sysimport tempfileimport urllib.parse@@ -58,6 +75,8 @@ def _project_version() -> str:OUTPUT_FILE_PREFIX = "hero"+CREDIT_FILE_NAME = "hero-credit.txt"+PAID_SKIPPED_MESSAGE = "Paid Gemini generation skipped: pass --allow-paid after the user approves the cost."DEFAULT_WIDTH = 1200DEFAULT_HEIGHT = 630DEFAULT_GEMINI_MODEL = os.environ.get("NANOBANANA_MODEL") or "gemini-nano-banana-2.1"@@ -373,28 +392,204 @@ def _fit_image_bytes(data: bytes, width: int, height: int) -> bytes:HERO_EXTENSIONS = (".png", ".jpg", ".jpeg", ".webp")+# Format each hero extension must carry; blog_preflight.py checks the same map.+_HERO_FORMATS = {".png": "png", ".jpg": "jpeg", ".jpeg": "jpeg", ".webp": "webp"}+# Minimum hero size Gates 1 and 2 of blog_preflight.py enforce. Kept as local+# numbers (not imported) and pinned equal by tests/test_hero_safety_gates.py.+HERO_MIN_WIDTH = 1200+HERO_MIN_HEIGHT = 630+# SOFn markers that carry frame dimensions (C4 DHT, C8 JPG and CC DAC do not).+_JPEG_SOF_MARKERS = frozenset(range(0xC0, 0xD0)) - {0xC4, 0xC8, 0xCC}+_JPEG_MAX_SEGMENTS = 4096+++def _png_dimensions(f) -> Optional[tuple[int, int]]:+ head = f.read(24)+ if len(head) < 24 or not head.startswith(b"\x89PNG\r\n\x1a\n") or head[12:16] != b"IHDR":+ return None+ return int.from_bytes(head[16:20], "big"), int.from_bytes(head[20:24], "big")-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+def _webp_dimensions(f) -> Optional[tuple[int, int]]:+ head = f.read(30)+ if len(head) < 16 or head[:4] != b"RIFF" or head[8:12] != b"WEBP":+ return None+ chunk = head[12:16]+ if chunk == b"VP8 " and len(head) >= 30 and head[23:26] == b"\x9d\x01\x2a":+ return int.from_bytes(head[26:28], "little") & 0x3FFF, int.from_bytes(head[28:30], "little") & 0x3FFF+ if chunk == b"VP8L" and len(head) >= 25 and head[20] == 0x2F:+ bits = int.from_bytes(head[21:25], "little")+ return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1+ if chunk == b"VP8X" and len(head) >= 30:+ return int.from_bytes(head[24:27], "little") + 1, int.from_bytes(head[27:30], "little") + 1+ return None+++def _jpeg_dimensions(f) -> Optional[tuple[int, int]]:+ """Walk JPEG segments (seeking past their bodies) to the first SOFn frame header."""+ if f.read(2) != b"\xff\xd8":+ return None+ for _ in range(_JPEG_MAX_SEGMENTS):+ if f.read(1) != b"\xff":+ return None+ marker = f.read(1)+ for _fill in range(64): # optional 0xFF fill bytes before the marker code+ if marker != b"\xff":+ break+ marker = f.read(1)+ if not marker or marker == b"\xff":+ return None+ code = marker[0]+ if code == 0x01 or 0xD0 <= code <= 0xD7:+ continue # standalone markers have no length field+ if code in (0xD9, 0xDA):+ return None # end of image or scan data before any frame header+ length_bytes = f.read(2)+ if len(length_bytes) < 2:+ return None+ length = int.from_bytes(length_bytes, "big")+ if length < 2:+ return None+ if code in _JPEG_SOF_MARKERS:+ body = f.read(5) # precision, height, width+ if len(body) < 5:+ return None+ return int.from_bytes(body[3:5], "big"), int.from_bytes(body[1:3], "big")+ f.seek(length - 2, os.SEEK_CUR)+ return None+++_DIMENSION_READERS = {"png": _png_dimensions, "jpeg": _jpeg_dimensions, "webp": _webp_dimensions}+++def _hero_problem(path: Path) -> Optional[str]:+ """Return why path is not a usable hero, or None when it is.++ Cheap checks without Pillow: a regular non-symlink file, non-empty, the+ signature of its extension's format, and a header whose size meets the+ HERO_MIN_WIDTH x HERO_MIN_HEIGHT minimum that delivery Gates 1 and 2+ enforce. A smaller hero would be kept here and then block delivery, so it+ counts as invalid. Full decoding is left to blog_preflight.py.+ """+ fmt = _HERO_FORMATS.get(path.suffix)+ if fmt is None:+ return "unsupported extension"+ try:+ info = path.lstat()+ except OSError as e:+ return f"cannot be inspected ({e})"+ if not stat.S_ISREG(info.st_mode):+ return "not a regular file"+ if info.st_size == 0:+ return "empty file"+ try:+ fd = os.open(str(path), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))+ with os.fdopen(fd, "rb") as f:+ dims = _DIMENSION_READERS[fmt](f)+ except OSError as e:+ return f"unreadable ({e})"+ if dims is None:+ return f"no valid {fmt.upper()} header"+ width, height = dims+ if width < 1 or height < 1:+ return "header reports zero width or height"+ if width < HERO_MIN_WIDTH or height < HERO_MIN_HEIGHT:+ return f"{width}x{height} is below the {HERO_MIN_WIDTH}x{HERO_MIN_HEIGHT} delivery minimum"return None-def _write_hero(out_dir: Path, img_bytes: bytes) -> Path:- """Write hero.<ext> and remove stale hero.* siblings of other extensions.+def _hero_candidates(out_dir: Path) -> list[Path]:+ """Lowercase hero.<ext> paths in scripts/blog_render.py preference order."""+ return [out_dir / f"{OUTPUT_FILE_PREFIX}{extension}" for extension in HERO_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.+def _symlinked_heroes(out_dir: Path) -> list[Path]:+ return [candidate for candidate in _hero_candidates(out_dir) if candidate.is_symlink()]+++def _survey_heroes(out_dir: Path) -> tuple[Optional[Path], list[tuple[Path, str]]]:+ """Return (first valid hero, invalid regular hero files with reasons).++ The valid hero is the first in renderer preference order. Symlinks and+ other non-regular entries are in neither list; main refuses them.+ """+ valid: Optional[Path] = None+ invalid: list[tuple[Path, str]] = []+ for candidate in _hero_candidates(out_dir):+ if candidate.is_symlink() or not candidate.is_file():+ continue+ problem = _hero_problem(candidate)+ if problem is not None:+ invalid.append((candidate, problem))+ elif valid is None:+ valid = candidate+ return valid, invalid+++def _existing_hero(out_dir: Path) -> Optional[Path]:+ """Return the first valid hero already in out_dir, if any (symlinks do not count)."""+ return _survey_heroes(out_dir)[0]+++def _refuse_unwritable_target(path: Path) -> None:+ """_refuse_unsafe_target plus a writability check on an existing file."""+ _refuse_unsafe_target(path)+ if os.path.lexists(path) and not os.access(path, os.W_OK):+ raise ValueError(f"refusing unwritable output path: {path}")+++def _refuse_unsafe_target(path: Path) -> None:+ """Raise ValueError when path is reached through a symlink or is not a regular file."""+ unsafe = _symlink_component(path)+ if unsafe is not None:+ raise ValueError(f"refusing symlink output path component: {unsafe}")+ if os.path.lexists(path) and not stat.S_ISREG(path.lstat().st_mode):+ raise ValueError(f"refusing non-regular output path: {path}")+++def _stage_temp(path: Path, data: bytes) -> str:+ """Write data to a temp file beside path and return the temp path."""+ 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)+ except Exception:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+ return tmp+++def _write_hero(out_dir: Path, img_bytes: bytes, credit_text: str) -> Path:+ """Write hero.<ext> and hero-credit.txt together, then remove stale hero.* siblings.++ Both are staged as temp files in out_dir and renamed into place only after+ both writes succeeded, so a refused credit (symlink, directory, disk full)+ leaves the old hero, old credit and siblings untouched. 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 both renames, 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}"+ credit_path = out_dir / CREDIT_FILE_NAME+ _refuse_unsafe_target(hero_path)+ _refuse_unsafe_target(credit_path)+ staged: list[tuple[str, Path]] = []+ try:+ staged.append((_stage_temp(hero_path, img_bytes), hero_path))+ staged.append((_stage_temp(credit_path, credit_text.encode("utf-8")), credit_path))+ for tmp, target in staged:+ os.replace(tmp, str(target))+ except Exception:+ for tmp, _target in staged:+ try:+ os.unlink(tmp)+ except OSError:+ pass # already renamed into place+ raise+ for stale in _hero_candidates(out_dir):if stale != hero_path and (stale.is_symlink() or stale.is_file()):stale.unlink()return hero_path@@ -469,8 +664,16 @@ def _http_get_json(url: str, headers: Optional[dict] = None) -> Optional[dict]: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."""+def _paid_key_set() -> bool:+ return bool(os.environ.get("GOOGLE_AI_API_KEY") or os.environ.get("GEMINI_API_KEY"))+++def _try_gemini(+ topic: str, tags: list[str], out_dir: Path, width: int, height: int, model: str, allow_paid: bool = False+) -> Optional[dict]:+ """Ladder step 2: direct Gemini API. Paid, so it runs only with allow_paid and a key."""+ if not allow_paid:+ return Noneapi_key = os.environ.get("GOOGLE_AI_API_KEY") or os.environ.get("GEMINI_API_KEY")if not api_key:return None@@ -520,10 +723,8 @@ 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 = _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",+ hero_path = _write_hero(+ out_dir, img_bytes, f"AI-generated via {used_model}. No attribution required.\nPrompt: {prompt}\n",)return {"source": "gemini", "model": used_model, "path": str(hero_path)}@@ -550,14 +751,13 @@ def _try_unsplash(query: str, out_dir: Path, width: int, height: int) -> Optionaexcept RuntimeError as e:print(f"[image] {e}", file=sys.stderr)return None- hero_path = _write_hero(out_dir, 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')- _atomic_write_text(out_dir / "hero-credit.txt", credit)+ hero_path = _write_hero(out_dir, img_bytes, credit)return {"source": "unsplash", "path": str(hero_path)}@@ -581,13 +781,12 @@ 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 = _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'f'Source: {item.get("url", img_url)}\n')- _atomic_write_text(out_dir / "hero-credit.txt", credit)+ hero_path = _write_hero(out_dir, img_bytes, credit)return {"source": "pexels", "path": str(hero_path)}@@ -614,13 +813,12 @@ def _try_pixabay(query: str, out_dir: Path, width: int, height: int) -> Optionalexcept RuntimeError as e:print(f"[image] {e}", file=sys.stderr)return None- 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'f'Source: {item.get("pageURL", img_url)}\n')- _atomic_write_text(out_dir / "hero-credit.txt", credit)+ hero_path = _write_hero(out_dir, img_bytes, credit)return {"source": "pixabay", "path": str(hero_path)}@@ -680,16 +878,13 @@ def _try_openverse(topic: str, tags: list[str], out_dir: Path, width: int, heighprint(f"[image] {e}", file=sys.stderr)return None- hero_path = _write_hero(out_dir, 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- _atomic_write_text(- out_dir / "hero-credit.txt",- f'"{title}" by {creator}\nLicense: {license_name}\nSource: {source}\nURL: {src_url}\n',+ hero_path = _write_hero(+ out_dir, img_bytes, f'"{title}" by {creator}\nLicense: {license_name}\nSource: {source}\nURL: {src_url}\n',)return {"source": "openverse", "creator": creator, "license": license_name, "path": str(hero_path)}@@ -707,58 +902,91 @@ def main() -> int:action="store_true",help="Generate a new hero even when the output directory already has one (default: keep it)",)+ parser.add_argument(+ "--allow-paid",+ action="store_true",+ help=(+ "Allow the paid Gemini route (needs GOOGLE_AI_API_KEY or GEMINI_API_KEY). Pass it only after "+ "the user approves the cost; without it a set key is ignored and the free steps run."+ ),+ )parser.add_argument("--json", action="store_true", help="Emit JSON result to stdout")args = parser.parse_args()- dims_ok, dims_error = _validate_dimensions(args.width, args.height)- if not dims_ok:- msg = f"ERROR: {dims_error}"+ def fail(code: str, msg: str, **extra) -> int:if args.json:- print(json.dumps({"error": "invalid-dimensions", "message": msg}))+ print(json.dumps({"error": code, "message": msg, **extra}))else:print(msg, file=sys.stderr)return 1+ dims_ok, dims_error = _validate_dimensions(args.width, args.height)+ if not dims_ok:+ return fail("invalid-dimensions", f"ERROR: {dims_error}")+raw_out_dir = Path(args.out)unsafe = _symlink_component(raw_out_dir)if unsafe is not None:- msg = f"ERROR: refusing symlink output directory component {unsafe}"- if args.json:- print(json.dumps({"error": "out-dir-symlink", "message": msg}))- else:- print(msg, file=sys.stderr)- return 1+ return fail("out-dir-symlink", f"ERROR: refusing symlink output directory component {unsafe}")out_dir = raw_out_dir.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+ return fail("out-dir-create-failed", f"ERROR: cannot create output directory {out_dir}: {e}")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- existing = _existing_hero(out_dir)+ return fail("out-dir-not-writable", f"ERROR: output directory {out_dir} is not writable")+ symlinked = _symlinked_heroes(out_dir)+ if symlinked:+ # A link may point anywhere: never keep it, write through it, or delete it.+ names = ", ".join(path.name for path in symlinked)+ return fail(+ "hero-symlink",+ f"ERROR: refusing to run: {names} in {out_dir} is a symlink. "+ "Replace it with a regular image file or remove it, then rerun. Nothing was written or deleted.",+ )+ existing, invalid = _survey_heroes(out_dir)+ invalid_names = [path.name for path, _problem in invalid]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.+ # Never overwrite or delete a valid hero that is already there (the+ # contract lets the user place one by hand), and never spend on a+ # second one. Invalid siblings are removed so the renderer cannot+ # embed them ahead of the kept hero.+ for path, problem in invalid:+ print(f"[existing] removing {path.name}: not a usable hero ({problem})", file=sys.stderr)+ try:+ path.unlink()+ except OSError as e:+ return fail("output-write-refused", f"ERROR: cannot remove invalid {path.name}: {e}")result = {"source": "existing", "path": str(existing)}+ if invalid_names:+ result["replaced_invalid"] = invalid_namesif args.json:print(json.dumps(result))else:print(f"OK: kept existing hero {existing} (pass --replace to generate a new one)")return 0+ try:+ # Refuse before any provider runs, so a bad target never costs a generation.+ for target in (*_hero_candidates(out_dir), out_dir / CREDIT_FILE_NAME):+ _refuse_unwritable_target(target)+ except (OSError, ValueError) as e:+ return fail("output-write-refused", f"ERROR: output write refused: {e}. Nothing was written or deleted.")+ for path, problem in invalid:+ print(f"[existing] {path.name} is not a usable hero ({problem}); generating a replacement", file=sys.stderr)++ notes: dict = {}+ if _paid_key_set() and not args.allow_paid:+ print(PAID_SKIPPED_MESSAGE, file=sys.stderr)+ notes["paid_gemini_skipped"] = Truetags = [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)),+ (+ "gemini",+ lambda: _try_gemini(+ args.topic, tags, out_dir, args.width, args.height, args.model, allow_paid=args.allow_paid+ ),+ ),("premium-stock", lambda: _try_premium_stock(args.topic, tags, out_dir, args.width, args.height)),("openverse", lambda: _try_openverse(args.topic, tags, out_dir, args.width, args.height)),]@@ -767,32 +995,27 @@ def main() -> int:try:result = fn()except (OSError, ValueError) as e:- msg = f"ERROR: {name} output write refused: {e}"- if args.json:- print(json.dumps({"error": "output-write-refused", "message": msg}))- else:- print(msg, file=sys.stderr)- return 1+ return fail("output-write-refused", f"ERROR: {name} output write refused: {e}", **notes)if result:+ result.update(notes)+ if invalid_names:+ result["replaced_invalid"] = invalid_namesif 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": (+ return fail(+ "no-image-gen-path",+ ("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, "+ "set GOOGLE_AI_API_KEY or GEMINI_API_KEY and pass --allow-paid once the user approves the cost, "+ "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+ **notes,+ )if __name__ == "__main__":diff --git a/skills/blog-google/scripts/google_auth.py b/skills/blog-google/scripts/google_auth.pyindex 9098f48..eeb6ed6 100644--- a/skills/blog-google/scripts/google_auth.py+++ b/skills/blog-google/scripts/google_auth.py@@ -51,6 +51,8 @@ SERVICE_AUTH = {}OAUTH_REDIRECT_URI = "http://127.0.0.1:8085"+# Seconds an accepted loopback connection may stay silent before it is dropped.+OAUTH_CONNECTION_TIMEOUT = 10.0_SECRET_NAMES = (@@ -580,6 +582,11 @@ def _listen_for_oauth_code(if remaining <= 0:breakserver.timeout = remaining+ # server.timeout only bounds the wait for a connection. The handler+ # applies its own timeout to the accepted socket, so a client that+ # connects and sends nothing (or a browser preconnect) is dropped+ # instead of blocking handle_request past the deadline.+ Handler.timeout = min(remaining, OAUTH_CONNECTION_TIMEOUT)server.handle_request()finally:server.server_close()diff --git a/tests/test_google_auth_hardening.py b/tests/test_google_auth_hardening.pyindex 07dee6b..bd29058 100644--- a/tests/test_google_auth_hardening.py+++ b/tests/test_google_auth_hardening.py@@ -106,3 +106,42 @@ def test_run_oauth_flow_prints_a_clear_message_when_the_port_is_busy(auth, tmp_passert exc.value.code == 1err = capsys.readouterr().errassert "8085" in err and "Address already in use" in err+++def _listen_daemon(auth, state, port, timeout):+ """Like _listen_in_thread, but a daemon thread so a regression cannot hang pytest."""+ box = {}++ def run():+ box["code"] = auth._listen_for_oauth_code(state, timeout=timeout, port=port)++ thread = threading.Thread(target=run, daemon=True)+ thread.start()+ for _ in range(100):+ 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_a_silent_client_cannot_hold_the_listener_past_the_deadline(auth):+ port = _free_port()+ started = time.monotonic()+ thread, box = _listen_daemon(auth, "s", port, timeout=1.0)+ with socket.create_connection(("127.0.0.1", port)):+ thread.join(timeout=8) # connected and silent for the whole window+ assert not thread.is_alive(), "listener blocked on a silent connection"+ assert box["code"] is None+ assert time.monotonic() - started < 6+++def test_a_silent_client_is_dropped_and_the_real_callback_still_lands(auth, monkeypatch):+ monkeypatch.setattr(auth, "OAUTH_CONNECTION_TIMEOUT", 0.3)+ port = _free_port()+ thread, box = _listen_daemon(auth, "good-state", port, timeout=20.0)+ with socket.create_connection(("127.0.0.1", port)):+ assert _get(port, "state=good-state&code=the-code") == 200+ thread.join(timeout=8)+ assert not thread.is_alive()+ assert box["code"] == "the-code"diff --git a/tests/test_hero_hardening.py b/tests/test_hero_hardening.pyindex c925963..c0f32b9 100644--- a/tests/test_hero_hardening.py+++ b/tests/test_hero_hardening.py@@ -127,7 +127,7 @@ def test_write_errors_are_still_reported_as_write_refused(hero, monkeypatch, tmpdef refuse(path, data):raise OSError("disk full")- monkeypatch.setattr(hero, "_atomic_write_bytes", refuse)+ monkeypatch.setattr(hero, "_stage_temp", refuse)code, out = _run_main(hero, monkeypatch, tmp_path, capsys)assert code == 1@@ -142,9 +142,10 @@ def test_successful_write_removes_stale_sibling_heroes(hero, tmp_path):unrelated = tmp_path / "hero2.png"unrelated.write_bytes(b"keep")- path = hero._write_hero(tmp_path, _jpeg())+ path = hero._write_hero(tmp_path, _jpeg(), "new credit")assert path == tmp_path / "hero.jpg"+ assert other.read_text() == "new credit"assert sorted(p.name for p in tmp_path.iterdir()) == ["hero-credit.txt", "hero.jpg", "hero2.png"]@@ -154,15 +155,15 @@ def test_failed_write_keeps_the_existing_hero(hero, monkeypatch, tmp_path):def refuse(path, data):raise OSError("disk full")- monkeypatch.setattr(hero, "_atomic_write_bytes", refuse)+ monkeypatch.setattr(hero, "_stage_temp", refuse)with pytest.raises(OSError):- hero._write_hero(tmp_path, _jpeg())+ hero._write_hero(tmp_path, _jpeg(), "credit")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())+ path = hero._write_hero(tmp_path, _png(), "credit")assert path == tmp_path / "hero.png"assert path.read_bytes() == _png()@@ -170,7 +171,8 @@ def test_rewriting_the_same_extension_replaces_in_place(hero, tmp_path):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")+ placed = _png(1200, 630)+ (out_dir / "hero.png").write_bytes(placed)monkeypatch.setenv("UNSPLASH_ACCESS_KEY", "fake")monkeypatch.setattr(hero, "_http_get_json", lambda *a, **k: pytest.fail("no provider may run"))@@ -178,14 +180,14 @@ def test_a_hero_already_in_the_folder_is_kept_and_no_provider_runs(hero, monkeypassert code == 0assert '"source": "existing"' in out.out- assert (out_dir / "hero.png").read_bytes() == b"placed by the user"+ assert (out_dir / "hero.png").read_bytes() == placedassert 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")+ (out_dir / "hero.webp").write_bytes(b"old") # invalid too; --replace runs either waymonkeypatch.setattr(hero, "_http_get_json",lambda url, headers=None: {"results": [{"url": "https://img.example/good", "title": "T", "creator": "C", "license": "by"}]},diff --git a/tests/test_hero_models_wave3.py b/tests/test_hero_models_wave3.pyindex 8566540..47785a2 100644--- a/tests/test_hero_models_wave3.py+++ b/tests/test_hero_models_wave3.py@@ -78,18 +78,29 @@ def test_environment_override_still_wins(monkeypatch):def test_gemini_api_key_variable_is_accepted(hero, monkeypatch, tmp_path):monkeypatch.delenv("GOOGLE_AI_API_KEY", raising=False)- monkeypatch.setenv("GEMINI_API_KEY", "fake-key-for-test")+ monkeypatch.setenv("GEMINI_API_KEY", "your-test-key")calls = _fake_genai(monkeypatch, {"gemini-nano-banana-2.1": PNG_1X1})- result = hero._try_gemini("topic", ["tag"], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL)+ result = hero._try_gemini("topic", ["tag"], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL, allow_paid=True)assert calls == ["gemini-nano-banana-2.1"]assert result and result["model"] == "gemini-nano-banana-2.1"[email protected]("variable", ["GOOGLE_AI_API_KEY", "GEMINI_API_KEY"])+def test_a_set_key_without_allow_paid_means_no_call(hero, monkeypatch, tmp_path, variable):+ monkeypatch.delenv("GOOGLE_AI_API_KEY", raising=False)+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)+ monkeypatch.setenv(variable, "your-test-key")+ calls = _fake_genai(monkeypatch, {"gemini-nano-banana-2.1": PNG_1X1})+ assert hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL) is None+ assert calls == []+ assert list(tmp_path.iterdir()) == []++def test_no_key_means_no_call(hero, monkeypatch, tmp_path):monkeypatch.delenv("GOOGLE_AI_API_KEY", raising=False)monkeypatch.delenv("GEMINI_API_KEY", raising=False)calls = _fake_genai(monkeypatch, {})- assert hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL) is None+ assert hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL, allow_paid=True) is Noneassert calls == []@@ -103,14 +114,14 @@ def test_no_key_means_no_call(hero, monkeypatch, tmp_path):],)def test_unfixable_errors_stop_the_ladder(hero, monkeypatch, tmp_path, message):- monkeypatch.setenv("GOOGLE_AI_API_KEY", "fake-key-for-test")+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")calls = _fake_genai(monkeypatch, {"gemini-nano-banana-2.1": RuntimeError(message)})- assert hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL) is None+ assert hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL, allow_paid=True) is Noneassert calls == ["gemini-nano-banana-2.1"]def test_model_specific_errors_still_fall_back_to_the_next_model(hero, monkeypatch, tmp_path):- monkeypatch.setenv("GOOGLE_AI_API_KEY", "fake-key-for-test")+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")calls = _fake_genai(monkeypatch,{@@ -118,7 +129,7 @@ def test_model_specific_errors_still_fall_back_to_the_next_model(hero, monkeypat"gemini-3.1-flash-image": PNG_1X1,},)- result = hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL)+ result = hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL, allow_paid=True)assert calls[:2] == ["gemini-nano-banana-2.1", "gemini-3.1-flash-image"]assert result and result["model"] == "gemini-3.1-flash-image"@@ -128,6 +139,6 @@ def test_error_text_never_contains_the_key(hero, monkeypatch, tmp_path, capsys):fake_value = "AI" + "za" + "FAKE" * 8 + "abc"monkeypatch.setenv("GOOGLE_AI_API_KEY", fake_value)_fake_genai(monkeypatch, {"gemini-nano-banana-2.1": RuntimeError(f"bad request key={fake_value}")})- hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL)+ hero._try_gemini("topic", [], tmp_path, 1200, 630, hero.DEFAULT_GEMINI_MODEL, allow_paid=True)captured = capsys.readouterr()assert fake_value not in captured.out + captured.errdiff --git a/tests/test_hero_safety_gates.py b/tests/test_hero_safety_gates.pynew file mode 100644index 0000000..7892d8e--- /dev/null+++ b/tests/test_hero_safety_gates.py@@ -0,0 +1,495 @@+"""generate_hero safety gates: paid opt-in, existing-hero validation, symlinked heroes, paired writes.++No network and no SDK: providers and google.genai are replaced with fakes.+"""++from __future__ import annotations++import importlib.util+import io+import json+import os+import re+import subprocess+import sys+import types+from pathlib import Path++import pytest++PIL = pytest.importorskip("PIL")+from PIL import Image, features # noqa: E402++ROOT = Path(__file__).resolve().parent.parent+HERO = ROOT / "scripts" / "generate_hero.py"+KEY_VARS = ("GOOGLE_AI_API_KEY", "GEMINI_API_KEY", "UNSPLASH_ACCESS_KEY", "PEXELS_API_KEY", "PIXABAY_API_KEY")+++def _image(fmt: str, size=(1200, 630), **save) -> bytes:+ out = io.BytesIO()+ Image.new("RGB", size, (10, 120, 200)).save(out, format=fmt, **save)+ return out.getvalue()+++def hero(monkeypatch):+ for name in (*KEY_VARS, "NANOBANANA_MODEL"):+ monkeypatch.delenv(name, raising=False)+ spec = importlib.util.spec_from_file_location("hero_safety_gates", HERO)+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def _fake_genai(monkeypatch, data: bytes):+ calls = []++ class Interactions:+ def create(self, model, input, response_format): # noqa: A002 - SDK name+ calls.append(model)+ return types.SimpleNamespace(output_image=types.SimpleNamespace(data=data))++ class Client:+ def __init__(self, api_key):+ self.interactions = Interactions()++ genai = types.ModuleType("google.genai")+ genai.Client = Client+ google = types.ModuleType("google")+ google.genai = genai+ monkeypatch.setitem(sys.modules, "google", google)+ monkeypatch.setitem(sys.modules, "google.genai", genai)+ return calls+++def _openverse(hero, monkeypatch, image: bytes | None = None):+ """Serve one Openverse result; returns the list of provider calls made."""+ calls = []++ def fake_json(url, headers=None):+ calls.append(url)+ 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: image or _image("PNG"))+ return calls+++def _no_provider(hero, monkeypatch):+ monkeypatch.setattr(hero, "_http_get_json", lambda *a, **k: pytest.fail("no provider may run"))+ monkeypatch.setattr(hero, "_try_gemini", lambda *a, **k: pytest.fail("no paid call may run"))+++def _run(hero, monkeypatch, out_dir, capsys, *extra):+ monkeypatch.setattr(+ sys, "argv",+ ["generate_hero.py", "--topic", "Topic", "--tags", "a,b", "--out", str(out_dir), "--json", *extra],+ )+ code = hero.main()+ captured = capsys.readouterr()+ return code, json.loads(captured.out), captured.err+++def _snapshot(directory: Path) -> dict:+ return {+ p.name: (p.readlink() if p.is_symlink() else p.read_bytes() if p.is_file() else "dir")+ for p in directory.iterdir()+ }+++# Fix 1: the paid route needs --allow-paid in code, not only in skill docs.+[email protected]("variable", ["GOOGLE_AI_API_KEY", "GEMINI_API_KEY"])+def test_a_set_key_without_allow_paid_never_calls_gemini(hero, monkeypatch, tmp_path, capsys, variable):+ monkeypatch.setenv(variable, "your-test-key")+ genai_calls = _fake_genai(monkeypatch, _image("PNG"))+ _openverse(hero, monkeypatch)++ code, result, err = _run(hero, monkeypatch, tmp_path / "out", capsys)++ assert code == 0, err+ assert genai_calls == []+ assert result["source"] == "openverse"+ assert result["paid_gemini_skipped"] is True+ assert err.count(hero.PAID_SKIPPED_MESSAGE) == 1+ assert "AI-generated" not in (tmp_path / "out" / "hero-credit.txt").read_text()+++def test_allow_paid_with_a_key_uses_gemini(hero, monkeypatch, tmp_path, capsys):+ monkeypatch.setenv("GEMINI_API_KEY", "your-test-key")+ genai_calls = _fake_genai(monkeypatch, _image("PNG"))+ _no_provider_json = lambda *a, **k: pytest.fail("stock must not run after a Gemini success") # noqa: E731+ monkeypatch.setattr(hero, "_http_get_json", _no_provider_json)++ code, result, err = _run(hero, monkeypatch, tmp_path / "out", capsys, "--allow-paid")++ assert code == 0, err+ assert genai_calls == [hero.DEFAULT_GEMINI_MODEL]+ assert result["source"] == "gemini" and "paid_gemini_skipped" not in result+ assert hero.PAID_SKIPPED_MESSAGE not in err+++def test_no_key_and_no_flag_adds_no_note(hero, monkeypatch, tmp_path, capsys):+ _openverse(hero, monkeypatch)+ code, result, err = _run(hero, monkeypatch, tmp_path / "out", capsys)+ assert code == 0+ assert "paid_gemini_skipped" not in result and hero.PAID_SKIPPED_MESSAGE not in err+++def test_setup_error_mentions_allow_paid_and_the_skip(hero, monkeypatch, tmp_path, capsys):+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")+ _fake_genai(monkeypatch, _image("PNG"))+ monkeypatch.setattr(hero, "_http_get_json", lambda *a, **k: None)++ code, result, err = _run(hero, monkeypatch, tmp_path / "out", capsys)++ assert code == 1+ assert result["error"] == "no-image-gen-path"+ assert "--allow-paid" in result["message"]+ assert result["paid_gemini_skipped"] is True+ assert err.count(hero.PAID_SKIPPED_MESSAGE) == 1+++def test_kept_existing_hero_prints_no_paid_note(hero, monkeypatch, tmp_path, capsys):+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ (out_dir / "hero.png").write_bytes(_image("PNG"))+ _no_provider(hero, monkeypatch)+ code, result, err = _run(hero, monkeypatch, out_dir, capsys)+ assert code == 0 and result == {"source": "existing", "path": str(out_dir / "hero.png")}+ assert hero.PAID_SKIPPED_MESSAGE not in err+++def test_help_documents_allow_paid():+ result = subprocess.run([sys.executable, str(HERO), "--help"], capture_output=True, text=True, check=False)+ assert result.returncode == 0+ assert "--allow-paid" in result.stdout+ assert "--allow-paid" in HERO.read_text(encoding="utf-8").split('"""', 2)[1]+++# Fix 2: an existing hero counts only when its bytes are a real image of its extension's format.++def _webp_variants():+ if not features.check("webp"):+ return []+ return [+ ("hero.webp", _image("WEBP", lossless=True)),+ ("hero.webp", _image("WEBP", quality=80)),+ ("hero.webp", _image("WEBP", exif=b"Exif\x00\x00II*\x00\x08\x00\x00\x00\x00\x00")),+ ]+++def _jpeg_with_big_app_segments() -> bytes:+ plain = _image("JPEG")+ app = b"\xff\xe2" + (65535).to_bytes(2, "big") + b"\x00" * 65533 # one maximal APP2 segment+ return plain[:2] + app * 3 + plain[2:]+++ "name,data",+ [+ ("hero.png", _image("PNG")),+ ("hero.jpg", _image("JPEG")),+ ("hero.jpeg", _image("JPEG", progressive=True)),+ ("hero.jpg", _jpeg_with_big_app_segments()),+ *_webp_variants(),+ ],+ ids=lambda v: v if isinstance(v, str) else f"{len(v)}b",+)+def test_valid_heroes_pass_the_header_check(hero, tmp_path, name, data):+ path = tmp_path / name+ path.write_bytes(data)+ assert hero._hero_problem(path) is None+++def _png_with_zero_width() -> bytes:+ data = bytearray(_image("PNG"))+ data[16:20] = b"\x00\x00\x00\x00"+ return bytes(data)+++ "name,data,reason",+ [+ ("hero.png", b"", "empty"),+ ("hero.png", b"placed by the user", "PNG"),+ ("hero.png", b"\x89PNG\r\n\x1a\n", "PNG"),+ ("hero.png", _png_with_zero_width(), "zero"),+ ("hero.png", _image("JPEG"), "PNG"),+ ("hero.jpg", _image("PNG"), "JPEG"),+ ("hero.jpg", b"\xff\xd8\xff\xd9", "JPEG"),+ ("hero.jpg", b"\xff\xd8" + b"\xff" * 4096, "JPEG"),+ ("hero.webp", b"RIFF\x00\x00\x00\x00WEBPJUNK", "WEBP"),+ ],+ ids=lambda v: v if isinstance(v, str) else f"{len(v)}b",+)+def test_invalid_heroes_fail_the_header_check(hero, tmp_path, name, data, reason):+ path = tmp_path / name+ path.write_bytes(data)+ assert reason in hero._hero_problem(path)+++def test_a_directory_named_like_a_hero_is_not_one(hero, tmp_path):+ (tmp_path / "hero.png").mkdir()+ assert hero._hero_problem(tmp_path / "hero.png") == "not a regular file"+ assert hero._existing_hero(tmp_path) is None++[email protected]("name,data", [("hero.png", b""), ("hero.jpg", _image("PNG")), ("hero.webp", b"RIFFjunk")],+ ids=lambda v: v if isinstance(v, str) else f"{len(v)}b",+)+def test_an_invalid_existing_hero_is_replaced_and_reported(hero, monkeypatch, tmp_path, capsys, name, data):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ (out_dir / name).write_bytes(data)+ _openverse(hero, monkeypatch)++ code, result, err = _run(hero, monkeypatch, out_dir, capsys)++ assert code == 0, err+ assert result["source"] == "openverse"+ assert result["replaced_invalid"] == [name]+ assert f"{name} is not a usable hero" in err+ assert sorted(p.name for p in out_dir.iterdir()) == ["hero-credit.txt", "hero.png"]+ assert hero._hero_problem(out_dir / "hero.png") is None+++def test_a_valid_existing_jpeg_is_kept(hero, monkeypatch, tmp_path, capsys):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ placed = _image("JPEG")+ (out_dir / "hero.jpg").write_bytes(placed)+ _no_provider(hero, monkeypatch)++ code, result, _err = _run(hero, monkeypatch, out_dir, capsys)++ assert code == 0 and result["source"] == "existing" and "replaced_invalid" not in result+ assert (out_dir / "hero.jpg").read_bytes() == placed+++# Fix 3: a symlinked hero.* stops the run before anything is written or deleted.+[email protected]("extra", [(), ("--replace",)])[email protected]("link_name", ["hero.png", "hero.webp"])+def test_a_symlinked_hero_refuses_and_touches_nothing(hero, monkeypatch, tmp_path, capsys, extra, link_name):+ outside = tmp_path / "outside.png"+ outside.write_bytes(_image("PNG"))+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ (out_dir / link_name).symlink_to(outside)+ if link_name != "hero.png":+ (out_dir / "hero.png").write_bytes(_image("PNG")) # a valid hero beside the link does not help+ (out_dir / "hero-credit.txt").write_text("old credit")+ before = _snapshot(out_dir)+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")+ _no_provider(hero, monkeypatch)++ code, result, err = _run(hero, monkeypatch, out_dir, capsys, "--allow-paid", *extra)++ assert code == 1+ assert result["error"] == "hero-symlink"+ assert link_name in result["message"] and "symlink" in result["message"]+ assert _snapshot(out_dir) == before+ assert outside.read_bytes() == _image("PNG")+ assert hero.PAID_SKIPPED_MESSAGE not in err+++# Fix 4: the image and credit land together; a refused credit changes nothing.++def _seed_old_files(out_dir: Path) -> None:+ out_dir.mkdir()+ (out_dir / "hero.png").write_bytes(b"old png")+ (out_dir / "hero.webp").write_bytes(b"old webp")+++def test_a_symlinked_credit_leaves_hero_credit_and_siblings_untouched(hero, tmp_path):+ out_dir = tmp_path / "out"+ _seed_old_files(out_dir)+ target = tmp_path / "elsewhere.txt"+ target.write_text("old credit")+ (out_dir / "hero-credit.txt").symlink_to(target)+ before = _snapshot(out_dir)++ with pytest.raises(ValueError, match="symlink"):+ hero._write_hero(out_dir, _image("JPEG"), "new credit")++ assert _snapshot(out_dir) == before+ assert target.read_text() == "old credit"+++def test_a_failed_credit_stage_leaves_everything_and_no_temp_files(hero, monkeypatch, tmp_path):+ out_dir = tmp_path / "out"+ _seed_old_files(out_dir)+ (out_dir / "hero-credit.txt").write_text("old credit")+ before = _snapshot(out_dir)+ real_stage = hero._stage_temp++ def stage(path, data):+ if path.name == "hero-credit.txt":+ raise OSError("disk full")+ return real_stage(path, data)++ monkeypatch.setattr(hero, "_stage_temp", stage)+ with pytest.raises(OSError):+ hero._write_hero(out_dir, _image("JPEG"), "new credit")++ assert _snapshot(out_dir) == before+++def test_a_successful_write_renames_both_and_leaves_no_temp_files(hero, tmp_path):+ out_dir = tmp_path / "out"+ _seed_old_files(out_dir)+ (out_dir / "hero-credit.txt").write_text("old credit")+ jpeg = _image("JPEG")++ path = hero._write_hero(out_dir, jpeg, "new credit")++ assert path == out_dir / "hero.jpg"+ assert _snapshot(out_dir) == {"hero.jpg": jpeg, "hero-credit.txt": b"new credit"}++[email protected]("kind", ["symlink", "directory"])+def test_replace_with_an_unwritable_credit_exits_nonzero_before_any_provider(hero, monkeypatch, tmp_path, capsys, kind):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ (out_dir / "hero.png").write_bytes(_image("PNG"))+ (out_dir / "hero.webp").write_bytes(_image("PNG"))+ credit = out_dir / "hero-credit.txt"+ if kind == "symlink":+ (tmp_path / "elsewhere.txt").write_text("old credit")+ credit.symlink_to(tmp_path / "elsewhere.txt")+ else:+ credit.mkdir()+ before = _snapshot(out_dir)+ _no_provider(hero, monkeypatch)++ code, result, _err = _run(hero, monkeypatch, out_dir, capsys, "--replace")++ assert code == 1+ assert result["error"] == "output-write-refused"+ assert _snapshot(out_dir) == before+++def test_a_credit_refused_at_write_time_keeps_the_old_files(hero, monkeypatch, tmp_path, capsys):+ out_dir = tmp_path / "out"+ _seed_old_files(out_dir)+ (out_dir / "hero-credit.txt").write_text("old credit")+ before = _snapshot(out_dir)+ _openverse(hero, monkeypatch, image=_image("JPEG"))+ real_stage = hero._stage_temp++ def stage(path, data):+ if path.name == "hero-credit.txt":+ raise OSError("credit refused")+ return real_stage(path, data)++ monkeypatch.setattr(hero, "_stage_temp", stage)+ code, result, _err = _run(hero, monkeypatch, out_dir, capsys, "--replace")++ assert code == 1+ assert result["error"] == "output-write-refused"+ assert _snapshot(out_dir) == before+++# Review follow-up: never overwrite a valid hand-placed hero; same size bar as the gates;+# every write target is checked before any provider (paid or free) runs.++def test_minimum_matches_the_delivery_gates(hero):+ text = (ROOT / "scripts" / "blog_preflight.py").read_text(encoding="utf-8")+ width = re.search(r"^HERO_MIN_WIDTH\s*=\s*(\d+)", text, re.MULTILINE)+ height = re.search(r"^HERO_MIN_HEIGHT\s*=\s*(\d+)", text, re.MULTILINE)+ assert width and height, "blog_preflight.py no longer defines HERO_MIN_WIDTH/HERO_MIN_HEIGHT"+ assert (hero.HERO_MIN_WIDTH, hero.HERO_MIN_HEIGHT) == (int(width.group(1)), int(height.group(1)))+++ "invalid_name,invalid_data,valid_name,valid_fmt",+ [+ ("hero.png", b"", "hero.jpg", "JPEG"),+ ("hero.png", _image("PNG", size=(800, 400)), "hero.jpg", "JPEG"),+ ("hero.webp", b"RIFFjunk", "hero.png", "PNG"),+ ("hero.jpg", _image("JPEG", size=(1199, 630)), "hero.jpeg", "JPEG"),+ ],+)+def test_a_valid_hero_beside_an_invalid_one_is_kept_and_nothing_is_spent(+ hero, monkeypatch, tmp_path, capsys, invalid_name, invalid_data, valid_name, valid_fmt+):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ placed = _image(valid_fmt)+ (out_dir / valid_name).write_bytes(placed)+ (out_dir / invalid_name).write_bytes(invalid_data)+ (out_dir / "hero-credit.txt").write_text("user credit")+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")+ _no_provider(hero, monkeypatch)++ code, result, err = _run(hero, monkeypatch, out_dir, capsys, "--allow-paid")++ assert code == 0, err+ assert result == {+ "source": "existing", "path": str(out_dir / valid_name), "replaced_invalid": [invalid_name],+ }+ assert f"removing {invalid_name}" in err+ assert _snapshot(out_dir) == {valid_name: placed, "hero-credit.txt": b"user credit"}+++def test_an_undersized_hero_alone_is_replaced_and_the_reason_is_reported(hero, monkeypatch, tmp_path, capsys):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ (out_dir / "hero.png").write_bytes(_image("PNG", size=(800, 400)))+ _openverse(hero, monkeypatch)++ code, result, err = _run(hero, monkeypatch, out_dir, capsys)++ assert code == 0, err+ assert result["source"] == "openverse" and result["replaced_invalid"] == ["hero.png"]+ assert "800x400 is below the 1200x630 delivery minimum" in err+ assert hero._hero_problem(out_dir / "hero.png") is None+++def test_an_uppercase_hero_name_is_not_read(hero, tmp_path):+ (tmp_path / "hero.PNG").write_bytes(_image("PNG"))+ assert hero._hero_problem(tmp_path / "hero.PNG") == "unsupported extension"++[email protected]("extra", [(), ("--replace",)])+def test_a_directory_hero_target_is_refused_before_the_paid_call(hero, monkeypatch, tmp_path, capsys, extra):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ (out_dir / "hero.png").mkdir()+ monkeypatch.setenv("GOOGLE_AI_API_KEY", "your-test-key")+ genai_calls = _fake_genai(monkeypatch, _image("PNG"))+ monkeypatch.setattr(hero, "_http_get_json", lambda *a, **k: pytest.fail("no provider may run"))+ before = _snapshot(out_dir)++ code, result, _err = _run(hero, monkeypatch, out_dir, capsys, "--allow-paid", *extra)++ assert code == 1+ assert result["error"] == "output-write-refused" and "hero.png" in result["message"]+ assert genai_calls == []+ assert _snapshot(out_dir) == before++[email protected](os.name != "posix" or os.geteuid() == 0, reason="needs POSIX permissions as a non-root user")+def test_an_unwritable_hero_target_is_refused_before_the_paid_call(hero, monkeypatch, tmp_path, capsys):+ out_dir = tmp_path / "out"+ out_dir.mkdir()+ old = out_dir / "hero.webp"+ old.write_bytes(_image("PNG")) # wrong format for .webp, so it is invalid and would be replaced+ old.chmod(0o444)+ monkeypatch.setenv("GEMINI_API_KEY", "your-test-key")+ genai_calls = _fake_genai(monkeypatch, _image("PNG"))+ monkeypatch.setattr(hero, "_http_get_json", lambda *a, **k: pytest.fail("no provider may run"))+ try:+ code, result, _err = _run(hero, monkeypatch, out_dir, capsys, "--allow-paid")+ finally:+ old.chmod(0o644)++ assert code == 1+ assert result["error"] == "output-write-refused" and "unwritable" in result["message"]+ assert genai_calls == []+ assert sorted(p.name for p in out_dir.iterdir()) == ["hero.webp"]diff --git a/tests/test_runtime_fixes.py b/tests/test_runtime_fixes.pyindex c3bfb8e..8ebe9a7 100644--- a/tests/test_runtime_fixes.py+++ b/tests/test_runtime_fixes.py@@ -317,7 +317,7 @@ def test_gemini_requests_jpeg_and_names_output_from_actual_bytes(monkeypatch.setenv("GOOGLE_AI_API_KEY", "test-key")monkeypatch.setattr(hero, "_fit_image_bytes", lambda data, _w, _h: data)- result = hero._try_gemini("Fixture", [], tmp_path, 1200, 630, "test-model")+ result = hero._try_gemini("Fixture", [], tmp_path, 1200, 630, "test-model", allow_paid=True)assert result is not None and result["path"].endswith("hero.jpg")assert captured["response_format"]["mime_type"] == "image/jpeg"