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(preflight): enforce the review rubric, a real hero path and the repair cap
Agrici Daniel2791ee0fabad
diff --git a/plugins/blog-studio/README.md b/plugins/blog-studio/README.mdindex e4ba820..51bbc3c 100644--- a/plugins/blog-studio/README.md+++ b/plugins/blog-studio/README.md@@ -63,9 +63,13 @@ workspace/session changes, clear, resume, and branch. Reload keeps a selectiononly in the same workspace/session and invalidates cached and in-flight results.A run already started may finish writing its selected draft after a clear orworkspace switch; its result cannot populate the new session's panel.-The companion passes `--project-root` to the checker. On Linux, the checker-opens the selected directory through descriptors without following symlinks-and anchors its working directory there. Replacing the selected path after+The companion runs both engine scripts with `python3 -E` (Python environment+variables are ignored; user site-packages, where `install.sh` puts the optional+dependencies without a virtual environment, stay available) and passes+`--project-root` to the checker. On Linux, the checker resolves symlinks at or+above the project root once (for example `/home` on Fedora atomic), then opens+the selected directory through descriptors without following any symlink+between the project root and the draft, and anchors its working directory there. Replacing the selected path afterlaunch cannot redirect its report writes to a different directory.## The live pipeline@@ -119,7 +123,10 @@ paths. It does not read the article body for display, reveal the review nonce,write a review, rotate verifier state, reset repair counters, or repair articles.The analyzer's configurable 70-point gate and the separate delivery requirement(score at least 90, zero uncleared P0 issues, valid matching nonce and nonblocking-decision) stay in the core engine. Manual checks do not consume repair iterations.+decision) stay in the core engine. Run checks passes `--manual-check`, so it+never reads or changes the draft's repair counter and the cap of 3 failed runs+does not apply to it. If the checker still exits 2 (an older engine without+`--manual-check`, or a capped run), the panel shows Blocked with that reason.## Evidence formatdiff --git a/plugins/blog-studio/hooks/register.ts b/plugins/blog-studio/hooks/register.tsindex bbec3f6..279685c 100644--- a/plugins/blog-studio/hooks/register.ts+++ b/plugins/blog-studio/hooks/register.ts@@ -147,7 +147,7 @@ function response(raw: { stdout: string; stderr: string; exitCode: number }): stasync function inspect($: EngineInterface, s: StudioState, runId?: string): Promise<Status> {const paths = await prepare($, s)- const args = ['python3', paths.scripts + '/' + HELPER, '--draft', paths.draft, '--project-root', rootOf(s)]+ const args = ['python3', '-E', paths.scripts + '/' + HELPER, '--draft', paths.draft, '--project-root', rootOf(s)]if (runId) args.push('--expected-run', runId)const out = await $.process.run(args, { cwd: rootOf(s), timeoutMs: 30_000 })const status = parseStatus(response(out), out.stderr)@@ -155,6 +155,9 @@ async function inspect($: EngineInterface, s: StudioState, runId?: string): Promreturn status}+// Exit 2 from the checker: it stopped before the gates. Shown as Blocked, never as passed.+class CheckerStopped extends Error {}+async function perform($: EngineInterface, check: boolean): Promise<string> {const snapshot = await context($)const s = snapshot.value@@ -170,8 +173,17 @@ async function perform($: EngineInterface, check: boolean): Promise<string> {if (check) {const paths = await prepare($, s)const tools = (await $.tool.list()).map(t => t.name)- const out = await $.process.run(['python3', paths.scripts + '/' + CHECKER, '--draft', paths.draft,- '--strict', '--json', '--tools-json', JSON.stringify(tools), '--project-root', rootOf(s)], { cwd: rootOf(s), timeoutMs: 600_000 })+ // -E ignores PYTHON* variables but keeps user site-packages, where install.sh puts the+ // optional dependencies without a venv. --manual-check never reads or changes the repair counter.+ const out = await $.process.run(['python3', '-E', paths.scripts + '/' + CHECKER, '--draft', paths.draft,+ '--strict', '--json', '--manual-check', '--tools-json', JSON.stringify(tools), '--project-root', rootOf(s)], { cwd: rootOf(s), timeoutMs: 600_000 })+ if (out.exitCode === 2) {+ let capped = false+ try { capped = (JSON.parse(response(out)) as { iteration_cap_exceeded?: unknown })?.iteration_cap_exceeded === true } catch { /* no report */ }+ throw new CheckerStopped(capped+ ? 'Repair cap reached: this draft failed 3 full gate runs. Manual fix required before checks can continue.'+ : 'Checker stopped before running the gates (exit 2): the repair cap is reached or this engine does not support --manual-check. ' + clean(out.stderr, 300))+ }const report = jsonResponse(response(out), out.stderr)if (!report || typeof report !== 'object') throw new Error('Checker returned no valid report.')const r = report as { evidence?: { run_id?: unknown }; strict?: unknown; blocked?: unknown; draft?: unknown }@@ -185,8 +197,11 @@ async function perform($: EngineInterface, check: boolean): Promise<string> {status = await inspect($, s, runId)} catch (error) {message = clean(error instanceof Error ? error.message : String(error))- status = { schema_version: 1, status: 'error', label: 'Execution error', checked_at: null,- passed_count: 0, gates: [], artifacts: [], diagnostics: [message] }+ status = error instanceof CheckerStopped+ ? { schema_version: 1, status: 'blocked', label: 'Blocked', checked_at: null,+ passed_count: 0, gates: [], artifacts: [], diagnostics: [message] }+ : { schema_version: 1, status: 'error', label: 'Execution error', checked_at: null,+ passed_count: 0, gates: [], artifacts: [], diagnostics: [message] }}if (((await $.session.root()).replace(/\/$/, '') || '/') !== s.workspace || await $.session.id() !== s.sessionId) return 'Previous check finished after the session changed; its result was discarded.'const final = { ...s, busy: false, status, message }diff --git a/plugins/blog-studio/tests/studio.test.ts b/plugins/blog-studio/tests/studio.test.tsindex 4f2eddb..34c58ad 100644--- a/plugins/blog-studio/tests/studio.test.ts+++ b/plugins/blog-studio/tests/studio.test.ts@@ -99,8 +99,8 @@ test('Run checks button executes the checker and inspector, then redraws', asynchost(on)const calls: string[] = []on('process.run', ($, e) => {- calls.push(e.argv[1] ?? '')- return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(e.argv[1]?.endsWith('blog_preflight.py') ?+ calls.push(e.argv[2] ?? '')+ return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(e.argv[2]?.endsWith('blog_preflight.py') ?{ strict: true, blocked: false, draft: '/work/outputs/article', evidence: { run_id: PASS.run_id } } : PASS) }) }})await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })@@ -183,7 +183,7 @@ for (const stage of ['checker', 'inspector']) {test('malformed ' + stage + ' JSON retains sanitized stderr diagnostics', async ($, on) => {host(on)on('process.run', ($, e) => {- const isChecker = e.argv[1]?.endsWith('blog_preflight.py')+ const isChecker = e.argv[2]?.endsWith('blog_preflight.py')const broken = stage === 'checker' ? isChecker : !isCheckerreturn { value: done({ exitCode: broken ? 1 : 0, stderr: broken ? '\x1b[31mMissing browser at /var/home/owner/private; ' + 'c'.repeat(32) : '',stdout: broken ? 'private article body' : JSON.stringify({ strict: true, blocked: false,@@ -227,16 +227,19 @@ test('check invokes strict canonical script with no shell then verifies run idenconst limits: number[] = []on('process.run', ($, e) => {calls.push([...e.argv]); limits.push(e.init?.timeoutMs ?? 0)- return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(e.argv[1]?.endsWith('blog_preflight.py') ?+ return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(e.argv[2]?.endsWith('blog_preflight.py') ?{ strict: true, blocked: false, draft: '/work/outputs/article', evidence: { run_id: PASS.run_id } } : PASS) }) }})await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })const out = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })expect(out).toMatchObject({ text: expect.stringContaining('Preflight passed') })- expect(calls[0]?.slice(0, 6)).toEqual(['python3', '/trusted/scripts/blog_preflight.py', '--draft', '/work/outputs/article', '--strict', '--json'])+ expect(calls[0]?.slice(0, 7)).toEqual(['python3', '-E', '/trusted/scripts/blog_preflight.py', '--draft', '/work/outputs/article', '--strict', '--json'])+ expect(calls[1]?.slice(0, 3)).toEqual(['python3', '-E', '/trusted/scripts/blog_studio_status.py'])expect(limits).toEqual([600_000, 30_000])expect(calls[1]).toContain('--expected-run')+ expect(calls[0]?.[7]).toBe('--manual-check')+ expect(calls[0]).not.toContain('-I')expect(calls[0]).not.toContain('--repair-attempt')expect(calls[0]).not.toContain('--init-review-nonce')expect(calls[0]?.slice(-2)).toEqual(['--project-root', '/work'])@@ -247,7 +250,7 @@ for (const failure of ['timeout', 'malformed', 'truncated', 'wrong-exit', 'missihost(on)on('process.run', () => {if (failure === 'timeout') throw new Error('python3 unavailable or process timed out')- return { value: done({ exitCode: failure === 'wrong-exit' ? 2 : 0, stderr: 'fixture stderr',+ return { value: done({ exitCode: failure === 'wrong-exit' ? 3 : 0, stderr: 'fixture stderr',stdout: failure === 'malformed' ? '{broken' : failure === 'missing-report' ? '' : JSON.stringify({ strict: true,blocked: false, draft: '/work/outputs/article', evidence: { run_id: PASS.run_id } }),isStdoutTruncated: failure === 'truncated' }) }@@ -260,6 +263,30 @@ for (const failure of ['timeout', 'malformed', 'truncated', 'wrong-exit', 'missi})}+for (const kind of ['capped', 'old-engine']) {+ test('checker exit 2 shows Blocked with its reason, never an execution error: ' + kind, async ($, on) => {+ host(on)+ const calls: string[][] = []+ on('process.run', ($, e) => {+ calls.push([...e.argv])+ return { value: done({ exitCode: 2,+ stderr: kind === 'capped' ? 'ITERATION CAP EXCEEDED' : 'blog_preflight.py: error: unrecognized arguments: --manual-check',+ stdout: kind === 'capped' ? JSON.stringify({ draft: '/work/outputs/article', strict: true, blocked: true,+ incomplete: true, iteration_cap_exceeded: true, gates: [] }) : '' }) }+ })+ await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })+ await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })+ const out = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })+ expect(out).toMatchObject({ text: expect.stringContaining('Blocked') })+ expect(out).not.toMatchObject({ text: expect.stringContaining('Execution error') })+ expect(out).not.toMatchObject({ text: expect.stringContaining('no valid report') })+ expect(out).toMatchObject({ text: expect.stringContaining(kind === 'capped' ? 'Repair cap reached' : 'does not support --manual-check') })+ expect(out).not.toMatchObject({ text: expect.stringContaining('Preflight passed') })+ // The inspector never runs after a stopped checker.+ expect(calls.length).toBe(1)+ })+}+for (const link of ['/work/outputs', '/trusted/scripts/blog_preflight.py']) {test('symlink path refused before any process: ' + link, async ($, on) => {host(on, { link })@@ -503,7 +530,7 @@ test('history follows the agent, backfills by scan, and opens a past blog in anoon('process.run', ($$, e) => {argvs.push([...e.argv])if (e.argv[0] === 'find') return { value: done({ exitCode: 0, stderr: '', stdout: '1760000000.0\t/other/proj/blog-a\n' }) }- const isChecker = e.argv[1]?.endsWith('blog_preflight.py')+ const isChecker = e.argv[2]?.endsWith('blog_preflight.py')return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(isChecker ?{ strict: true, blocked: false, draft: '/other/proj/blog-a', evidence: { run_id: PASS.run_id } } : PASS) }) }})@@ -520,7 +547,7 @@ test('history follows the agent, backfills by scan, and opens a past blog in anoconst opened = await $.command.run({ command: 'blog-studio', args: 'open 2', ...RUN })expect(opened).toMatchObject({ text: expect.stringContaining('Project root: /other/proj') })await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })- const checker = argvs.find(a => a[1]?.endsWith('blog_preflight.py'))+ const checker = argvs.find(a => a[2]?.endsWith('blog_preflight.py'))expect(checker).toEqual(expect.arrayContaining(['--draft', '/other/proj/blog-a', '--project-root', '/other/proj']))const missing = await $.command.run({ command: 'blog-studio', args: 'open 9', ...RUN })expect(missing).toMatchObject({ text: expect.stringContaining('No blog number 9') })@@ -549,7 +576,7 @@ test('the engine location is remembered across sessions and can be forgotten', ahost(on, { env: null, sessionId: () => sessionId })on('process.run', ($$, e) => {argvs.push([...e.argv])- const isChecker = e.argv[1]?.endsWith('blog_preflight.py')+ const isChecker = e.argv[2]?.endsWith('blog_preflight.py')return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(isChecker ?{ strict: true, blocked: false, draft: '/work/outputs/article', evidence: { run_id: PASS.run_id } } : PASS) }) }})@@ -559,7 +586,7 @@ test('the engine location is remembered across sessions and can be forgotten', asessionId = 'two'await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })- expect(argvs.some(a => a[1] === '/trusted/scripts/blog_preflight.py')).toBe(true)+ expect(argvs.some(a => a[2] === '/trusted/scripts/blog_preflight.py')).toBe(true)const cleared = await $.command.run({ command: 'blog-studio', args: 'configure reset', ...RUN })expect(cleared).toMatchObject({ text: expect.stringContaining('cleared') })sessionId = 'three'diff --git a/scripts/blog_preflight.py b/scripts/blog_preflight.pyindex 7ed1307..953bcdd 100644--- a/scripts/blog_preflight.py+++ b/scripts/blog_preflight.py@@ -18,7 +18,8 @@ Usage:--json Emit the report JSON to stdout in addition to the file.Exit codes: 0 = all gates passed; 1 = at least one gate blocked-(when --strict); 2 = repair iteration cap exceeded. Warnings never block.+(when --strict); 2 = repair iteration cap exceeded (a fourth full gate run+for the same draft). Warnings never block."""from __future__ import annotations@@ -27,6 +28,7 @@ import argparseimport contextlibimport datetime as dtimport hashlib+import http.clientimport ipaddressimport importlib.utilimport json@@ -34,8 +36,10 @@ import osimport reimport shutilimport socket+import sslimport sysimport tempfile+import threadingimport urllib.errorimport urllib.parseimport urllib.request@@ -84,11 +88,14 @@ PREFLIGHT_TARGETS_FILE = "preflight-targets.json"LEGACY_ALLOWLIST_FILE = "preflight-allowlist.json"# VULN-802 code-enforced iteration counter (v1.9.1).-# The contract documents "up to 3 retries before escalating." v1.9.0-# enforced this only as orchestrator prose; any draft-controlled text-# could convince the orchestrator the counter was at 0. v1.9.1 backs the-# claim with a file on disk that survives across preflight invocations.-ITERATION_COUNTER_FILE = ".iteration-count"+# The contract allows 3 failed full gate runs per draft, then a stop: the+# next full run exits 2. Passing runs, --gate runs and --manual-check runs+# never count. The counter lives with the review verifier state outside the+# draft folder, keyed like the nonce, so an agent that can write the draft+# cannot reset it. A legacy <draft>/.iteration-count file is ignored.+ITERATION_COUNTER_FILE = ".iteration-count" # legacy location, never read+ITERATION_STATE_SUFFIX = ".iterations.json"+ITERATION_LOCK_SUFFIX = ".iterations.lock"MAX_ITERATIONS = 3EXIT_ITERATION_CAP = 2@@ -110,6 +117,12 @@ def _review_state_path(draft: Path) -> Path:return state_root / f"{digest}.json"+def _iteration_state_path(draft: Path) -> Path:+ """Return the external repair-counter path, keyed like the review nonce."""+ nonce_path = _review_state_path(draft)+ return nonce_path.with_name(nonce_path.stem + ITERATION_STATE_SUFFIX)++def _reject_symlink_output(path: Path) -> None:if path.is_symlink():raise ValueError(f"refusing to overwrite symlink: {path}")@@ -337,56 +350,84 @@ def _init_review_nonce(draft: Path) -> str:return nonce-def _iteration_check(draft: Path, reset: bool = False, increment: bool = False) -> int:- """Read or increment the per-draft repair counter; refuse past cap.+def _read_iteration_count(draft: Path) -> int:+ """Failed full gate runs recorded for this draft; absent or corrupt is 0."""+ try:+ data = json.loads(_read_text_no_follow(_iteration_state_path(draft)))+ except FileNotFoundError:+ return 0+ except (ValueError, OSError):+ return 0+ runs = data.get("runs") if isinstance(data, dict) else None+ return runs if type(runs) is int and runs >= 0 else 0+- Behavior:- * reset=True: counter is set to 0.- * increment=False: no counter mutation after any reset.- * increment=True, counter absent or corrupt: counter is set to 1.- * increment=True, counter at MAX_ITERATIONS: emit stderr message and- return EXIT_ITERATION_CAP. Caller should sys.exit(2).- * Otherwise with increment=True: counter += 1; return 0.+def _iteration_lock(draft: Path):+ """Hold an exclusive per-draft lock (POSIX flock; msvcrt on Windows; else none).- Fail-soft on corrupt counter file: a non-integer value resets to 1- rather than refusing to run (an attacker who can write to the draft- folder has bigger problems; refusing on garbage would be a self-DoS).+ The lock spans the cap check, the gates and the increment, so concurrent+ counted runs on one draft run one at a time and see each other's count.+ """+ nonce_path = _review_state_path(draft)+ path = nonce_path.with_name(nonce_path.stem + ITERATION_LOCK_SUFFIX)+ path.parent.mkdir(parents=True, exist_ok=True)+ try:+ os.chmod(path.parent, 0o700)+ except OSError:+ pass+ fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)+ try:+ try:+ import fcntl+ except ImportError: # pragma: no cover - Windows+ fcntl = None+ if fcntl is not None:+ fcntl.flock(fd, fcntl.LOCK_EX)+ else: # pragma: no cover - Windows best effort+ try:+ import msvcrt+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)+ except (ImportError, OSError):+ pass+ yield+ finally:+ os.close(fd)+++def _iteration_cap_message() -> str:+ return (+ f"ITERATION CAP EXCEEDED: this draft has failed {MAX_ITERATIONS} full gate runs. "+ "Stop and show the user the diagnostic in preflight-report.json (manual fix required). "+ "Use --reset-iterations only when starting a new write or rewrite in this draft folder."+ )+++def _iteration_check(draft: Path, reset: bool = False) -> int:+ """Reset the counter if asked, then return EXIT_ITERATION_CAP when it is at the cap.++ The counter is stored next to the review nonce state, outside the draft+ folder (see ``_iteration_state_path``). A legacy ``<draft>/.iteration-count``+ file is ignored, and a corrupt counter counts as 0 rather than refusing to+ run. Only failed counted runs increment it (see ``_run_preflight``)."""- counter_path = draft / ITERATION_COUNTER_FILEif reset:- _atomic_write_counter(counter_path, 0)- if not increment:+ _write_iteration_count(draft, _iteration_state_path(draft), 0)return 0- try:- raw = counter_path.read_text(encoding="utf-8").strip()- current = int(raw)- except (FileNotFoundError, ValueError, OSError):- current = 0- if current >= MAX_ITERATIONS:- sys.stderr.write(- f"ITERATION CAP EXCEEDED: this draft has used all {MAX_ITERATIONS} "- f"preflight iterations. Escalate to the user, or run with "- f"--reset-iterations after a code change.\n"- )+ if _read_iteration_count(draft) >= MAX_ITERATIONS:+ sys.stderr.write(_iteration_cap_message() + "\n")return EXIT_ITERATION_CAP- _atomic_write_counter(counter_path, current + 1)return 0-def _atomic_write_counter(path: Path, value: int) -> None:- """Atomic write of the integer counter (mkstemp + os.replace)."""- import tempfile- fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(f"{int(value)}\n")- os.replace(tmp, str(path))- except Exception:- try:- os.unlink(tmp)- except OSError:- pass- raise+def _write_iteration_count(draft: Path, path: Path, value: int) -> None:+ """Atomic private write of the external gate-run counter."""+ _atomic_write_json(+ path,+ {"draft": str(draft.resolve()), "runs": int(value), "max_runs": MAX_ITERATIONS},+ private=True,+ sort_keys=True,+ )def _gate_result(gate: int, name: str, passed: bool, violations: Optional[list] = None, warnings: Optional[list] = None, **kwargs: Any) -> dict:@@ -623,12 +664,109 @@ def _well_formed_http_url(url: str) -> tuple[bool, str | None]:return True, None-def gate_1_capability_discovery(draft_dir: Path, live_tools: list[str] | None = None) -> dict:- """Enumerate available capabilities; write capabilities.json."""+OPENVERSE_PROBE_URL = "https://api.openverse.org/v1/images/?q=landscape&page_size=1"+OPENVERSE_PROBE_TIMEOUT = 3.0+STOCK_KEYS = ("UNSPLASH_ACCESS_KEY", "PEXELS_API_KEY", "PIXABAY_API_KEY")+GEMINI_KEYS = ("GOOGLE_AI_API_KEY", "GEMINI_API_KEY")+NO_HERO_PATH_MESSAGE = (+ "Hero image required but no generation path available. Configure Banana MCP, set GOOGLE_AI_API_KEY, "+ "set UNSPLASH/PEXELS/PIXABAY key, or place a 1200x630 hero.png in the draft folder manually. "+ "(No valid local hero, no live Banana MCP, no Gemini or stock key, and Openverse unreachable.)"+)+++class _PinnedHTTPSConnection(http.client.HTTPSConnection):+ """HTTPS connection to one already validated address; no global DNS patch."""++ def __init__(self, host: str, address: str, port: int, timeout: float):+ super().__init__(host, port, timeout=timeout, context=ssl.create_default_context())+ self._pinned_address = address++ def connect(self) -> None:+ sock = socket.create_connection((self._pinned_address, self.port), self.timeout)+ self.sock = self._context.wrap_socket(sock, server_hostname=self.host)+++def _openverse_probe_once(url: str, timeout: float) -> bool:+ """One HEAD to Openverse: HTTPS only, public addresses only, no redirects."""+ if urllib.parse.urlparse(url).scheme != "https":+ return False+ ok, _reason, host, port, infos = _resolve_public_http_url(url)+ if not ok or host is None or port is None or not infos:+ return False+ parsed = urllib.parse.urlparse(url)+ target = parsed.path + (f"?{parsed.query}" if parsed.query else "")+ conn = _PinnedHTTPSConnection(host, infos[0][4][0], port, timeout)+ try:+ conn.request("HEAD", target or "/", headers={"User-Agent": USER_AGENT})+ # http.client never follows redirects; only a direct 2xx counts.+ return 200 <= conn.getresponse().status < 300+ finally:+ conn.close()+++def _openverse_reachable(url: str = OPENVERSE_PROBE_URL, timeout: float = OPENVERSE_PROBE_TIMEOUT) -> bool:+ """Return whether the Openverse API answers within ``timeout`` seconds in total.++ DNS, connect, TLS and the response all run in a daemon thread that is+ abandoned at the deadline. Tests monkeypatch this function.+ """+ outcome: list[bool] = []++ def probe() -> None:+ try:+ outcome.append(_openverse_probe_once(url, timeout))+ except Exception:+ outcome.append(False)++ worker = threading.Thread(target=probe, name="openverse-probe", daemon=True)+ worker.start()+ worker.join(timeout)+ return bool(outcome) and outcome[0]+++# The renderer and generate_hero.py pick the first of these that exists.+HERO_PREFERENCE = ("hero.png", "hero.jpg", "hero.jpeg", "hero.webp")+++def _valid_local_hero(draft_dir: Path) -> str | None:+ """Name of the hero the renderer would use, if it passes the Gate 2 image check.++ Only exact lowercase names count, in renderer order (png, jpg, jpeg,+ webp). The first regular, non-symlink match is the one the article+ embeds, so it alone decides: it must decode and be at least+ HERO_MIN_WIDTH x HERO_MIN_HEIGHT, as Gate 2 requires.+ """+ try:+ names = set(os.listdir(draft_dir))+ except OSError:+ return None+ for name in HERO_PREFERENCE:+ hero = draft_dir / name+ if name not in names or hero.is_symlink() or not hero.is_file():+ continue+ data = _safe_read_bytes(hero)+ return name if data is not None and not _hero_check(hero, data)[0] else None+ return None+++def gate_1_capability_discovery(+ draft_dir: Path,+ live_tools: list[str] | None = None,+ project_dir: Path | None = None,+) -> dict:+ """Enumerate available capabilities; write capabilities.json.++ ``project_dir`` is the user's project (``--project-root``, otherwise the+ current directory), where BRAND.md, VOICE.md and DISCOURSE.md live. Agents+ and helper scripts are looked up in the install root.+ """root = _project_root()+ user_project = project_dir if project_dir is not None else Path.cwd()live_tools = live_tools or []env_keys = {"GOOGLE_AI_API_KEY": bool(os.environ.get("GOOGLE_AI_API_KEY")),+ "GEMINI_API_KEY": bool(os.environ.get("GEMINI_API_KEY")),"UNSPLASH_ACCESS_KEY": bool(os.environ.get("UNSPLASH_ACCESS_KEY")),"PEXELS_API_KEY": bool(os.environ.get("PEXELS_API_KEY")),"PIXABAY_API_KEY": bool(os.environ.get("PIXABAY_API_KEY")),@@ -642,37 +780,49 @@ def gate_1_capability_discovery(draft_dir: Path, live_tools: list[str] | None ="markdown": _has_module("markdown"),}project_files = {- "BRAND.md": (root / "BRAND.md").is_file(),- "VOICE.md": (root / "VOICE.md").is_file(),- "DISCOURSE.md": (root / "DISCOURSE.md").is_file(),+ "BRAND.md": (user_project / "BRAND.md").is_file(),+ "VOICE.md": (user_project / "VOICE.md").is_file(),+ "DISCOURSE.md": (user_project / "DISCOURSE.md").is_file(),}agents = {a: (root / "agents" / f"{a}.md").is_file() for a in REQUIRED_AGENTS + OPTIONAL_AGENTS}scripts = {s: (root / s).is_file() for s in REQUIRED_SCRIPTS}- configured_image_paths = (- any("nanobanana" in tool.lower() or "banana" in tool.lower() for tool in live_tools)- or env_keys["GOOGLE_AI_API_KEY"]- or env_keys["UNSPLASH_ACCESS_KEY"]- or env_keys["PEXELS_API_KEY"]- or env_keys["PIXABAY_API_KEY"]- )- # Openverse is the no-key fallback at the bottom of the ladder. We do NOT- # probe its reachability here (network HEAD at gate-1 time is too slow- # and flaky); we report it as best-effort and let generate_hero.py- # surface a runtime failure if Openverse is unreachable when invoked.- openverse_assumed_available = True # best-effort fallback- image_gen_available = configured_image_paths or openverse_assumed_available+ local_hero = _valid_local_hero(draft_dir)+ banana_live = any("banana" in tool.lower() for tool in live_tools)+ stock_key = any(env_keys[k] for k in STOCK_KEYS)+ gemini_key = any(env_keys[k] for k in GEMINI_KEYS)+ # Free paths: a valid local hero, a stock key, a reachable Openverse.+ # Paid paths (Banana MCP, Gemini key) need the user's consent, so they+ # never stand in for the free probe: Openverse is probed (bounded,+ # offline-safe) whenever no other free path exists.+ openverse_reachable: bool | None = None+ if not (local_hero or stock_key):+ openverse_reachable = _openverse_reachable()+ free_path = bool(local_hero or stock_key or openverse_reachable)+ paid_path = bool(banana_live or gemini_key)+ paid_only = paid_path and not free_path+ image_gen_available = free_path or paid_pathcapabilities = {"live_tools": live_tools,"live_tools_source": "orchestrator" if live_tools else "not-provided","env_keys_present": env_keys,"python_deps": py_deps,+ "project_root": str(user_project),"project_root_files": project_files,"agents": agents,"scripts": scripts,"image_gen_path_available": image_gen_available,- "openverse_assumed_available": openverse_assumed_available,+ "hero_paths": {+ "local_hero": local_hero,+ "banana_mcp": banana_live,+ "gemini_api": {"available": gemini_key, "paid": True, "requires_consent": True},+ "stock_api": stock_key,+ # None: not probed because another free path is available.+ "openverse_reachable": openverse_reachable,+ "free_path": free_path,+ "paid_only": paid_only,+ },}try:_atomic_write_json(draft_dir / "capabilities.json", capabilities, indent=2)@@ -686,7 +836,14 @@ def gate_1_capability_discovery(draft_dir: Path, live_tools: list[str] | None =if not live_tools:warnings.append("live tool availability not provided; MCP image tools cannot be verified from declarations")if not image_gen_available:- violations.append("no image-gen path available: no live Banana MCP, API key, stock key, or Openverse fallback")+ violations.append(NO_HERO_PATH_MESSAGE)+ elif paid_only:+ paid = " and ".join(name for name, present in (("Banana MCP", banana_live), ("Gemini API key", gemini_key)) if present)+ warnings.append(+ f"paid_only: the only hero path is paid ({paid}); the user must approve the cost first "+ "(blog-image consent gate, then generate_hero.py --allow-paid), or add a free path: a 1200x630 "+ "hero.png in the draft, a stock key, or a reachable Openverse"+ )if not py_deps["patchright"] and not py_deps["playwright"]:warnings.append("neither patchright nor playwright installed; strict Gate 3 will block delivery")if not py_deps["weasyprint"] and not py_deps["patchright"] and not py_deps["playwright"]:@@ -2893,11 +3050,10 @@ REVIEW_CATEGORY_MAX = {def _category_score_violations(text: str, overall: int) -> list[str]:"""Check reviewer category scores against the rubric and the overall score.- Reads `Category: N/MAX` and `| Category | N | MAX |` forms. Absent- categories are allowed (older reviews carry only the overall line), but- every present score must fit its rubric maximum and the overall must lie- between the sum of the stated scores and that sum plus the maxima of the- categories not stated. With all five present this means overall == sum.+ Reads `Category: N/MAX` and `| Category | N | MAX |` forms. All five+ categories are required (the delivery contract and quality-scoring.md),+ each score must fit its rubric maximum, and the overall must equal the sum+ of the five category scores."""violations: list[str] = []found: dict[str, float] = {}@@ -2910,6 +3066,7 @@ def _category_score_violations(text: str, overall: int) -> list[str]:)values = {(float(m.group(1)), float(m.group(2)) if m.group(2) else None) for m in pattern.finditer(text)}if not values:+ violations.append(f"review.md is missing the {name} score")continueif len({value for value, _stated in values}) > 1:violations.append(f"review.md contains conflicting {name} scores")@@ -2922,13 +3079,12 @@ def _category_score_violations(text: str, overall: int) -> list[str]:violations.append(f"review {name} score {value:g}/{maximum} exceeds its maximum")else:found[name] = value- if found and not violations:- floor = sum(found.values())- ceiling = floor + sum(m for n, m in REVIEW_CATEGORY_MAX.items() if n not in found)- if not floor - 1e-9 <= overall <= ceiling + 1e-9:+ if not violations:+ total = sum(found.values())+ if abs(overall - total) > 1e-9:violations.append(f"review overall score {overall}/100 is inconsistent with its category scores "- f"(stated categories sum to {floor:g}; overall must be between {floor:g} and {ceiling:g})"+ f"(the five categories sum to {total:g}; the overall must equal that sum)")return violations@@ -3114,7 +3270,13 @@ def main() -> int:parser.add_argument("--draft", required=True, help="Draft folder containing the .md/.html/.pdf/hero artifacts")parser.add_argument("--project-root",- help="Anchor execution inside this project directory (Unix only); the report then records the draft path as given",+ help=(+ "Anchor execution inside this project directory (Unix only) and look for BRAND.md, VOICE.md "+ "and DISCOURSE.md there (default: the current directory). Symlinks at or above the project "+ "root are resolved; a symlink or '..' between the project root and the draft is refused. "+ "The report then records the draft as an absolute path (joined to the current directory, "+ "symlinks not resolved)"+ ),)parser.add_argument("--gate", type=int, choices=[1, 2, 3, 4, 5], help="Run only this gate (default: all)")parser.add_argument("--slug", help="Require all source/rendered artifacts to match this stem")@@ -3123,11 +3285,32 @@ def main() -> int:parser.add_argument("--json", action="store_true", help="Emit report JSON to stdout")parser.add_argument("--tools-json", help="JSON list/object of live tool names supplied by the orchestrator")parser.add_argument("--diagnostics-all", action="store_true", help="Run later gates after a failure for diagnostics")- parser.add_argument("--repair-attempt", action="store_true", help="Increment the repair iteration counter for orchestrator repair loops")+ parser.add_argument(+ "--repair-attempt",+ action="store_true",+ help=(+ "Apply the repair cap to this run even with --gate. Full gate runs (no --gate) always do: "+ f"each failed run (exit 1 under --strict) counts, passing runs never count, and after "+ f"{MAX_ITERATIONS} failed runs the next one exits {EXIT_ITERATION_CAP}"+ ),+ )+ parser.add_argument(+ "--manual-check",+ action="store_true",+ help=(+ "Run the gates and write the report without reading or changing the repair counter, so no "+ "cap applies. For status checks and re-checks of delivered posts (Blog Studio uses it), "+ "never inside a repair loop"+ ),+ )parser.add_argument("--reset-iterations",action="store_true",- help="Reset the per-draft iteration counter to 0 (the next --repair-attempt counts as the first).",+ help=(+ "Reset the per-draft failed-run counter to 0 and exit without running gates. Use it only when "+ "starting a new write or rewrite in a draft folder that was used before, never to continue "+ "a repair loop past the cap"+ ),)parser.add_argument("--init-review-nonce",@@ -3145,6 +3328,8 @@ def main() -> int:if _anchored_draft is None:print("ERROR: --project-root needs scripts/blog_studio_status.py next to this script", file=sys.stderr)return 1+ # Resolved before anchoring changes the working directory.+ args.user_project_dir = Path(args.project_root).resolve()with contextlib.ExitStack() as stack:try:draft, identity = stack.enter_context(_anchored_draft(args.draft, args.project_root))@@ -3153,6 +3338,7 @@ def main() -> int:return 1return _run_preflight(args, draft, identity)+ args.user_project_dir = Path.cwd()draft = Path(args.draft).resolve()if not draft.is_dir():print(f"ERROR: {draft} is not a directory", file=sys.stderr)@@ -3160,8 +3346,26 @@ def main() -> int:return _run_preflight(args, draft, str(draft))+def _bypass_warning(results: list[dict]) -> str:+ """The delivery contract's --no-strict warning, naming the failed gates."""+ failed = ", ".join(f"Gate {r['gate']}" for r in results if not r["passed"])+ return (+ f"WARNING: Delivery contract bypassed. Failed gates: [{failed}].\n"+ "The draft is being presented anyway per --no-strict. Do not publish without manual review."+ )++def _run_preflight(args: argparse.Namespace, draft: Path, draft_identity: str) -> int:"""Run the requested gates. ``draft_identity`` is the path recorded in the report."""+ if args.reset_iterations:+ try:+ _iteration_check(draft, reset=True)+ except (OSError, ValueError) as e:+ print(f"ERROR: iteration counter reset refused: {e}", file=sys.stderr)+ return 1+ if not args.init_review_nonce:+ print(f"iteration counter reset to 0 ({MAX_ITERATIONS} failed full gate runs allowed)", file=sys.stderr)+ return 0if args.init_review_nonce:nonce = _init_review_nonce(draft)print(nonce)@@ -3181,24 +3385,66 @@ def _run_preflight(args: argparse.Namespace, draft: Path, draft_identity: str) -print(f"ERROR: preflight-report.json write refused: {e}", file=sys.stderr)return 1- # Count only orchestrator repair attempts, not every preflight or single-gate run.- iteration_exit = _iteration_check(- draft,- reset=args.reset_iterations,- increment=args.repair_attempt,+ # The cap applies to full gate runs and to --gate runs with+ # --repair-attempt, never to --manual-check. Only a failed counted run+ # (exit 1 under --strict) increments the counter. The lock spans the cap+ # check, the gates and the increment, so concurrent runs cannot overrun.+ if args.manual_check or not (args.gate is None or args.repair_attempt):+ return _run_gates(args, draft, draft_identity)+ lock = contextlib.ExitStack()+ try:+ lock.enter_context(_iteration_lock(draft))+ iteration_exit = _iteration_check(draft)+ except (OSError, ValueError) as e:+ lock.close()+ return _counter_failure(args, draft_identity, previous_gates, report_path, e)+ with lock:+ if iteration_exit != 0:+ # Keep the diagnostic the cap exists to hand over, but never as a+ # current result: the report stays blocked and incomplete.+ capped = _incomplete_report(+ draft_identity, args.strict,+ "iteration cap exceeded; the last complete run's gates are in previous_gates",+ )+ capped["iteration_cap_exceeded"] = True+ capped["previous_gates"] = previous_gates+ _atomic_write_json(report_path, capped, indent=2)+ if args.json:+ print(json.dumps(capped))+ return iteration_exit+ code = _run_gates(args, draft, draft_identity)+ if code == 1:+ try:+ _write_iteration_count(draft, _iteration_state_path(draft), _read_iteration_count(draft) + 1)+ except (OSError, ValueError) as e:+ print(f"ERROR: repair counter could not be updated: {e}", file=sys.stderr)+ return code+++def _counter_failure(+ args: argparse.Namespace, draft_identity: str, previous_gates: list[Any], report_path: Path, exc: BaseException,+) -> int:+ """Fail closed, with a clear message, when the repair counter is unusable."""+ reason = (+ f"repair counter unavailable ({type(exc).__name__}: {exc}); check that the review state "+ f"directory is writable or set {REVIEW_STATE_ENV}")- if iteration_exit != 0:- # Keep the diagnostic the cap exists to hand over, but never as a- # current result: the report stays blocked and incomplete.- capped = _incomplete_report(- draft_identity, args.strict,- "iteration cap exceeded; the last complete run's gates are in previous_gates",- )- capped["iteration_cap_exceeded"] = True- capped["previous_gates"] = previous_gates- _atomic_write_json(report_path, capped, indent=2)- return iteration_exit+ failed = _incomplete_report(draft_identity, args.strict, reason)+ failed["iteration_counter_error"] = True+ if previous_gates:+ failed["previous_gates"] = previous_gates+ try:+ _atomic_write_json(report_path, failed, indent=2)+ except (OSError, ValueError):+ pass+ if args.json:+ print(json.dumps(failed))+ print(f"ERROR: {reason}", file=sys.stderr)+ return 1++def _run_gates(args: argparse.Namespace, draft: Path, draft_identity: str) -> int:+ """Run the selected gates, write the report and return the exit status."""live_tools = _parse_tool_names(args.tools_json or os.environ.get("CLAUDE_BLOG_TOOLS_JSON"))rendered_context: dict[str, Any] = {}@@ -3214,8 +3460,9 @@ def _run_preflight(args: argparse.Namespace, draft: Path, draft_identity: str) -rendered_schema_validation=rendered_context.get("schema"),)+ project_dir = getattr(args, "user_project_dir", None)gates = [- (1, lambda d: gate_1_capability_discovery(d, live_tools=live_tools)),+ (1, lambda d: gate_1_capability_discovery(d, live_tools=live_tools, project_dir=project_dir)),(2, lambda d: gate_2_format_completeness(d, slug=args.slug)),(3, run_gate_3),(4, gate_4_content_review),@@ -3279,8 +3526,8 @@ def _run_preflight(args: argparse.Namespace, draft: Path, draft_identity: str) -print(f" violation: {v}")for w in r.get("warnings", []):print(f" warning: {w}")- if blocked and not args.strict:- print("WARNING: contract bypassed via --no-strict; do not publish without manual review.", file=sys.stderr)+ if blocked and not args.strict:+ print(_bypass_warning(results), file=sys.stderr)if blocked and args.strict:return 1diff --git a/scripts/blog_studio_status.py b/scripts/blog_studio_status.pyindex 3cc7827..e4f5ed5 100644--- a/scripts/blog_studio_status.py+++ b/scripts/blog_studio_status.py@@ -53,29 +53,40 @@ LABELS = {def anchored_draft(draft_name: str, project_name: str):"""Anchor a Linux companion subprocess to a verified directory object.- Walking with directory descriptors and O_NOFOLLOW refuses ancestor links.- Relative gate I/O then uses the anchored cwd, so replacing the lexical- draft path after launch cannot redirect report writes to another directory.- This is path containment, not a sandbox against a hostile local user.+ Symlinks at or above the project root (``/home -> var/home`` on Fedora+ atomic, ``/tmp`` and ``/var`` on macOS, or a linked project folder) are+ the operator's choice and are resolved once. Every component from the+ resolved root down to the draft is then walked with directory descriptors+ and O_NOFOLLOW, so a symlink between the project root and the draft is+ refused, as is any ``..``. Relative gate I/O then uses the anchored cwd, so+ replacing the lexical draft path after launch cannot redirect report+ writes to another directory. The yielded identity is the draft path made+ absolute (joined to the current directory, symlinks not resolved). This is+ path containment, not a sandbox against a hostile local user."""if not all(hasattr(os, name) for name in ("O_NOFOLLOW", "O_DIRECTORY", "fchdir")):raise ValueError("project-contained execution requires Unix directory descriptors")# "." is harmless (pathlib drops it, so `--project-root .` works); ".." is not.if any(part == ".." for value in (draft_name, project_name) for part in value.split("/")):raise ValueError("draft/project traversal is refused")- project = Path(project_name).absolute()+ lexical_project = Path(project_name).absolute()+ project = Path(os.path.realpath(lexical_project))selected = Path(draft_name).absolute()- selected.relative_to(project)+ try:+ relative = selected.relative_to(lexical_project)+ except ValueError:+ # The draft may be spelled from the resolved root instead.+ relative = selected.relative_to(project)flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOWprevious = os.open(".", flags)current = -1try:current = os.open("/", flags)- for component in selected.parts[1:]:+ for component in project.parts[1:] + relative.parts:child = os.open(component, flags, dir_fd=current)os.close(current)current = child- expected, actual = os.stat(selected, follow_symlinks=False), os.fstat(current)+ expected, actual = os.stat(project / relative, follow_symlinks=False), os.fstat(current)if (expected.st_dev, expected.st_ino) != (actual.st_dev, actual.st_ino):raise ValueError("selected draft changed during launch")os.fchdir(current)diff --git a/tests/test_blog_delivery_contract.py b/tests/test_blog_delivery_contract.pyindex 472450d..fb24aed 100644--- a/tests/test_blog_delivery_contract.py+++ b/tests/test_blog_delivery_contract.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport jsonimport importlib.util+import osimport reimport subprocessimport sys@@ -408,6 +409,8 @@ def test_preflight_gate_1_rejects_symlink_capabilities_output(tmp_path: Path) ->[sys.executable, str(PREFLIGHT_PATH), "--draft", str(tmp_path),"--gate", "1", "--no-strict"],capture_output=True, text=True, check=False,+ # A stock key gives Gate 1 a hero path, so it never probes Openverse.+ env={**os.environ, "PEXELS_API_KEY": "your-test-key"},)assert "FAIL" in result.stdout and "Gate 1" in result.stdoutassert "capabilities.json write refused" in result.stdoutdiff --git a/tests/test_blog_studio.py b/tests/test_blog_studio.pyindex 37e9f03..027b19a 100644--- a/tests/test_blog_studio.py+++ b/tests/test_blog_studio.py@@ -351,9 +351,9 @@ def test_unfinished_run_marker_is_blocked_not_passed(draft, monkeypatch):def test_iteration_cap_keeps_lexical_draft_and_never_looks_passed(draft, monkeypatch):run(draft, monkeypatch)- (draft / '.iteration-count').write_text(str(preflight.MAX_ITERATIONS) + '\n')+ preflight._write_iteration_count(draft, preflight._iteration_state_path(draft), preflight.MAX_ITERATIONS)monkeypatch.setattr(sys, 'argv', ['blog_preflight.py', '--draft', str(draft), '--json',- '--repair-attempt', '--project-root', str(draft.parent)])+ '--project-root', str(draft.parent)])assert preflight.main() == preflight.EXIT_ITERATION_CAPreport = json.loads((draft / 'preflight-report.json').read_text())assert report['draft'] == str(draft) and report['incomplete'] is True and report['blocked'] is Truediff --git a/tests/test_blog_studio_integration.py b/tests/test_blog_studio_integration.pyindex 53e4f10..c391eec 100644--- a/tests/test_blog_studio_integration.py+++ b/tests/test_blog_studio_integration.py@@ -1,8 +1,9 @@"""Run the real engine scripts the way the Blog Studio plugin does.-plugins/blog-studio/hooks/register.ts runs blog_preflight.py with-``--draft <d> --strict --json --tools-json <list> --project-root <root>`` and then-blog_studio_status.py with ``--project-root`` and ``--expected-run``. These tests+plugins/blog-studio/hooks/register.ts runs ``python3 -E blog_preflight.py`` with+``--draft <d> --strict --json --manual-check --tools-json <list> --project-root <root>``+and then ``python3 -E blog_studio_status.py`` with ``--project-root`` and+``--expected-run``. These testsspawn both scripts as subprocesses and validate the output with a Python mirrorof ``parseStatus`` in hooks/logic.ts and the report checks in hooks/register.ts.@@ -99,14 +100,16 @@ def project(tmp_path):draft.mkdir(parents=True)for name in ("post.md", "post.html", "post.pdf", "hero.webp", "review.md"):(draft / name).write_text("fixture " + name)- env = {**os.environ, "CLAUDE_BLOG_REVIEW_STATE_DIR": str(tmp_path / "verifier")}+ # A stock key gives Gate 1 a hero path, so it never probes Openverse.+ env = {**os.environ, "CLAUDE_BLOG_REVIEW_STATE_DIR": str(tmp_path / "verifier"), "PEXELS_API_KEY": "your-test-key"}return root, draft, env-def preflight(root, draft, env, *, patched, extra=()):- argv = [sys.executable]+def preflight(root, draft, env, *, patched, extra=(), manual=True):+ argv = [sys.executable, "-E"]argv += ["-c", HARNESS, str(SCRIPTS)] if patched else [str(SCRIPTS / "blog_preflight.py")]- argv += ["--draft", str(draft), "--strict", "--json", "--tools-json", "[]", "--project-root", str(root), *extra]+ argv += ["--draft", str(draft), "--strict", "--json", *(["--manual-check"] if manual else []),+ "--tools-json", "[]", "--project-root", str(root), *extra]proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=120)return proc, json.loads(proc.stdout)@@ -171,10 +174,14 @@ def test_expected_run_mismatch_is_an_error_status(project):def test_iteration_cap_exit_stays_additive_and_never_passes(project):root, draft, env = project+ # Passing runs never count; three failed full runs reach the cap.assert preflight(root, draft, env, patched=True)[0].returncode == 0- (draft / ".iteration-count").write_text("3\n")+ for _ in range(3):+ assert preflight(root, draft, env, patched=False, manual=False)[0].returncode == 1+ # A legacy in-draft counter is ignored; the external one already holds 3 failed runs.+ (draft / ".iteration-count").write_text("0\n")argv = [sys.executable, str(SCRIPTS / "blog_preflight.py"), "--draft", str(draft), "--strict", "--json",- "--tools-json", "[]", "--project-root", str(root), "--repair-attempt"]+ "--tools-json", "[]", "--project-root", str(root)]proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)assert proc.returncode == 2 and "ITERATION CAP EXCEEDED" in proc.stderrmarker = json.loads((draft / "preflight-report.json").read_text())@@ -182,6 +189,19 @@ def test_iteration_cap_exit_stays_additive_and_never_passes(project):assert status(root, draft, env)[1]["status"] == "blocked"+def test_repeated_studio_checks_never_reach_the_cap(project):+ """Studio runs pass --manual-check: re-checking a post, failing or passing, never caps."""+ root, draft, env = project+ for _ in range(5):+ proc, report = preflight(root, draft, env, patched=False)+ assert proc.returncode == 1 and report["blocked"] is True+ for _ in range(2):+ proc, _report = preflight(root, draft, env, patched=True)+ assert proc.returncode == 0, proc.stderr+ state = Path(env["CLAUDE_BLOG_REVIEW_STATE_DIR"])+ assert not list(state.glob("*.iterations.json"))++def test_preflight_without_project_root_still_works_and_adds_evidence(project):root, draft, env = projectargv = [sys.executable, str(SCRIPTS / "blog_preflight.py"), "--draft", str(draft), "--strict", "--json",@@ -218,3 +238,82 @@ def test_project_root_outside_the_draft_is_refused(project, tmp_path):proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)assert proc.returncode == 1 and "refused" in proc.stderrassert not (draft / "preflight-report.json").exists()+++def _linked_project(tmp_path):+ """A project reached through a symlinked ancestor, like /home -> var/home."""+ real = tmp_path / "real"+ draft = real / "project" / "drafts" / "post"+ draft.mkdir(parents=True)+ for name in ("post.md", "post.html", "post.pdf", "hero.webp", "review.md"):+ (draft / name).write_text("fixture " + name)+ (tmp_path / "link").symlink_to(real, target_is_directory=True)+ root = tmp_path / "link" / "project"+ env = {**os.environ, "CLAUDE_BLOG_REVIEW_STATE_DIR": str(tmp_path / "verifier"), "PEXELS_API_KEY": "your-test-key"}+ return root, root / "drafts" / "post", env+++def test_symlinked_ancestor_of_the_project_root_is_resolved(tmp_path):+ root, draft, env = _linked_project(tmp_path)+ proc, report = preflight(root, draft, env, patched=True)+ assert proc.returncode == 0, proc.stderr+ run_id = check_report(report, draft, proc.returncode)+ # The report records the absolute draft path, symlinks not resolved.+ assert report["draft"] == str(draft)+ proc, passed = status(root, draft, env, run_id)+ assert proc.returncode == 0, passed+ assert passed["status"] == "passed"+++def test_project_root_that_is_itself_a_symlink_is_resolved(tmp_path):+ _root, _draft, env = _linked_project(tmp_path)+ (tmp_path / "proj-link").symlink_to(tmp_path / "real" / "project", target_is_directory=True)+ root = tmp_path / "proj-link"+ draft = root / "drafts" / "post"+ proc, report = preflight(root, draft, env, patched=True)+ assert proc.returncode == 0, proc.stderr+ assert status(root, draft, env, check_report(report, draft, proc.returncode))[1]["status"] == "passed"+++def test_symlink_between_the_project_root_and_the_draft_is_still_refused(tmp_path):+ root, draft, env = _linked_project(tmp_path)+ (root / "drafts" / "alias").symlink_to(draft, target_is_directory=True)+ (root / "hop").symlink_to(root / "drafts", target_is_directory=True)+ for linked in (root / "drafts" / "alias", root / "hop" / "post"):+ argv = [sys.executable, str(SCRIPTS / "blog_preflight.py"), "--draft", str(linked), "--strict", "--json",+ "--tools-json", "[]", "--project-root", str(root)]+ proc = subprocess.run(argv, cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60)+ assert proc.returncode == 1 and "refused" in proc.stderr, proc.stderr+ proc = subprocess.run([sys.executable, str(SCRIPTS / "blog_studio_status.py"), "--draft", str(linked),+ "--project-root", str(root)], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60)+ assert json.loads(proc.stdout)["status"] == "error"+ assert not (draft / "preflight-report.json").exists()+++def test_dot_dot_escape_is_still_refused(tmp_path):+ root, draft, env = _linked_project(tmp_path)+ escaped = f"{root}/drafts/../drafts/post"+ proc = subprocess.run([sys.executable, str(SCRIPTS / "blog_studio_status.py"), "--draft", escaped,+ "--project-root", str(root)], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60)+ result = json.loads(proc.stdout)+ assert proc.returncode == 1 and result["status"] == "error"+ assert "traversal" in result["diagnostics"][0]++[email protected](not Path("/home").is_symlink(), reason="needs a system /home symlink (Fedora atomic)")+def test_system_home_symlink_project_root_works(tmp_path):+ """The reported repro: /home -> var/home made --project-root fail with 'Not a directory'."""+ home_target = Path(os.path.realpath("/home"))+ real_tmp = Path(os.path.realpath(tmp_path))+ if home_target not in real_tmp.parents:+ pytest.skip("tmp_path is not below the /home symlink target")+ lexical = Path("/home") / real_tmp.relative_to(home_target)+ draft = lexical / "post"+ draft.mkdir()+ for name in ("post.md", "post.html", "post.pdf", "hero.webp", "review.md"):+ (draft / name).write_text("fixture " + name)+ env = {**os.environ, "CLAUDE_BLOG_REVIEW_STATE_DIR": str(tmp_path / "verifier"), "PEXELS_API_KEY": "your-test-key"}+ proc, report = preflight(lexical, draft, env, patched=True)+ assert proc.returncode == 0, proc.stderr+ proc, result = status(lexical, draft, env, check_report(report, draft, proc.returncode))+ assert result["status"] == "passed", resultdiff --git a/tests/test_iteration_counter.py b/tests/test_iteration_counter.pyindex 2c3ca08..016ec33 100644--- a/tests/test_iteration_counter.py+++ b/tests/test_iteration_counter.py@@ -1,13 +1,16 @@-"""Code-enforced iteration counter tests (VULN-802, v1.9.1).+"""Code-enforced iteration counter tests (VULN-802).-The 5-gate Blog Delivery Contract documents 'up to 3 retries before-escalating' but v1.9.0 enforced it only as orchestrator prose. This-suite locks in the file-backed counter at <draft>/.iteration-count-that survives across preflight invocations.+The Blog Delivery Contract allows 3 failed full gate runs per draft; the next+full run exits 2. Only a failed counted run (exit 1 under --strict) counts:+passing runs, --gate runs, --init-review-nonce and --manual-check never do.+The counter lives with the review nonce state outside the draft folder,+keyed the same way, so an agent that can write the draft cannot reset it. A+legacy <draft>/.iteration-count file is ignored."""from __future__ import annotationsimport json+import osimport subprocessimport sysfrom pathlib import Path@@ -16,15 +19,13 @@ import pytestROOT = Path(__file__).resolve().parent.parentPREFLIGHT = ROOT / "scripts" / "blog_preflight.py"+sys.path.insert(0, str(ROOT / "scripts"))+import blog_preflight # noqa: E402-def _make_minimal_draft(tmp: Path) -> Path:- """Create a draft folder skeleton sufficient for preflight to run.- Note: preflight will likely fail Gate 1-5 on this minimal draft.- That's intentional; the counter test only cares about iteration- bookkeeping, not gate outcomes.- """+def _make_minimal_draft(tmp: Path) -> Path:+ """A draft that always fails Gate 2 (no html, pdf or hero)."""draft = tmp / "post"draft.mkdir()(draft / "post.md").write_text(@@ -34,73 +35,232 @@ def _make_minimal_draft(tmp: Path) -> Path:return draft+def _env(tmp: Path) -> dict[str, str]:+ env = dict(os.environ)+ env[blog_preflight.REVIEW_STATE_ENV] = str(tmp / "state")+ # A stock key gives Gate 1 a free hero path, so it never probes Openverse.+ env.update({"PEXELS_API_KEY": "your-test-key"})+ return env++def _run_preflight(draft: Path, *extra) -> subprocess.CompletedProcess:- cmd = [sys.executable, str(PREFLIGHT), "--draft", str(draft), "--no-strict", *extra]- return subprocess.run(cmd, capture_output=True, text=True, cwd=str(ROOT))+ cmd = [sys.executable, str(PREFLIGHT), "--draft", str(draft), *extra]+ return subprocess.run(cmd, capture_output=True, text=True, cwd=str(ROOT), env=_env(draft.parent))+++def _counter_path(draft: Path) -> Path:+ state = draft.parent / "state"+ digest = blog_preflight._review_state_path(draft).stem+ return state / f"{digest}{blog_preflight.ITERATION_STATE_SUFFIX}"++def _count(draft: Path) -> int:+ path = _counter_path(draft)+ return json.loads(path.read_text(encoding="utf-8"))["runs"] if path.exists() else 0-def test_normal_run_does_not_create_counter(tmp_path):++def _stub_gates(monkeypatch, passing: bool) -> None:+ names = ("gate_1_capability_discovery", "gate_2_format_completeness", "gate_3_visual_verification",+ "gate_4_content_review", "gate_5_asset_link_integrity")+ for n, name in enumerate(names, 1):+ def gate(_draft, n=n, **_kwargs):+ ok = passing or n != 2+ return blog_preflight._gate_result(n, blog_preflight.GATE_NAMES[n], ok, [] if ok else ["fixture"])+ monkeypatch.setattr(blog_preflight, name, gate)+++def _main(monkeypatch, draft: Path, *extra) -> int:+ monkeypatch.setenv(blog_preflight.REVIEW_STATE_ENV, str(draft.parent / "state"))+ monkeypatch.setattr(sys, "argv", ["blog_preflight.py", "--draft", str(draft), *extra])+ return blog_preflight.main()+++def test_counter_lives_outside_the_draft_keyed_like_the_nonce(tmp_path, monkeypatch):draft = _make_minimal_draft(tmp_path)- assert not (draft / ".iteration-count").exists()- _run_preflight(draft)+ monkeypatch.setenv(blog_preflight.REVIEW_STATE_ENV, str(tmp_path / "state"))+ nonce = blog_preflight._review_state_path(draft)+ counter = blog_preflight._iteration_state_path(draft)+ assert counter.parent == nonce.parent+ assert counter.name == nonce.stem + ".iterations.json"+ assert draft not in counter.parents+++def test_failed_full_run_counts_and_nothing_is_written_to_the_draft(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ assert _run_preflight(draft).returncode == 1+ assert _count(draft) == 1assert not (draft / ".iteration-count").exists()-def test_first_repair_attempt_creates_counter_at_one(tmp_path):+def test_three_failed_runs_then_the_next_full_run_exits_two(tmp_path):draft = _make_minimal_draft(tmp_path)- _run_preflight(draft, "--repair-attempt")- counter_file = draft / ".iteration-count"- assert counter_file.exists()- assert counter_file.read_text(encoding="utf-8").strip() == "1"+ for _ in range(3):+ assert _run_preflight(draft).returncode == 1+ assert _count(draft) == 3+ result = _run_preflight(draft, "--json")+ assert result.returncode == 2, result.stderr+ assert "ITERATION CAP EXCEEDED" in result.stderr+ assert "failed 3 full gate runs" in result.stderr+ assert "new write or rewrite" in result.stderr+ capped = json.loads(result.stdout)+ assert capped["iteration_cap_exceeded"] is True and capped["blocked"] is True+ assert _count(draft) == 3-def test_three_runs_accumulate_to_three(tmp_path):+def test_passing_runs_never_count(tmp_path, monkeypatch):draft = _make_minimal_draft(tmp_path)+ _stub_gates(monkeypatch, passing=True)+ for _ in range(6):+ assert _main(monkeypatch, draft) == 0+ assert _count(draft) == 0+++def test_passing_run_at_the_cap_is_still_refused(tmp_path, monkeypatch):+ draft = _make_minimal_draft(tmp_path)+ _stub_gates(monkeypatch, passing=False)for _ in range(3):- _run_preflight(draft, "--repair-attempt")- assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "3"+ assert _main(monkeypatch, draft) == 1+ _stub_gates(monkeypatch, passing=True)+ assert _main(monkeypatch, draft) == blog_preflight.EXIT_ITERATION_CAP-def test_fourth_run_exits_with_code_two(tmp_path):+def test_no_strict_blocked_runs_do_not_count(tmp_path, monkeypatch):draft = _make_minimal_draft(tmp_path)+ _stub_gates(monkeypatch, passing=False)+ for _ in range(4):+ assert _main(monkeypatch, draft, "--no-strict") == 0+ assert _count(draft) == 0+++def test_manual_check_never_reads_or_changes_the_counter(tmp_path, monkeypatch):+ draft = _make_minimal_draft(tmp_path)+ _stub_gates(monkeypatch, passing=False)for _ in range(3):- _run_preflight(draft, "--repair-attempt")- result = _run_preflight(draft, "--repair-attempt")- assert result.returncode == 2, (- f"expected exit 2 (iteration cap), got {result.returncode}\n"- f"stdout: {result.stdout}\nstderr: {result.stderr}"- )- assert "ITERATION CAP" in result.stderr.upper() or "iteration" in result.stderr.lower()+ _main(monkeypatch, draft)+ assert _count(draft) == 3+ for _ in range(5):+ assert _main(monkeypatch, draft, "--manual-check") == 1+ assert _count(draft) == 3+ _stub_gates(monkeypatch, passing=True)+ assert _main(monkeypatch, draft, "--manual-check") == 0+++def test_manual_check_works_with_an_unwritable_state_dir(tmp_path, monkeypatch):+ draft = _make_minimal_draft(tmp_path)+ _stub_gates(monkeypatch, passing=False)+ (tmp_path / "state").write_text("not a directory")+ assert _main(monkeypatch, draft, "--manual-check") == 1+ assert json.loads((draft / "preflight-report.json").read_text())["gates"]-def test_reset_iterations_flag_resets_counter(tmp_path):+def test_repair_attempt_applies_the_cap_to_single_gate_runs(tmp_path):draft = _make_minimal_draft(tmp_path)for _ in range(3):- _run_preflight(draft, "--repair-attempt")- # 4th would refuse; --reset-iterations clears and allows a fresh run.- result = _run_preflight(draft, "--reset-iterations", "--repair-attempt")- assert result.returncode != 2, (- f"--reset-iterations should allow a fresh run, got exit {result.returncode}"- )- assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "1"+ assert _run_preflight(draft, "--gate", "2", "--repair-attempt").returncode == 1+ assert _run_preflight(draft, "--gate", "2", "--repair-attempt").returncode == 2+++def test_single_gate_runs_never_count(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ for _ in range(4):+ assert _run_preflight(draft, "--gate", "2").returncode == 1+ assert not _counter_path(draft).exists()+++def test_init_review_nonce_does_not_count(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ result = _run_preflight(draft, "--init-review-nonce")+ assert result.returncode == 0+ assert not _counter_path(draft).exists()+++def test_reset_iterations_resets_and_runs_no_gates(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ for _ in range(3):+ _run_preflight(draft)+ (draft / "preflight-report.json").unlink()+ result = _run_preflight(draft, "--reset-iterations")+ assert result.returncode == 0, result.stderr+ assert _count(draft) == 0+ assert not (draft / "preflight-report.json").exists(), "a reset must not run or record gates"+ assert _run_preflight(draft).returncode == 1+ assert _count(draft) == 1+++def test_reset_with_init_review_nonce_still_prints_the_nonce(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ for _ in range(3):+ _run_preflight(draft)+ result = _run_preflight(draft, "--reset-iterations", "--init-review-nonce")+ assert result.returncode == 0+ assert len(result.stdout.strip()) == 32+ assert _count(draft) == 0-def test_corrupted_counter_file_resets_to_one(tmp_path):- """Tampered counter file (non-int) is treated as 0 and run proceeds.+def test_corrupted_counter_file_counts_as_zero(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ path = _counter_path(draft)+ path.parent.mkdir(parents=True)+ path.write_text("not-json", encoding="utf-8")+ assert _run_preflight(draft).returncode == 1+ assert _count(draft) == 1+- Fail-soft: an attacker who can write to the draft folder already has- bigger problems (can write review.md, modify the .md). Refusing to- run on garbage counter would create a self-DoS vector.- """+def test_legacy_draft_counter_is_ignored(tmp_path):+ """An old <draft>/.iteration-count neither caps nor resets the new counter."""draft = _make_minimal_draft(tmp_path)- (draft / ".iteration-count").write_text("not-an-int", encoding="utf-8")- result = _run_preflight(draft, "--repair-attempt")- assert result.returncode != 2- assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "1"+ (draft / ".iteration-count").write_text("3\n", encoding="utf-8")+ assert _run_preflight(draft).returncode == 1+ assert _count(draft) == 1+ (draft / ".iteration-count").write_text("0\n", encoding="utf-8")+ for _ in range(2):+ _run_preflight(draft)+ assert _run_preflight(draft).returncode == 2-def test_counter_not_incremented_on_reset_run(tmp_path):- """--reset-iterations without repair leaves counter at 0."""+def test_deleting_draft_files_does_not_reset_the_counter(tmp_path):draft = _make_minimal_draft(tmp_path)- _run_preflight(draft, "--reset-iterations")- assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "0"+ for _ in range(3):+ _run_preflight(draft)+ for child in draft.iterdir():+ if child.is_file():+ child.unlink()+ assert _run_preflight(draft).returncode == 2++[email protected]("json_mode", [False, True])+def test_unwritable_state_dir_fails_cleanly(tmp_path, json_mode):+ draft = _make_minimal_draft(tmp_path)+ (tmp_path / "state").write_text("a file where the state directory should be")+ result = _run_preflight(draft, *(["--json"] if json_mode else []))+ assert result.returncode == 1+ assert "Traceback" not in result.stderr+ assert "repair counter unavailable" in result.stderr+ if json_mode:+ report = json.loads(result.stdout)+ assert report["blocked"] is True and report["iteration_counter_error"] is True+ assert "repair counter unavailable" in report["reason"]+++def test_concurrent_failed_runs_never_exceed_the_cap(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ cmd = [sys.executable, str(PREFLIGHT), "--draft", str(draft)]+ procs = [subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,+ cwd=str(ROOT), env=_env(tmp_path)) for _ in range(6)]+ codes = [p.wait(timeout=120) for p in procs]+ for p in procs:+ p.stderr.close()+ assert sorted(codes) == [1, 1, 1, 2, 2, 2]+ assert _count(draft) == 3++[email protected]("flag,needle", [+ ("--reset-iterations", "new write or rewrite"),+ ("--repair-attempt", "passing runs never count"),+ ("--manual-check", "without reading or changing the repair counter"),+])+def test_counter_flags_help_explains_the_rule(flag, needle):+ result = subprocess.run([sys.executable, str(PREFLIGHT), "--help"], capture_output=True, text=True)+ text = " ".join(result.stdout.split())+ assert flag in text+ assert needle in textdiff --git a/tests/test_preflight_gate1_hero_paths.py b/tests/test_preflight_gate1_hero_paths.pynew file mode 100644index 0000000..0e3d2a7--- /dev/null+++ b/tests/test_preflight_gate1_hero_paths.py@@ -0,0 +1,344 @@+"""Gate 1 hero paths, project-root context files and the --no-strict warning.++Free hero paths: a valid local hero, a stock key, a reachable Openverse.+Paid paths (live Banana MCP, Gemini key) need the user's consent, so Openverse+is probed whenever no other free path exists. Gate 1 passes with any free+path, passes with only paid paths (``paid_only`` plus a cost warning), and+blocks only when there is no path at all. The Openverse probe is+monkeypatched everywhere here; no test touches the network.+"""+from __future__ import annotations++import json+import socket+import struct+import sys+import time+import zlib+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "scripts"))++import blog_preflight as preflight # noqa: E402++KEYS = ("GOOGLE_AI_API_KEY", "GEMINI_API_KEY", "UNSPLASH_ACCESS_KEY", "PEXELS_API_KEY", "PIXABAY_API_KEY")+++def _png(width: int, height: int) -> bytes:+ def chunk(kind: bytes, data: bytes) -> bytes:+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)+ raw = b"".join(b"\x00" + b"\x80" * (width * 3) for _ in range(height))+ ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")+++def offline(monkeypatch, tmp_path):+ """No keys, an unreachable Openverse, and a record of probe calls."""+ for key in KEYS:+ monkeypatch.delenv(key, raising=False)+ calls: list[int] = []++ def unreachable(*_args, **_kwargs):+ calls.append(1)+ return False++ monkeypatch.setattr(preflight, "_openverse_reachable", unreachable)+ monkeypatch.setenv(preflight.REVIEW_STATE_ENV, str(tmp_path / "state"))+ draft = tmp_path / "draft"+ draft.mkdir()+ return draft, calls+++def _gate1(draft, **kwargs):+ kwargs.setdefault("project_dir", draft.parent)+ return preflight.gate_1_capability_discovery(draft, **kwargs)+++def test_no_hero_path_blocks_with_the_contract_message(offline):+ draft, calls = offline+ result = _gate1(draft)+ assert not result["passed"]+ assert preflight.NO_HERO_PATH_MESSAGE in result["violations"]+ assert result["violations"][0].startswith("Hero image required but no generation path available.")+ assert calls == [1]+ paths = result["capabilities"]["hero_paths"]+ assert paths["openverse_reachable"] is False and result["capabilities"]["image_gen_path_available"] is False+ assert "openverse_assumed_available" not in result["capabilities"]+++def test_reachable_openverse_is_a_hero_path(offline, monkeypatch):+ draft, _calls = offline+ monkeypatch.setattr(preflight, "_openverse_reachable", lambda *a, **k: True)+ result = _gate1(draft)+ assert result["passed"], result["violations"]+ assert result["capabilities"]["hero_paths"]["openverse_reachable"] is True+++def test_valid_local_hero_is_a_path_and_skips_the_probe(offline):+ draft, calls = offline+ (draft / "hero.png").write_bytes(_png(1200, 630))+ result = _gate1(draft)+ assert result["passed"], result["violations"]+ assert result["capabilities"]["hero_paths"]["local_hero"] == "hero.png"+ assert result["capabilities"]["hero_paths"]["openverse_reachable"] is None+ assert calls == []++[email protected]("content", [None, b"not an image", "1199"])+def test_too_small_or_broken_local_hero_does_not_count(offline, content):+ draft, _calls = offline+ data = {None: _png(40, 20), "1199": _png(1199, 630)}.get(content, content)+ (draft / "hero.png").write_bytes(data)+ result = _gate1(draft)+ assert not result["passed"]+ assert result["capabilities"]["hero_paths"]["local_hero"] is None+++def test_uppercase_hero_name_does_not_count(offline):+ draft, _calls = offline+ (draft / "hero.PNG").write_bytes(_png(1200, 630))+ if (draft / "hero.png").exists():+ pytest.skip("case-insensitive filesystem")+ assert _gate1(draft)["capabilities"]["hero_paths"]["local_hero"] is None+++def test_the_hero_the_renderer_would_use_decides(offline):+ """Renderer order is png, jpg, jpeg, webp; the first present file alone counts."""+ draft, _calls = offline+ (draft / "hero.webp").write_bytes(b"junk")+ (draft / "hero.png").write_bytes(_png(1200, 630))+ assert _gate1(draft)["capabilities"]["hero_paths"]["local_hero"] == "hero.png"+ (draft / "hero.png").write_bytes(_png(600, 315))+ (draft / "hero.jpg").write_bytes(b"also junk")+ assert _gate1(draft)["capabilities"]["hero_paths"]["local_hero"] is None+++def test_gate_1_and_gate_2_agree_on_a_hero_below_the_minimum(offline):+ draft, _calls = offline+ (draft / "hero.png").write_bytes(_png(1000, 600))+ assert _gate1(draft)["capabilities"]["hero_paths"]["local_hero"] is None+ problems, _evidence = preflight._hero_check(draft / "hero.png", (draft / "hero.png").read_bytes())+ assert problems+++def test_symlinked_local_hero_does_not_count(offline, tmp_path):+ draft, _calls = offline+ real = tmp_path / "elsewhere.png"+ real.write_bytes(_png(1200, 630))+ (draft / "hero.png").symlink_to(real)+ assert not _gate1(draft)["passed"]++[email protected]("key", ["UNSPLASH_ACCESS_KEY", "PEXELS_API_KEY", "PIXABAY_API_KEY"])+def test_stock_key_is_a_path_and_skips_the_probe(offline, monkeypatch, key):+ draft, calls = offline+ monkeypatch.setenv(key, "your-test-key")+ result = _gate1(draft)+ assert result["passed"], result["violations"]+ assert result["capabilities"]["hero_paths"]["stock_api"] is True+ assert calls == []+ assert not any("paid" in w for w in result["warnings"])++[email protected]("key", ["GOOGLE_AI_API_KEY", "GEMINI_API_KEY"])+def test_gemini_key_alone_is_paid_only_and_still_probes_openverse(offline, monkeypatch, key):+ draft, calls = offline+ monkeypatch.setenv(key, "your-test-key")+ result = _gate1(draft)+ assert result["passed"], result["violations"]+ assert result["capabilities"]["env_keys_present"][key] is True+ paths = result["capabilities"]["hero_paths"]+ assert paths["gemini_api"] == {"available": True, "paid": True, "requires_consent": True}+ assert paths["paid_only"] is True and paths["free_path"] is False+ assert any(w.startswith("paid_only:") and "approve the cost" in w and "--allow-paid" in w+ for w in result["warnings"])+ assert calls == [1], "a paid key must not skip the free Openverse probe"+++def test_live_banana_tool_alone_is_paid_only(offline):+ draft, calls = offline+ result = _gate1(draft, live_tools=["mcp__nanobanana__gemini_generate_image"])+ assert result["passed"], result["violations"]+ assert result["capabilities"]["hero_paths"]["paid_only"] is True+ assert any("Banana MCP" in w and "approve the cost" in w for w in result["warnings"])+ assert calls == [1]+++def test_paid_key_with_reachable_openverse_is_not_paid_only(offline, monkeypatch):+ draft, _calls = offline+ monkeypatch.setenv("GEMINI_API_KEY", "your-test-key")+ monkeypatch.setattr(preflight, "_openverse_reachable", lambda *a, **k: True)+ result = _gate1(draft)+ assert result["passed"]+ assert result["capabilities"]["hero_paths"]["paid_only"] is False+ assert not any(w.startswith("paid_only:") for w in result["warnings"])+++def test_capability_file_never_holds_key_values(offline, monkeypatch):+ draft, _calls = offline+ monkeypatch.setenv("GEMINI_API_KEY", "secret-value-must-not-appear")+ _gate1(draft)+ assert "secret-value-must-not-appear" not in (draft / "capabilities.json").read_text()+++# --- The Openverse probe itself ---------------------------------------------+++def test_probe_constants_are_https_and_at_most_three_seconds():+ assert preflight.OPENVERSE_PROBE_URL.startswith("https://api.openverse.org/")+ assert preflight.OPENVERSE_PROBE_TIMEOUT <= 3+++def test_probe_total_time_is_bounded(monkeypatch):+ monkeypatch.setattr(preflight, "_openverse_probe_once", lambda *_a: time.sleep(5) or True)+ started = time.monotonic()+ assert preflight._openverse_reachable(timeout=0.2) is False+ assert time.monotonic() - started < 1.5+++def test_probe_errors_count_as_unreachable(monkeypatch):+ def boom(*_a):+ raise OSError("down")+ monkeypatch.setattr(preflight, "_openverse_probe_once", boom)+ assert preflight._openverse_reachable(timeout=0.5) is False+++def test_probe_refuses_plain_http_before_any_lookup(monkeypatch):+ monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **k: pytest.fail("no DNS lookup for http"))+ assert preflight._openverse_probe_once("http://api.openverse.org/v1/images/", 1) is False+++def test_probe_refuses_non_public_addresses(monkeypatch):+ monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443))])+ monkeypatch.setattr(preflight, "_PinnedHTTPSConnection", lambda *a, **k: pytest.fail("must not connect"))+ assert preflight._openverse_probe_once(preflight.OPENVERSE_PROBE_URL, 1) is False++[email protected]("status,reachable", [(200, True), (301, False), (302, False), (403, False), (503, False)])+def test_probe_counts_only_a_direct_2xx(monkeypatch, status, reachable):+ public = [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))]+ monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **k: public)+ seen = {}++ class FakeConnection:+ def __init__(self, host, address, port, timeout):+ seen.update(host=host, address=address, port=port, timeout=timeout)++ def request(self, method, target, headers):+ seen.update(method=method, target=target)++ def getresponse(self):+ return type("R", (), {"status": status})()++ def close(self):+ seen["closed"] = True++ monkeypatch.setattr(preflight, "_PinnedHTTPSConnection", FakeConnection)+ assert preflight._openverse_probe_once(preflight.OPENVERSE_PROBE_URL, 2) is reachable+ assert seen["host"] == "api.openverse.org" and seen["address"] == "93.184.216.34" and seen["port"] == 443+ assert seen["method"] == "HEAD" and seen["target"].startswith("/v1/images/") and seen["closed"]+++# --- BRAND.md, VOICE.md, DISCOURSE.md come from the user's project ----------+++def _context_files(result):+ return result["capabilities"]["project_root_files"]+++def test_context_files_are_read_from_the_given_project_dir(offline, tmp_path):+ draft, _calls = offline+ project = tmp_path / "site"+ project.mkdir()+ (project / "BRAND.md").write_text("brand")+ (project / "DISCOURSE.md").write_text("discourse")+ files = _context_files(_gate1(draft, project_dir=project))+ assert files == {"BRAND.md": True, "VOICE.md": False, "DISCOURSE.md": True}+++def test_main_uses_project_root_for_context_files(offline, monkeypatch, tmp_path):+ draft, _calls = offline+ (tmp_path / "VOICE.md").write_text("voice")+ elsewhere = tmp_path / "cwd"+ elsewhere.mkdir()+ monkeypatch.chdir(elsewhere)+ monkeypatch.setattr(sys, "argv", ["blog_preflight.py", "--draft", str(draft), "--gate", "1",+ "--no-strict", "--project-root", str(tmp_path)])+ preflight.main()+ capabilities = json.loads((draft / "capabilities.json").read_text())+ assert capabilities["project_root_files"]["VOICE.md"] is True+ assert capabilities["project_root"] == str(tmp_path.resolve())+++def test_main_defaults_to_the_current_directory_not_the_install_root(offline, monkeypatch, tmp_path):+ draft, _calls = offline+ cwd = tmp_path / "user-project"+ cwd.mkdir()+ (cwd / "BRAND.md").write_text("brand")+ monkeypatch.chdir(cwd)+ monkeypatch.setattr(sys, "argv", ["blog_preflight.py", "--draft", str(draft), "--gate", "1", "--no-strict"])+ preflight.main()+ capabilities = json.loads((draft / "capabilities.json").read_text())+ assert capabilities["project_root_files"]["BRAND.md"] is True+ assert capabilities["project_root"] == str(cwd)+++# --- --no-strict prints the contract's bypass warning in every mode ----------+++def _contract_warning() -> str:+ text = (ROOT / "skills/blog/references/blog-delivery-contract.md").read_text(encoding="utf-8")+ block = text[text.index("## Bypass Mechanism"):]+ return block[block.index("```\n") + 4:block.index("\n```", block.index("```\n") + 4)]+++def _stub_gates(monkeypatch, failing):+ names = ("gate_1_capability_discovery", "gate_2_format_completeness", "gate_3_visual_verification",+ "gate_4_content_review", "gate_5_asset_link_integrity")+ for n, name in enumerate(names, 1):+ def gate(_draft, n=n, **_kwargs):+ return preflight._gate_result(n, preflight.GATE_NAMES[n], n not in failing,+ ["fixture"] if n in failing else [])+ monkeypatch.setattr(preflight, name, gate)++[email protected]("json_mode", [False, True])+def test_bypass_warning_matches_the_contract_text(offline, monkeypatch, capsys, json_mode):+ draft, _calls = offline+ _stub_gates(monkeypatch, {3, 5})+ argv = ["blog_preflight.py", "--draft", str(draft), "--no-strict", "--diagnostics-all"]+ if json_mode:+ argv.append("--json")+ monkeypatch.setattr(sys, "argv", argv)+ assert preflight.main() == 0+ out = capsys.readouterr()+ expected = _contract_warning()+ assert "Failed gates: [Gate 3, Gate 5]." in expected+ assert expected in out.err+ assert "WARNING" not in out.out+ if json_mode:+ json.loads(out.out)+++def test_no_bypass_warning_when_nothing_failed_or_strict(offline, monkeypatch, capsys):+ draft, _calls = offline+ _stub_gates(monkeypatch, set())+ monkeypatch.setattr(sys, "argv", ["blog_preflight.py", "--draft", str(draft), "--no-strict", "--json"])+ assert preflight.main() == 0+ assert "bypassed" not in capsys.readouterr().err+ _stub_gates(monkeypatch, {2})+ monkeypatch.setattr(sys, "argv", ["blog_preflight.py", "--draft", str(draft), "--json"])+ assert preflight.main() == 1+ assert "bypassed" not in capsys.readouterr().err+++def test_project_root_help_matches_the_recorded_path():+ import subprocess+ text = " ".join(subprocess.run([sys.executable, str(ROOT / "scripts/blog_preflight.py"), "--help"],+ capture_output=True, text=True, check=True).stdout.split())+ assert "as given" not in text+ assert "absolute path" in text and "symlinks not resolved" in textdiff --git a/tests/test_preflight_hardening.py b/tests/test_preflight_hardening.pyindex 8a5a1c6..7a02167 100644--- a/tests/test_preflight_hardening.py+++ b/tests/test_preflight_hardening.py@@ -246,7 +246,9 @@ def test_every_gate_3_context_blocks_service_workers():# --- Gate 4 reviewer contract ------------------------------------------------def _review(nonce, clearance="zero P0 issues found", overall=92, categories="", reason="cleared all gates"):+def _review(nonce, clearance="zero P0 issues found", overall=92, categories=None, reason="cleared all gates"):+ if categories is None:+ categories = TABLE_92return ("## Quality Review: Fixture\n"f"### Overall Score: {overall}/100 - Exceptional\n"@@ -301,7 +303,7 @@ def test_gate_4_accepts_plural_zero_clearance(gate4, clearance):def test_gate_4_rejects_category_scores_that_contradict_the_overall(gate4):- result = gate4(categories="Content Quality: 3/30\n", overall=91)+ result = gate4(categories=TABLE_92.replace("| Content Quality | 28 |", "| Content Quality | 3 |"), overall=91)assert not result["passed"]assert any("inconsistent with its category scores" in item for item in result["violations"])@@ -330,17 +332,36 @@ def test_gate_4_rejects_conflicting_category_scores(gate4):assert any("conflicting Content Quality" in item for item in result["violations"])+LINES_92 = (+ "Content Quality: 28/30\nSEO Optimization: 23/25\nE-E-A-T Signals: 14/15\n"+ "Technical Elements: 14/15\nAI Citation Readiness: 13/15\n"+)++@pytest.mark.parametrize("categories,overall", [(TABLE_92, 92),- ("Content Quality: 28/30\nSEO Optimization: 23/25\n", 92),- ("Content Quality (30 pts): 28\n", 92),- ("", 92),+ (LINES_92, 92),+ (LINES_92.replace("Content Quality: 28/30", "Content Quality (30 pts): 28"), 92),])-def test_gate_4_accepts_consistent_or_absent_category_scores(gate4, categories, overall):+def test_gate_4_accepts_consistent_category_scores(gate4, categories, overall):result = gate4(categories=categories, overall=overall)assert result["passed"], result["violations"][email protected]("categories,missing", [+ ("", ["Content Quality", "SEO Optimization", "E-E-A-T Signals", "Technical Elements", "AI Citation Readiness"]),+ ("Content Quality: 28/30\nSEO Optimization: 23/25\n", ["E-E-A-T Signals", "Technical Elements", "AI Citation Readiness"]),+ (TABLE_92.replace("| AI Citation Readiness | 13 | 15 | strong |\n", ""), ["AI Citation Readiness"]),+])+def test_gate_4_requires_all_five_category_scores(gate4, categories, missing):+ """An overall-only or partial scorecard fails: the contract requires all five."""+ result = gate4(categories=categories, overall=92)+ assert not result["passed"]+ for name in missing:+ assert f"review.md is missing the {name} score" in result["violations"]+ assert not any("inconsistent" in item for item in result["violations"])++def test_gate_4_blocks_when_the_draft_changed_after_the_nonce_was_issued(preflight, gate4):draft = gate4.draft(draft / "post.html").write_text("<html>first</html>")@@ -438,8 +459,9 @@ def test_crashing_gate_becomes_a_failed_gate_and_a_fresh_report(preflight, monkedef test_iteration_cap_cannot_leave_a_stale_passing_report(preflight, monkeypatch, tmp_path, capsys):(tmp_path / "preflight-report.json").write_text(json.dumps(STALE_PASS))- (tmp_path / ".iteration-count").write_text("3\n")- assert _run_main(preflight, monkeypatch, tmp_path, "--repair-attempt") == preflight.EXIT_ITERATION_CAP+ monkeypatch.setenv("CLAUDE_BLOG_REVIEW_STATE_DIR", str(tmp_path.parent / "state"))+ preflight._write_iteration_count(tmp_path, preflight._iteration_state_path(tmp_path), 3)+ assert _run_main(preflight, monkeypatch, tmp_path) == preflight.EXIT_ITERATION_CAPreport = json.loads((tmp_path / "preflight-report.json").read_text())assert report["blocked"] is True and report["incomplete"] is Trueassert "iteration cap" in report["reason"]@@ -554,7 +576,7 @@ def test_rendered_gate_accepts_a_second_json_ld_block(preflight, renderer, tmp_passert result["passed"], result["violations"]-def test_reset_iterations_help_matches_the_behaviour(preflight, tmp_path):+def test_reset_iterations_help_matches_the_behaviour(preflight, tmp_path, monkeypatch):import subprocesshelp_text = subprocess.run([sys.executable, str(ROOT / "scripts" / "blog_preflight.py"), "--help"],@@ -562,6 +584,12 @@ def test_reset_iterations_help_matches_the_behaviour(preflight, tmp_path):).stdoutflat = " ".join(help_text.split())assert "counter to 0" in flat- (tmp_path / ".iteration-count").write_text("2\n")- preflight._iteration_check(tmp_path, reset=True)- assert (tmp_path / ".iteration-count").read_text().strip() == "0"+ assert "starting a new write or rewrite" in flat+ monkeypatch.setenv("CLAUDE_BLOG_REVIEW_STATE_DIR", str(tmp_path / "state"))+ draft = tmp_path / "draft"+ draft.mkdir()+ counter = preflight._iteration_state_path(draft)+ preflight._write_iteration_count(draft, counter, 2)+ preflight._iteration_check(draft, reset=True)+ assert json.loads(counter.read_text())["runs"] == 0+ assert not (draft / ".iteration-count").exists()diff --git a/tests/test_preflight_wave3.py b/tests/test_preflight_wave3.pyindex 83bc957..042f0c0 100644--- a/tests/test_preflight_wave3.py+++ b/tests/test_preflight_wave3.py@@ -98,7 +98,10 @@ def _has(result, *needles):def _review(nonce: str) -> str:return (- "## Quality Review\n\n### Overall Score: 92/100\n\nzero P0 issues found\n\n"+ "## Quality Review\n\n### Overall Score: 92/100\n\n"+ "Content Quality: 28/30\nSEO Optimization: 23/25\nE-E-A-T Signals: 14/15\n"+ "Technical Elements: 14/15\nAI Citation Readiness: 13/15\n\n"+ "zero P0 issues found\n\n"f"Nonce: {nonce}\nBLOCKING: false (cleared all gates)\n")@@ -846,7 +849,7 @@ def test_a_crashed_run_leaves_an_incomplete_blocked_report(preflight, draft, monassert _run_main(preflight, monkeypatch, draft) == 0passing = json.loads((draft / "preflight-report.json").read_text(encoding="utf-8"))assert passing["blocked"] is False- monkeypatch.setattr(preflight, "_iteration_check", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")))+ monkeypatch.setattr(preflight, "_parse_tool_names", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")))with pytest.raises(RuntimeError):_run_main(preflight, monkeypatch, draft)report = json.loads((draft / "preflight-report.json").read_text(encoding="utf-8"))diff --git a/tests/test_review_nonce.py b/tests/test_review_nonce.pyindex b7e1607..5b74464 100644--- a/tests/test_review_nonce.py+++ b/tests/test_review_nonce.py@@ -174,6 +174,12 @@ def _passing_review(nonce: str) -> str:return ("## Quality Review: Fixture\n""### Overall Score: 92/100 - Exceptional\n"+ "| Category | Score | Max |\n"+ "| Content Quality | 28 | 30 |\n"+ "| SEO Optimization | 23 | 25 |\n"+ "| E-E-A-T Signals | 14 | 15 |\n"+ "| Technical Elements | 14 | 15 |\n"+ "| AI Citation Readiness | 13 | 15 |\n""### Editorial Style Diagnostics\n""These observations are advisory and do not infer authorship.\n""zero P0 issues found\n"diff --git a/tests/test_review_thresholds.py b/tests/test_review_thresholds.pyindex e13720b..3eaf2ce 100644--- a/tests/test_review_thresholds.py+++ b/tests/test_review_thresholds.py@@ -20,13 +20,18 @@ def test_configurable_quality_gate_boundaries(monkeypatch, score, threshold, pasassert gate.DEFAULT_THRESHOLD == 70assert gate.analyze_post("post.md", threshold)["passed"] is passed+def categories(score):+ """All five rubric categories, summing to ``score`` (Gate 4 requires them)."""+ return (f"Content Quality: {score - 63}/30\nSEO Optimization: 22/25\nE-E-A-T Signals: 14/15\n"+ "Technical Elements: 14/15\nAI Citation Readiness: 13/15\n")+@pytest.mark.parametrize("score,clearance,passed", [(89,"zero P0 issues",False),(90,"zero P0 issues",True),(90,"",False),(90,"zero P0 issues\nP0: unresolved fabricated statistic",False)])def test_delivery_score_and_explicit_p0_clearance(monkeypatch, tmp_path, score, clearance, passed):gate = load("boundary_preflight", "scripts/blog_preflight.py")monkeypatch.setenv("CLAUDE_BLOG_REVIEW_STATE_DIR", str(tmp_path / "state"))draft = tmp_path / "draft"; draft.mkdir()nonce = gate._init_review_nonce(draft)- (draft / "review.md").write_text(f"Overall Score: {score}/100\n{clearance}\nNonce: {nonce}\nBLOCKING: false (review decision)\n")+ (draft / "review.md").write_text(f"Overall Score: {score}/100\n{categories(score)}{clearance}\nNonce: {nonce}\nBLOCKING: false (review decision)\n")assert gate.gate_4_content_review(draft)["passed"] is passed@@ -40,7 +45,7 @@ def test_delivery_rejects_ambiguous_review_fields(monkeypatch, tmp_path, mutatiomonkeypatch.setenv("CLAUDE_BLOG_REVIEW_STATE_DIR", str(tmp_path / "state"))draft = tmp_path / "draft"; draft.mkdir()nonce = gate._init_review_nonce(draft)- review = f"Overall Score: 90/100\nzero P0 issues\nNonce: {nonce}\nBLOCKING: false (controlled review)\n"+ review = f"Overall Score: 90/100\n{categories(90)}zero P0 issues\nNonce: {nonce}\nBLOCKING: false (controlled review)\n"changes = {"negated-clearance": ("zero P0 issues", "There are not zero P0 issues."),"qualified-clearance": ("zero P0 issues", "zero P0 issues except an unresolved claim"),@@ -69,5 +74,5 @@ def test_delivery_accepts_affirmative_legacy_review_forms(monkeypatch, tmp_path,monkeypatch.setenv("CLAUDE_BLOG_REVIEW_STATE_DIR", str(tmp_path / "state"))draft = tmp_path / "draft"; draft.mkdir()nonce = gate._init_review_nonce(draft)- (draft / "review.md").write_text(f"Overall Score: 92/100\n{clearance}\nNonce: {nonce}\nBLOCKING: false ({reason})\n")+ (draft / "review.md").write_text(f"Overall Score: 92/100\n{categories(92)}{clearance}\nNonce: {nonce}\nBLOCKING: false ({reason})\n")assert gate.gate_4_content_review(draft)["passed"] is True