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(studio): make Blog Studio 0.2.0 work with the real engine (#102)
Agrici Danielc34368da5317
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 4e719ee..6268684 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -25,7 +25,7 @@ claude-blog/│ ├── blog-rewrite/│ └── ... # 31 sub-skill dirs: 30 user-facing + 1 internal├── agents/ # 5 specialized agents-├── scripts/ # 20 root-level Python helper scripts+├── scripts/ # 23 root-level Python helper scripts├── tests/ # pytest test suite (security guardrails + script tests)├── docs/ # Documentation (installation, commands, architecture, templates, troubleshooting, MCP)└── .github/workflows/ # CI pipelinediff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 014547b..78e3298 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -202,6 +202,35 @@ jobs:# or warning. See .github/scripts/validate_plugin_tolerate_reserved_name.py.run: python3 .github/scripts/validate_plugin_tolerate_reserved_name.py --root .+ blog-studio:+ # Offline checks for the optional plugins/blog-studio companion: validate+ # the manifest and run its hook fixtures. The job creates no session, loads+ # no mod and needs no sign-in or network beyond the dependency download.+ # The real engine contract it relies on is covered by+ # tests/test_blog_studio_integration.py in the test job. The reference+ # type check (npm run typecheck:reference) is not run here yet: it reports+ # 3 errors in hooks/view.ts against the 2.1.277 reference typings.+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1, SHA-pinned+ with:+ persist-credentials: false++ - name: Set up Node.js 22+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0, SHA-pinned+ with:+ node-version: "22"++ - name: Install the pinned Claude Code test kit+ run: npm install --global --no-audit --no-fund @anthropic-ai/[email protected]++ - name: Validate the companion without loading it+ run: claude plugin validate --strict --json plugins/blog-studio++ - name: Run the offline hook and drawing fixtures+ run: claude plugin test plugins/blog-studio+lint-markdown:runs-on: ubuntu-lateststeps:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13cf169..34c3851 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- Make Blog Studio 0.2.0 work with the real engine (#102). The plugin called a status script and a preflight flag that did not exist, so it could never show a passing result. `scripts/blog_studio_status.py` is new (read-only; prints the status JSON the plugin parses, with `--draft`, `--project-root` and `--expected-run`). `scripts/blog_preflight.py` gains `--project-root` and writes an additive `evidence` object (including a 32-hex `run_id`) into `preflight-report.json`. Stdout modes, other flags and exit codes are unchanged, and the report `draft` field keeps the path as given under `--project-root`. An unfinished or iteration-capped run shows as Blocked, never as passed or stale.+- Add `tests/test_blog_studio.py` and `tests/test_blog_studio_integration.py`, which run the real scripts the way the plugin does and mirror its response parser, plus a `blog-studio` CI job (strict plugin validation and the 59 test-kit tests on a pinned Claude Code release). The companion's reference type check still reports 3 errors in `hooks/view.ts`, so CI does not run it yet.+- Extend `scripts/consistency_check.py` and `scripts/validate_public_release.py` to cover `plugins/` (the studio version must match its marketplace entry), and correct the script, reference and screenshot counts in the docs, the `installer_ownership.py` release note and the `/blog style` and `/blog decay` command sections.++Other fixes in this release are listed below by their owners.+### Changed- Turn off Dependabot version-update PRs (`open-pull-requests-limit: 0`). Hash-locked pip bumps need a maintainer relock, so the PRs only added notifications. Vulnerability alerts stay on.diff --git a/CLAUDE.md b/CLAUDE.mdindex ee200d3..b802052 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -30,6 +30,7 @@ claude-blog/brain/ # Vendored self-contained evidence-gated Obsidian brain; not plugin payload; tooling stays under skills/scripts/analyze_blog.py # 5-category quality scoring (stdlib)scripts/blog_preflight.py # 5-gate delivery contract runner (v1.9.0)+ scripts/blog_studio_status.py # Read-only preflight evidence inspector for the optional blog-studio pluginscripts/blog_render.py # md -> html -> pdf renderer; XSS-safe JSON-LD (v1.9.0)scripts/blog_hygiene.py # Optional deterministic hygiene: lazy-load imgs + auto-TOC (v1.11.0)scripts/cognitive_load.py # Per-section concept-density analyzer (v1.8.0)@@ -50,12 +51,14 @@ claude-blog/scripts/check_google_currentness.py # Google update ledger vs official feedsscripts/sync_google_updates.py # Google update ledger sync into the Blog Brainscripts/installer_ownership.py # Shared Unix installer ownership engine- # 22 scripts/*.py in total: `ls scripts/*.py | wc -l`+ # 23 scripts/*.py in total: `ls scripts/*.py | wc -l`skills/ # 32 skill directories (1 orchestrator + 31 sub-skills)blog/SKILL.md # Main orchestrator, routing, scoringreferences/ # 22 on-demand knowledge files (5 in v1.8.0, 1 in v1.9.0)templates/ # 12 content templates- blog-write/SKILL.md # Write new articles from scratch+ blog-write/ # Write new articles from scratch+ SKILL.md+ references/ # 2 reference docs (delivery, drafting)blog-rewrite/SKILL.md # Optimize existing blog postsblog-analyze/SKILL.md # 5-category 100-point scoringblog-brief/SKILL.md # Detailed content briefsdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 139aa7d..a7f289b 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -53,7 +53,7 @@ The Claude Blog Brain is vendored at `./brain` as a self-contained, evidence-gat| |v v+------------------+ +------------------------+-| 5 Subagents | | 22 root-level Scripts |+| 5 Subagents | | 23 root-level Scripts || agents/*.md | | scripts/*.py || | | || blog-researcher | | analyze_blog |@@ -189,11 +189,11 @@ Structural templates for different content types. Each template definessection structure, word count targets, and format-specific guidance.See [TEMPLATES.md](TEMPLATES.md) for the full reference.-### 6. Root-Level Python Scripts (22)+### 6. Root-Level Python Scripts (23)**Location**: `scripts/*.py`-Twenty-two Python helpers live at the repository root (count them with+Twenty-three Python helpers live at the repository root (count them with`ls scripts/*.py | wc -l`; `scripts/windows_installer_ownership.ps1` is thePowerShell twin of the ownership engine and is not counted). They support theorchestrator, the delivery contract, the installers and the CI checks.@@ -207,6 +207,7 @@ dependencies are stdlib-only or narrowly pinned.| `blog_hygiene.py` | Optional deterministic hygiene: lazy-load images and auto-TOC | v1.11.0 || `blog_preflight.py` | Runs the 5-gate Blog Delivery Contract (Gates 1, 2, 3, 5 plus the Gate 4 nonce and digest checks); `--init-review-nonce` issues the review nonce | v1.9.0 || `blog_render.py` | md -> html -> pdf renderer; XSS-safe JSON-LD via `</`->`<\/`; O_NOFOLLOW symlink refusal; frontmatter validation; embeds `blog-source-sha256`; refuses `.html` input | v1.9.0 |+| `blog_studio_status.py` | Read-only inspector for the saved preflight report's `evidence` object; prints the status JSON the optional Blog Studio plugin displays (`--draft`, `--project-root`, `--expected-run`) | Unreleased || `check_google_currentness.py` | Checks the reviewed Google update ledger against official machine-readable feeds | Maintenance || `check_secrets.py` | Fails on unadjudicated detect-secrets findings without printing raw values | Maintenance || `cognitive_load.py` | Per-section concept-density analyzer (entities, numerics, jargon, forward refs, clause depth) | v1.8.0 |diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.mdindex dbf8ae8..93fdff9 100644--- a/docs/INSTALLATION.md+++ b/docs/INSTALLATION.md@@ -420,7 +420,7 @@ chmod +x uninstall.shThe uninstaller removes verified package-owned files from:- `~/.claude/skills/blog/` and `~/.claude/skills/blog-*/` (32 skill directories: 1 orchestrator + 31 sub-skills; 30 user-facing commands; `blog-chart` is internal-only)-- `~/.claude/scripts/` (the root `scripts/*.py` helpers, 22 at the time of writing, including the shared `installer_ownership.py` engine)+- `~/.claude/scripts/` (the root `scripts/*.py` helpers, 23 at the time of writing, including the shared `installer_ownership.py` engine)- `~/.claude/agents/blog-*.md` (all 5 agents: blog-researcher, blog-writer, blog-seo, blog-reviewer, blog-translator)Shared Google credentials under `~/.config/claude-seo/` are owned by the userdiff --git a/plugins/blog-studio/README.md b/plugins/blog-studio/README.mdindex e500a87..e4ba820 100644--- a/plugins/blog-studio/README.md+++ b/plugins/blog-studio/README.md@@ -20,7 +20,7 @@ loads until you install it.Blog Studio is a Claude Code mod (function-hook plugin), so it needs a Claude Coderelease with mods support. It was developed and checked on the Linux CLI,-2.1.294 to 2.1.296. The panel uses host theme colors and the shared+2.1.294 to 2.1.296, and re-run (strict validation and the 59 test-kit tests) on 2.1.312. The panel uses host theme colors and the sharedterminal/Desktop element set. Desktop fixture tests do not establish nativeDesktop support. Codex does not run Claude Code mods.diff --git a/scripts/blog_preflight.py b/scripts/blog_preflight.pyindex d9cd28b..7ed1307 100644--- a/scripts/blog_preflight.py+++ b/scripts/blog_preflight.py@@ -24,6 +24,7 @@ Exit codes: 0 = all gates passed; 1 = at least one gate blockedfrom __future__ import annotationsimport argparse+import contextlibimport datetime as dtimport hashlibimport ipaddress@@ -38,10 +39,20 @@ import tempfileimport urllib.errorimport urllib.parseimport urllib.request+import uuidfrom html.parser import HTMLParserfrom pathlib import Pathfrom typing import Any, Optional+# The sibling module must load under `python3 -I` too, which drops the script+# directory from sys.path.+sys.path.insert(0, str(Path(__file__).resolve().parent))+try: # Optional: evidence and --project-root need the Blog Studio inspector module.+ from blog_studio_status import anchored_draft as _anchored_draft+ from blog_studio_status import capture_inputs, capture_outputs, engine_identity+except ImportError: # pragma: no cover - exercised by a test that blocks the import+ _anchored_draft = capture_inputs = capture_outputs = engine_identity = None+def _project_version() -> str:"""Read the package version from pyproject.toml."""@@ -3069,7 +3080,7 @@ GATE_NAMES = {}-def _incomplete_report(draft: Path, strict: bool, reason: str) -> dict[str, Any]:+def _incomplete_report(draft: Path | str, strict: bool, reason: str) -> dict[str, Any]:"""Blocked placeholder report written before any gate runs."""return {"draft": str(draft),@@ -3101,6 +3112,10 @@ def _previous_report_gates(report_path: Path) -> list[Any]:def main() -> int:parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])parser.add_argument("--draft", required=True, help="Draft folder containing the .md/.html/.pdf/hero artifacts")+ parser.add_argument(+ "--project-root",+ help="Anchor execution inside this project directory (Unix only); the report then records the draft path as given",+ )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")parser.add_argument("--strict", dest="strict", action="store_true", default=True)@@ -3126,11 +3141,27 @@ def main() -> int:)args = parser.parse_args()+ if args.project_root is not None:+ if _anchored_draft is None:+ print("ERROR: --project-root needs scripts/blog_studio_status.py next to this script", file=sys.stderr)+ return 1+ with contextlib.ExitStack() as stack:+ try:+ draft, identity = stack.enter_context(_anchored_draft(args.draft, args.project_root))+ except (OSError, ValueError) as exc:+ print(f"ERROR: project-contained preflight refused: {exc}", file=sys.stderr)+ return 1+ return _run_preflight(args, draft, identity)+draft = Path(args.draft).resolve()if not draft.is_dir():print(f"ERROR: {draft} is not a directory", file=sys.stderr)return 1+ return _run_preflight(args, draft, str(draft))++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.init_review_nonce:nonce = _init_review_nonce(draft)print(nonce)@@ -3141,7 +3172,7 @@ def main() -> int:report_path = draft / "preflight-report.json"previous_gates = _previous_report_gates(report_path)try:- started = _incomplete_report(draft, args.strict, "run started and has not finished")+ started = _incomplete_report(draft_identity, args.strict, "run started and has not finished")if previous_gates:# Crash safety must not erase the last diagnostic.started["previous_gates"] = previous_gates@@ -3160,7 +3191,7 @@ def main() -> int:# 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, args.strict,+ draft_identity, args.strict,"iteration cap exceeded; the last complete run's gates are in previous_gates",)capped["iteration_cap_exceeded"] = True@@ -3195,6 +3226,9 @@ def main() -> int:results: list[dict] = []blocked = False+ started_at = dt.datetime.now(dt.timezone.utc).isoformat()+ evidence_engine = engine_identity() if engine_identity else None+ inputs_before = capture_inputs(draft, _review_state_path(draft)) if capture_inputs else Nonefor n, fn in gates:try:r = fn(draft)@@ -3207,11 +3241,28 @@ def main() -> int:breakreport = {- "draft": str(draft),+ "draft": draft_identity,"strict": args.strict,"blocked": blocked,"gates": results,}+ if inputs_before is not None:+ # Additive freshness evidence for Blog Studio. Fingerprints show what+ # was checked; they are not an approval and add no new gate.+ inputs_after = capture_inputs(draft, _review_state_path(draft))+ report["evidence"] = {+ "schema_version": 1,+ "run_id": uuid.uuid4().hex,+ "contract_version": CONTRACT_VERSION,+ "engine": evidence_engine,+ "started_at": started_at,+ "finished_at": dt.datetime.now(dt.timezone.utc).isoformat(),+ "requested_gates": [n for n, _fn in gates],+ "completed_gates": [r["gate"] for r in results],+ "inputs": inputs_before,+ "inputs_unchanged": not inputs_before["errors"] and inputs_before == inputs_after,+ "outputs": capture_outputs(draft),+ }try:_atomic_write_json(draft / "preflight-report.json", report, indent=2)except (OSError, ValueError) as e:diff --git a/scripts/blog_studio_status.py b/scripts/blog_studio_status.pynew file mode 100644index 0000000..3cc7827--- /dev/null+++ b/scripts/blog_studio_status.py@@ -0,0 +1,409 @@+#!/usr/bin/env python3+"""Inspect saved preflight evidence without rendering, network calls or writes.++Fingerprints describe the files checked, not authenticated approval. The+preflight remains the delivery authority. Legacy reports have unknown freshness.++Usage:+ python3 scripts/blog_studio_status.py --draft <dir> [--project-root <root>]+ [--expected-run <32-hex run id>]++Reads <draft>/preflight-report.json (written by blog_preflight.py) and prints+one JSON object on stdout: schema_version, status (passed, blocked, partial,+stale, unverified or error), passed_count, gates, artifacts, diagnostics,+checked_at and, once the report carries evidence, run_id. Exit status is 1 only+for status "error", otherwise 0. With --project-root the inspection is anchored+inside that project and refuses symlinked or traversing draft paths. With+--expected-run a report from any other run is an error. The same module also+supplies the fingerprint helpers blog_preflight.py uses to write the report's+additive "evidence" object (see skills/blog/references/blog-delivery-contract.md).+"""+from __future__ import annotations++import argparse+from contextlib import contextmanager+import datetime as dt+import hashlib+import json+import math+import os+import re+import stat+import sys+from pathlib import Path+from typing import Any++# blog_preflight is imported lazily from this directory, also under `python3 -I`.+sys.path.insert(0, str(Path(__file__).resolve().parent))++EVIDENCE_VERSION = 1+MAX_REPORT_BYTES = 1024 * 1024+MAX_FILES = 4096+MAX_INPUT_BYTES = 512 * 1024 * 1024+EXCLUDED_FILES = {"preflight-report.json", "capabilities.json", ".iteration-count"}+SCREENSHOTS = {"preview/mobile-375.png", "preview/tablet-768.png",+ "preview/desktop-1280.png", "preview/desktop-1280-dark.png"}+LABELS = {+ "passed": "Preflight passed", "blocked": "Blocked", "partial": "Partial",+ "stale": "Stale", "unverified": "Unverified", "error": "Execution error",+}+++@contextmanager+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.+ """+ 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()+ selected = Path(draft_name).absolute()+ selected.relative_to(project)+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW+ previous = os.open(".", flags)+ current = -1+ try:+ current = os.open("/", flags)+ for component in selected.parts[1:]:+ child = os.open(component, flags, dir_fd=current)+ os.close(current)+ current = child+ expected, actual = os.stat(selected, 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)+ yield Path("."), str(selected)+ finally:+ os.fchdir(previous)+ os.close(previous)+ if current >= 0:+ os.close(current)++++def safe_text(value: str, limit: int = 500) -> str:+ """Bound diagnostic text and suppress terminal control codes and nonces."""+ value = re.sub(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|$))", "", value)+ value = re.sub(r"\b[0-9a-fA-F]{32}\b", "[redacted identifier]", value)+ return "".join(c for c in value if c.isprintable() or c == "\n")[:limit]+++def _open_no_follow(path: Path, flags: int) -> int:+ """Open through anchored parent descriptors on the Linux target."""+ if os.open not in os.supports_dir_fd or not hasattr(os, "O_NOFOLLOW"):+ return os.open(path, flags)+ parts = path.parts[1:] if path.is_absolute() else path.parts+ if ".." in parts:+ raise ValueError("fingerprint traversal is refused")+ directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW+ parent = os.open("/" if path.is_absolute() else ".", directory_flags)+ try:+ for component in parts[:-1]:+ child = os.open(component, directory_flags, dir_fd=parent)+ os.close(parent)+ parent = child+ return os.open(parts[-1] if parts else ".", flags, dir_fd=parent)+ finally:+ os.close(parent)+++def _entries(directory: Path) -> list[tuple[Path, int]]:+ if os.stat not in os.supports_dir_fd or not hasattr(os, "O_DIRECTORY"):+ return [(path, path.lstat().st_mode) for path in sorted(directory.iterdir())]+ fd = _open_no_follow(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)+ try:+ names = sorted(os.listdir(fd))+ if len(names) > MAX_FILES:+ raise ValueError("fingerprint directory entry limit exceeded")+ return [(directory / name, os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode) for name in names]+ finally:+ os.close(fd)+++def _file_hash(path: Path, budget: int = MAX_INPUT_BYTES) -> dict[str, Any]:+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)+ fd = _open_no_follow(path, flags)+ with os.fdopen(fd, "rb") as stream:+ before = os.fstat(stream.fileno())+ if not stat.S_ISREG(before.st_mode) or before.st_size > budget:+ raise ValueError("not a regular file or fingerprint byte limit exceeded")+ digest = hashlib.sha256()+ total = 0+ while chunk := stream.read(min(1024 * 1024, budget - total + 1)):+ total += len(chunk)+ if total > budget:+ raise ValueError("fingerprint byte limit exceeded")+ digest.update(chunk)+ after = os.fstat(stream.fileno())+ if (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (+ after.st_size, after.st_mtime_ns, after.st_ctime_ns+ ):+ raise ValueError("file changed during fingerprinting")+ return {"sha256": digest.hexdigest(), "size": total}+++def _optional_hash(path: Path) -> dict[str, Any] | None:+ try:+ return _file_hash(path)+ except FileNotFoundError:+ return None+++def capture_inputs(draft: Path, review_state_path: Path) -> dict[str, Any]:+ """Conservatively fingerprint the bounded draft tree and verifier state.++ All regular files are inputs except known preflight outputs. This includes+ local styles, fonts, images and scripts whose browser use is dynamic.+ Symlinks and unsupported file types make freshness unverified.+ """+ files: dict[str, Any] = {}+ errors: list[str] = []+ total = 0+ try:+ pending = [draft]+ while pending:+ directory = pending.pop()+ if directory.is_symlink():+ raise ValueError("symlink directory in draft")+ for path, mode in _entries(directory):+ relative = path.relative_to(draft).as_posix()+ if relative in SCREENSHOTS or relative in EXCLUDED_FILES:+ continue+ # Atomic preflight temporary files are outputs, not inputs.+ if path.parent == draft and path.name.startswith((".preflight-report.json.", ".capabilities.json.", ".iteration-count.")):+ continue+ if any(path.parent == draft / "preview" and path.name.startswith("." + Path(name).name + ".")+ for name in SCREENSHOTS):+ continue+ if stat.S_ISLNK(mode):+ raise ValueError("symlink in draft: " + relative)+ if stat.S_ISDIR(mode):+ pending.append(path)+ elif stat.S_ISREG(mode):+ if len(files) >= MAX_FILES:+ raise ValueError("fingerprint file limit exceeded")+ value = _file_hash(path, MAX_INPUT_BYTES - total)+ files[relative] = value+ total += value["size"]+ else:+ raise ValueError("unsupported file type: " + relative)+ verifier = _optional_hash(review_state_path)+ except (OSError, ValueError) as exc:+ errors.append(safe_text(str(exc)))+ verifier = None+ return {"files": files, "review_state": verifier, "errors": errors}+++def capture_outputs(draft: Path) -> dict[str, Any]:+ files: dict[str, Any] = {}+ errors: list[str] = []+ try:+ if (draft / "preview").is_symlink():+ raise ValueError("preview is a symlink")+ paths = [draft / "capabilities.json", *(draft / name for name in sorted(SCREENSHOTS))]+ total = 0+ for path in paths:+ if not path.exists() and not path.is_symlink():+ continue+ if len(files) >= MAX_FILES or path.is_symlink():+ raise ValueError("unsafe or excessive generated outputs")+ value = _file_hash(path, MAX_INPUT_BYTES - total)+ files[path.relative_to(draft).as_posix()] = value+ total += value["size"]+ except (OSError, ValueError) as exc:+ errors.append(safe_text(str(exc)))+ return {"files": files, "errors": errors}+++def engine_identity() -> dict[str, Any]:+ scripts = Path(__file__).resolve().parent+ files = {}+ errors = []+ for name in ("blog_preflight.py", "blog_studio_status.py"):+ try:+ files[name] = _file_hash(scripts / name)+ except (OSError, ValueError):+ errors.append("Engine fingerprint unavailable: " + name)+ for name in ("skills/blog/references/blog-delivery-contract.md", "agents/blog-reviewer.md"):+ try:+ files[name] = _file_hash(scripts.parent / name)+ except (OSError, ValueError):+ errors.append("Contract fingerprint unavailable: " + name)+ return {"files": files, "python": list(sys.version_info[:3]), "errors": errors}+++def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise ValueError("duplicate JSON field")+ result[key] = value+ return result+++def load_report(path: Path) -> dict[str, Any]:+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)+ fd = _open_no_follow(path, flags)+ with os.fdopen(fd, "rb") as stream:+ info = os.fstat(stream.fileno())+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_REPORT_BYTES:+ raise ValueError("report must be a regular file within the size limit")+ data = stream.read(MAX_REPORT_BYTES + 1)+ if len(data) > MAX_REPORT_BYTES:+ raise ValueError("report exceeds size limit")+ result = json.loads(data.decode("utf-8"), object_pairs_hook=_unique_object)+ if not isinstance(result, dict):+ raise ValueError("report must be an object")+ return result+++def _validate_report(report: dict[str, Any]) -> list[dict[str, Any]]:+ if type(report.get("strict")) is not bool or type(report.get("blocked")) is not bool:+ raise ValueError("report strict/blocked must be booleans")+ gates = report.get("gates")+ if not isinstance(gates, list) or not 1 <= len(gates) <= 5:+ raise ValueError("report requires one to five gates")+ seen = set()+ for gate in gates:+ if not isinstance(gate, dict) or type(gate.get("gate")) is not int:+ raise ValueError("invalid gate")+ number = gate["gate"]+ if number not in range(1, 6) or number in seen or type(gate.get("passed")) is not bool:+ raise ValueError("invalid, duplicate or nonboolean gate")+ seen.add(number)+ for key in ("violations", "warnings"):+ value = gate.get(key, [])+ if not isinstance(value, list) or len(value) > 200 or not all(isinstance(v, str) for v in value):+ raise ValueError("invalid gate diagnostics")+ if not isinstance(gate.get("name"), str):+ raise ValueError("invalid gate name")+ if gate["passed"] and gate.get("violations"):+ raise ValueError("passing gate contains violations")+ score = gate.get("score")+ if score is not None and (type(score) not in (int, float) or not math.isfinite(score) or not 0 <= score <= 100):+ raise ValueError("invalid reviewer score")+ if number == 4 and gate["passed"] and (score is None or score < 90):+ raise ValueError("passing content review contradicts the delivery threshold")+ if report["blocked"] != any(not g["passed"] for g in gates):+ raise ValueError("report blocked flag contradicts gate results")+ return gates+++def inspect_status(draft: Path, project_root: Path | None = None, expected_run: str | None = None) -> dict[str, Any]:+ if project_root is None:+ return _inspect_status(draft, expected_run)+ try:+ with anchored_draft(str(draft), str(project_root)) as (anchored, identity):+ return _inspect_status(anchored, expected_run, identity)+ except (OSError, ValueError) as exc:+ status = "unverified" if isinstance(exc, FileNotFoundError) else "error"+ return {"schema_version": 1, "status": status, "label": LABELS[status],+ "checked_at": None, "passed_count": 0, "gates": [], "artifacts": [],+ "diagnostics": [safe_text("Project-contained inspection refused: " + str(exc))]}+++def _inspect_status(draft: Path, expected_run: str | None = None, draft_identity: str | None = None) -> dict[str, Any]:+ result: dict[str, Any] = {"schema_version": 1, "status": "unverified", "label": LABELS["unverified"],+ "checked_at": None, "passed_count": 0, "gates": [], "artifacts": [], "diagnostics": []}+ def finish(status: str, message: str | None = None) -> dict[str, Any]:+ result.update(status=status, label=LABELS[status])+ if message:+ result["diagnostics"].append(safe_text(message))+ return result+ try:+ if draft.is_symlink() or not draft.is_dir():+ raise ValueError("draft must be a regular directory")+ if draft_identity is None:+ draft = draft.resolve()+ draft_identity = str(draft)+ report = load_report(draft / "preflight-report.json")+ if report.get("draft") != draft_identity:+ raise ValueError("report belongs to a different draft")+ if report.get("incomplete") is True:+ # Start marker or iteration-cap record: no current gate results.+ return finish("blocked", "Preflight did not finish: " + str(report.get("reason", "run incomplete")))+ gates = _validate_report(report)+ result["passed_count"] = sum(g["passed"] for g in gates)+ result["gates"] = [{"gate": g["gate"], "name": safe_text(g["name"]), "passed": g["passed"],+ "violations": [safe_text(v) for v in g.get("violations", [])],+ "warnings": [safe_text(v) for v in g.get("warnings", [])],+ "score": g.get("score") if type(g.get("score")) in (int, float) else None} for g in gates]+ evidence = report.get("evidence")+ if not isinstance(evidence, dict) or evidence.get("schema_version") != EVIDENCE_VERSION:+ return finish("unverified", "Saved report has no supported freshness evidence. Run checks.")+ run_id = evidence.get("run_id")+ if not isinstance(run_id, str) or not re.fullmatch(r"[0-9a-f]{32}", run_id):+ raise ValueError("invalid run identity")+ if expected_run is not None and run_id != expected_run:+ return finish("error", "Saved report does not match this check run.")+ result["run_id"] = run_id+ for key in ("started_at", "finished_at"):+ stamp = dt.datetime.fromisoformat(evidence[key])+ if stamp.tzinfo is None or stamp.utcoffset() != dt.timedelta(0):+ raise ValueError("evidence timestamps must use UTC")+ if dt.datetime.fromisoformat(evidence["started_at"]) > dt.datetime.fromisoformat(evidence["finished_at"]):+ raise ValueError("invalid check timestamps")+ if evidence.get("contract_version") != blog_contract_version():+ return finish("stale", "Delivery contract version changed since the check.")+ result["checked_at"] = evidence["finished_at"]+ completed = [g["gate"] for g in gates]+ requested = evidence.get("requested_gates")+ if (evidence.get("completed_gates") != completed or not isinstance(requested, list)+ or not requested or any(type(n) is not int or n not in range(1, 6) for n in requested)+ or len(set(requested)) != len(requested) or completed != requested[:len(completed)]):+ raise ValueError("evidence gate scope contradicts results")+ # Import the canonical nonce-state locator without running any gates.+ import blog_preflight+ current = capture_inputs(draft, blog_preflight._review_state_path(draft))+ current_engine = engine_identity()+ if current_engine["errors"]:+ return finish("unverified", "Engine identity could not be established.")+ if evidence.get("engine") != current_engine:+ return finish("stale", "Engine or Python runtime changed since the check.")+ if current["errors"] or evidence.get("inputs", {}).get("errors") or evidence.get("outputs", {}).get("errors"):+ return finish("unverified", "Freshness could not be established for all files.")+ if evidence.get("inputs_unchanged") is not True or current != evidence.get("inputs"):+ return finish("stale", "Article inputs or review verifier state changed. Run checks again.")+ if capture_outputs(draft) != evidence.get("outputs"):+ return finish("stale", "Generated verification artifacts changed or are missing.")+ result["artifacts"] = [safe_text(p, 1000) for p in sorted(current["files"])] + [safe_text(p, 1000) for p in sorted(evidence["outputs"]["files"])]+ if not report["strict"]:+ return finish("unverified", "Preview mode cannot establish strict preflight success.")+ if report["blocked"]:+ return finish("blocked")+ if evidence["requested_gates"] != [1, 2, 3, 4, 5] or completed != [1, 2, 3, 4, 5]:+ return finish("partial", "Only part of the delivery contract was checked.")+ return finish("passed")+ except FileNotFoundError:+ return finish("unverified", "No saved report or selected draft is available. Run checks.")+ except ImportError as exc:+ return finish("error", "Engine module unavailable: " + str(exc))+ except (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError) as exc:+ return finish("error", "Invalid evidence: " + str(exc))+++def blog_contract_version() -> str:+ import blog_preflight+ return blog_preflight.CONTRACT_VERSION+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--draft", type=Path, required=True)+ parser.add_argument("--project-root", type=Path)+ parser.add_argument("--expected-run")+ args = parser.parse_args()+ result = inspect_status(args.draft, args.project_root, args.expected_run)+ print(json.dumps(result, allow_nan=False))+ return 1 if result["status"] == "error" else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/consistency_check.py b/scripts/consistency_check.pyindex a359468..b0f1518 100644--- a/scripts/consistency_check.py+++ b/scripts/consistency_check.py@@ -16,7 +16,9 @@ import sysfrom pathlib import Pathfrom urllib.parse import unquote-SCANNED_ROOTS = ("docs", "skills", "agents", ".github")+SCANNED_ROOTS = ("docs", "skills", "agents", ".github", "plugins")+# Vendored or generated trees below plugins/ that are not project documentation.+SKIPPED_PARTS = {"node_modules", ".reference-types"}RESOURCE_ROOTS = ("docs", "skills", "agents", "scripts")EXPLICIT_PATH_RE = re.compile(r"`((?:skills|agents|scripts|docs)/[A-Za-z0-9_./-]+)`"@@ -45,7 +47,11 @@ def _markdown_sources(root: Path) -> list[Path]:for directory in SCANNED_ROOTS:base = root / directoryif base.is_dir():- sources.extend(base.rglob("*.md"))+ sources.extend(+ path for path in base.rglob("*.md")+ if not SKIPPED_PARTS & set(path.parts)+ and ".claude-plugin/types/" not in path.as_posix()+ )return sorted({path for path in sources if path.is_file()})diff --git a/scripts/validate_public_release.py b/scripts/validate_public_release.pyindex 3ebf46d..8e3e931 100644--- a/scripts/validate_public_release.py+++ b/scripts/validate_public_release.py@@ -116,11 +116,17 @@ def validate(root: Path) -> dict:"agents": ("*.md",),"scripts": ("*.py", "*.ps1"),"data": ("*.json",),+ "plugins": ("*.md", "*.ts", "*.mjs", "*.json"),".github/workflows": ("*.yml", "*.yaml"),}.items():for pattern in patterns:for path in (root / directory).rglob(pattern):- if path.is_symlink() or any(part in {".venv", "__pycache__"} for part in path.parts):+ if path.is_symlink() or any(+ part in {".venv", "__pycache__", "node_modules", ".reference-types"}+ for part in path.parts+ ):+ continue+ if ".claude-plugin/types/" in path.as_posix():continuerelative = path.relative_to(root).as_posix()contents.setdefault(relative, path.read_text(encoding="utf-8"))@@ -343,9 +349,13 @@ def validate(root: Path) -> dict:)marketplace_text = contents.get(".claude-plugin/marketplace.json", "")+ marketplace: dict = {}try:marketplace = json.loads(marketplace_text)- except json.JSONDecodeError:+ if not isinstance(marketplace, dict):+ raise ValueError("marketplace must be an object")+ except ValueError: # JSONDecodeError is a ValueError+ marketplace = {}errors.append({"kind": "invalid_json", "file": ".claude-plugin/marketplace.json"})@@ -386,6 +396,35 @@ def validate(root: Path) -> dict:})+ # The optional Blog Studio companion versions independently of claude-blog:+ # the manifest, its marketplace entry and the repository must agree.+ studio_manifest = root / "plugins/blog-studio/.claude-plugin/plugin.json"+ entries = marketplace.get("plugins")+ studio_entries = [+ entry for entry in entries+ if isinstance(entry, dict) and entry.get("name") == "blog-studio"+ ] if isinstance(entries, list) else []+ if studio_manifest.exists() or studio_entries:+ try:+ studio = json.loads(studio_manifest.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ studio = None+ if (+ not isinstance(studio, dict)+ or studio.get("name") != "blog-studio"+ or not isinstance(studio.get("version"), str)+ or studio.get("repository") != PUBLIC_REPOSITORY+ or len(studio_entries) != 1+ or studio_entries[0].get("source") != "./plugins/blog-studio"+ or studio_entries[0].get("version") != studio.get("version")+ ):+ errors.append(+ {+ "kind": "invalid_studio_distribution",+ "file": "plugins/blog-studio/.claude-plugin/plugin.json",+ }+ )+return {"status": "pass" if not errors else "fail","root": str(root),diff --git a/skills/blog/references/blog-delivery-contract.md b/skills/blog/references/blog-delivery-contract.mdindex 43f87d1..740fb66 100644--- a/skills/blog/references/blog-delivery-contract.md+++ b/skills/blog/references/blog-delivery-contract.md@@ -318,3 +318,16 @@ Category lines use the fixed rubric maxima (30, 25, 15, 15, 15) and the overallequals the sum of the five category scores; Gate 4 rejects a card whose numbersdisagree. See the draft-stage rule in `quality-scoring.md` for items a draftcannot evidence.++## Optional status companion++Blog Studio reads the additive `evidence` object in `preflight-report.json`+(`schema_version`, `run_id`, `contract_version`, `engine`, `started_at`,+`finished_at`, `requested_gates`, `completed_gates`, `inputs`, `inputs_unchanged`,+`outputs`). The `scripts/blog_studio_status.py` inspector checks run scope and+local fingerprints without executing gates. Missing, legacy, partial or stale+evidence cannot establish full preflight success. Fingerprints describe+freshness, not authenticated approval. The five gates and the reviewer remain+the delivery authority. Manual checks do not reset nonces or consume repair+iterations. Run `blog_preflight.py --project-root <dir>` to anchor a run inside+a project; stdout modes, other flags and exit codes are unchanged.diff --git a/tests/test_blog_studio.py b/tests/test_blog_studio.pynew file mode 100644index 0000000..37e9f03--- /dev/null+++ b/tests/test_blog_studio.py@@ -0,0 +1,385 @@+"""Saved evidence is complete, scoped and fresh before Studio displays success.++Unit tests here patch the gates. The real CLI contract the Blog Studio plugin+relies on is covered end to end in test_blog_studio_integration.py.+"""+from __future__ import annotations++import json+import os+import sys+from pathlib import Path++import pytest+import blog_preflight as preflight+import blog_studio_status as studio+++def draft(tmp_path, monkeypatch):+ root = tmp_path / 'project'+ root.mkdir()+ folder = root / 'article'+ folder.mkdir()+ for name in ('article.md', 'article.html', 'article.pdf', 'hero.webp', 'review.md', 'style.css'):+ (folder / name).write_text('fixture ' + name)+ monkeypatch.setenv(preflight.REVIEW_STATE_ENV, str(tmp_path / 'verifier'))+ preflight._init_review_nonce(folder)+ return folder+++def run(draft, monkeypatch, *, gate=None, blocked=None, preview=False, mutate=False, mutate_name='article.md', project_root=None):+ def result(n):+ def check(_draft, **_kwargs):+ if mutate and n == 3:+ (_draft / mutate_name).write_text('changed during checks')+ if n == 1:+ (_draft / 'capabilities.json').write_text('{}')+ if n == 3:+ (_draft / 'preview').mkdir(exist_ok=True)+ (_draft / 'preview/desktop-1280.png').write_bytes(b'fixture screenshot')+ kwargs = {'score': 90} if n == 4 else {}+ return preflight._gate_result(n, 'Fixture gate', blocked != n,+ ['fixture blocker'] if blocked == n else [], **kwargs)+ return check+ for n, name in enumerate(('gate_1_capability_discovery', 'gate_2_format_completeness',+ 'gate_3_visual_verification', 'gate_4_content_review', 'gate_5_asset_link_integrity'), 1):+ monkeypatch.setattr(preflight, name, result(n))+ args = ['blog_preflight.py', '--draft', str(draft), '--json']+ if gate: args.extend(['--gate', str(gate)])+ if preview: args.append('--no-strict')+ if project_root: args.extend(['--project-root', str(project_root)])+ monkeypatch.setattr(sys, 'argv', args)+ code = preflight.main()+ return code, json.loads((draft / 'preflight-report.json').read_text())+++def test_full_strict_run_has_complete_evidence(draft, monkeypatch):+ code, report = run(draft, monkeypatch)+ assert code == 0+ assert report['strict'] is True and report['blocked'] is False+ assert report['evidence']['requested_gates'] == [1, 2, 3, 4, 5]+ assert report['evidence']['completed_gates'] == [1, 2, 3, 4, 5]+ assert report['evidence']['inputs_unchanged'] is True+ assert set(report['evidence']['inputs']['files']) == {'article.md', 'article.html', 'article.pdf', 'hero.webp', 'review.md', 'style.css'}+ assert set(report['evidence']['outputs']['files']) == {'capabilities.json', 'preview/desktop-1280.png'}+ status = studio.inspect_status(draft, draft.parent, report['evidence']['run_id'])+ assert status['status'] == 'passed'+ assert status['passed_count'] == 5+ assert 'nonce' not in json.dumps(status).lower()++[email protected]('gate', [1, 2, 3, 4, 5])+def test_single_gate_never_displays_full_success(draft, monkeypatch, gate):+ run(draft, monkeypatch, gate=gate)+ assert studio.inspect_status(draft)['status'] == 'partial'++[email protected]('blocked', [1, 2, 3, 4, 5])+def test_fail_fast_preserves_exit_and_blocker(draft, monkeypatch, blocked):+ code, report = run(draft, monkeypatch, blocked=blocked)+ assert code == 1+ assert len(report['gates']) == blocked+ status = studio.inspect_status(draft)+ assert status['status'] == 'blocked'+ assert status['gates'][-1]['violations'] == ['fixture blocker']+++def test_preview_run_remains_unverified(draft, monkeypatch):+ code, _ = run(draft, monkeypatch, blocked=3, preview=True)+ assert code == 0+ assert studio.inspect_status(draft)['status'] == 'unverified'+++def test_inputs_changed_during_checks_invalidate_evidence(draft, monkeypatch):+ _, report = run(draft, monkeypatch, mutate=True)+ assert report['evidence']['inputs_unchanged'] is False+ assert studio.inspect_status(draft)['status'] == 'stale'++[email protected]('name', ['article.md', 'article.html', 'article.pdf', 'hero.webp', 'review.md', 'style.css', 'preflight-targets.json', 'external-links.allowed', 'preview/desktop-1280.png', 'capabilities.json'])+def test_any_changed_consumed_input_or_output_is_stale(draft, monkeypatch, name):+ run(draft, monkeypatch)+ (draft / name).write_text('changed')+ assert studio.inspect_status(draft)['status'] == 'stale'+++def test_deleted_input_is_stale(draft, monkeypatch):+ run(draft, monkeypatch)+ (draft / 'article.pdf').unlink()+ assert studio.inspect_status(draft)['status'] == 'stale'+++def test_verifier_rotation_is_stale_without_exposing_nonce(draft, monkeypatch):+ run(draft, monkeypatch)+ nonce = preflight._init_review_nonce(draft)+ status = studio.inspect_status(draft)+ assert status['status'] == 'stale'+ assert nonce not in json.dumps(status)+++def test_run_identity_mismatch_cannot_accept_an_old_report(draft, monkeypatch):+ run(draft, monkeypatch)+ assert studio.inspect_status(draft, expected_run='b' * 32)['status'] == 'error'+++def test_legacy_report_has_unknown_freshness(draft, monkeypatch):+ _, report = run(draft, monkeypatch)+ del report['evidence']+ (draft / 'preflight-report.json').write_text(json.dumps(report))+ assert studio.inspect_status(draft)['status'] == 'unverified'++[email protected]('change', [+ lambda r: r.update(draft='/somewhere/else'),+ lambda r: r.update(blocked=True),+ lambda r: r['gates'].append(r['gates'][0]),+ lambda r: r['gates'][0].update(passed='true'),+ lambda r: r['gates'][0].update(violations=['contradiction']),+ lambda r: r['gates'][3].update(score=89),+ lambda r: r['gates'][3].update(score=float('nan')),+ lambda r: r['evidence'].update(completed_gates=[1]),+ lambda r: r['evidence'].update(requested_gates=[True, 2, 3, 4, 5]),+ lambda r: r['evidence'].update(started_at='tomorrow'),+ lambda r: r['evidence'].update(run_id='invalid'),+])+def test_malformed_or_contradictory_report_is_rejected(draft, monkeypatch, change):+ _, report = run(draft, monkeypatch)+ change(report)+ (draft / 'preflight-report.json').write_text(json.dumps(report))+ assert studio.inspect_status(draft)['status'] == 'error'++[email protected]('raw', ['{"strict":true,"strict":false}', '[]', '{broken'])+def test_bad_json_is_rejected(draft, raw):+ (draft / 'preflight-report.json').write_text(raw)+ assert studio.inspect_status(draft)['status'] == 'error'+++def test_missing_report_is_unverified(draft):+ assert studio.inspect_status(draft)['status'] == 'unverified'+++def test_symlink_input_is_unverified(draft, monkeypatch, tmp_path):+ run(draft, monkeypatch)+ (draft / 'escape').symlink_to(tmp_path)+ assert studio.inspect_status(draft)['status'] == 'unverified'+++def test_symlink_report_is_rejected(draft, tmp_path):+ target = tmp_path / 'report.json'+ target.write_text('{}')+ (draft / 'preflight-report.json').symlink_to(target)+ assert studio.inspect_status(draft)['status'] == 'error'++[email protected](not hasattr(os, 'mkfifo'), reason='FIFO requires Unix')+def test_fifo_report_is_refused_without_blocking(draft):+ os.mkfifo(draft / 'preflight-report.json')+ assert studio.inspect_status(draft)['status'] == 'error'+++def test_streaming_hash_supports_files_larger_than_mod_fs_limit(draft, monkeypatch):+ (draft / 'hero.webp').write_bytes(b'fixture' * 800_000)+ run(draft, monkeypatch)+ assert studio.inspect_status(draft)['status'] == 'passed'+++def test_fingerprint_limit_is_not_a_pass(draft, monkeypatch):+ monkeypatch.setattr(studio, 'MAX_FILES', 1)+ run(draft, monkeypatch)+ assert studio.inspect_status(draft)['status'] == 'unverified'+++def test_project_boundary_is_enforced(draft, monkeypatch, tmp_path):+ run(draft, monkeypatch)+ other = tmp_path / 'other'+ other.mkdir()+ assert studio.inspect_status(draft, other)['status'] == 'error'+ link = draft.parent / 'alias'+ link.symlink_to(draft, target_is_directory=True)+ assert studio.inspect_status(link, draft.parent)['status'] == 'error'+++def test_lexical_traversal_is_rejected_even_when_target_returns_inside(draft, monkeypatch):+ run(draft, monkeypatch)+ (draft.parent / 'other').mkdir()+ traversing = draft.parent / 'other/../article'+ assert studio.inspect_status(traversing, draft.parent)['status'] == 'error'+++def test_changed_engine_is_stale(draft, monkeypatch):+ run(draft, monkeypatch)+ identity = studio.engine_identity()+ identity['python'] = [0, 0, 0]+ monkeypatch.setattr(studio, 'engine_identity', lambda: identity)+ assert studio.inspect_status(draft)['status'] == 'stale'++[email protected]('missing', ['blog_preflight.py', 'blog_studio_status.py', 'blog-delivery-contract.md', 'blog-reviewer.md'])+def test_missing_identity_file_cannot_establish_freshness(draft, monkeypatch, missing):+ original = studio._file_hash+ def missing_hash(path, *args):+ if path.name == missing:+ raise FileNotFoundError('fixture identity file absent')+ return original(path, *args)+ monkeypatch.setattr(studio, '_file_hash', missing_hash)+ _, report = run(draft, monkeypatch)+ assert report['evidence']['engine']['errors']+ assert studio.inspect_status(draft)['status'] == 'unverified'+++def test_non_generated_preview_resources_are_inputs(draft, monkeypatch):+ resource = draft / 'preview/fonts/local.woff'+ resource.parent.mkdir(parents=True)+ resource.write_bytes(b'fixture font')+ _, report = run(draft, monkeypatch, mutate=True, mutate_name='preview/fonts/local.woff')+ assert 'preview/fonts/local.woff' in report['evidence']['inputs']['files']+ assert report['evidence']['inputs_unchanged'] is False+ assert studio.inspect_status(draft)['status'] == 'stale'+++def test_generated_screenshot_names_match_canonical_viewports():+ expected = {f"preview/{vp['name']}-{vp['width']}.png" for vp in preflight.VIEWPORTS}+ assert studio.SCREENSHOTS == expected | {'preview/desktop-1280-dark.png'}+++def test_project_contained_run_preserves_draft_identity_and_restores_cwd(draft, monkeypatch):+ before = Path.cwd()+ code, report = run(draft, monkeypatch, project_root=draft.parent)+ assert Path.cwd() == before+ assert code == 0 and report['draft'] == str(draft)+ assert studio.inspect_status(draft, draft.parent)['status'] == 'passed'+++def test_launch_refuses_replaced_draft_symlink(draft, monkeypatch, tmp_path):+ outside = tmp_path / 'outside'+ outside.mkdir()+ draft.rename(draft.with_name('original'))+ draft.symlink_to(outside, target_is_directory=True)+ monkeypatch.setattr(sys, 'argv', ['blog_preflight.py', '--draft', str(draft), '--project-root', str(draft.parent), '--json'])+ assert preflight.main() == 1+ assert not (outside / 'preflight-report.json').exists()+ assert not (outside / 'capabilities.json').exists()+++def test_anchored_writes_cannot_follow_replaced_path(draft, tmp_path):+ outside = tmp_path / 'outside'+ outside.mkdir()+ original = draft.with_name('original')+ before = Path.cwd()+ with preflight._anchored_draft(str(draft), str(draft.parent)) as (anchored, identity):+ assert identity == str(draft)+ draft.rename(original)+ draft.symlink_to(outside, target_is_directory=True)+ (anchored / 'sentinel').write_text('authorized selected directory only')+ assert Path.cwd() == before+ assert (original / 'sentinel').is_file()+ assert not (outside / 'sentinel').exists()+++def test_inspection_stays_anchored_when_selected_path_is_replaced(draft, monkeypatch, tmp_path):+ run(draft, monkeypatch)+ outside = tmp_path / 'outside'+ outside.mkdir()+ (outside / 'preflight-report.json').write_text('{"outside":true}')+ original = draft.with_name('original')+ original_load = studio.load_report+ opened = []+ def swapping_load(path):+ draft.rename(original)+ draft.symlink_to(outside, target_is_directory=True)+ opened.append(path.resolve())+ return original_load(path)+ monkeypatch.setattr(studio, 'load_report', swapping_load)+ before = Path.cwd()+ status = studio.inspect_status(draft, draft.parent)+ assert Path.cwd() == before+ assert opened == [original / 'preflight-report.json']+ assert status['status'] == 'stale'+++def test_fingerprinting_cannot_follow_a_replaced_child_directory(draft, monkeypatch, tmp_path):+ folder = draft / 'resources'+ folder.mkdir()+ (folder / 'local.css').write_text('selected style')+ outside = tmp_path / 'outside'+ outside.mkdir()+ (outside / 'local.css').write_text('outside private data')+ original_hash = studio._file_hash+ def swapping_hash(path, *args):+ if path.name == 'local.css':+ folder.rename(draft / 'original-resources')+ folder.symlink_to(outside, target_is_directory=True)+ return original_hash(path, *args)+ monkeypatch.setattr(studio, '_file_hash', swapping_hash)+ inputs = studio.capture_inputs(draft, preflight._review_state_path(draft))+ assert inputs['errors']+ assert 'resources/local.css' not in inputs['files']+++def test_report_open_refuses_symlinked_parent(tmp_path):+ outside = tmp_path / 'outside'+ outside.mkdir()+ (outside / 'report.json').write_text('{}')+ link = tmp_path / 'alias'+ link.symlink_to(outside, target_is_directory=True)+ with pytest.raises(OSError):+ studio.load_report(link / 'report.json')+++def test_status_inspection_does_not_write_files(draft, monkeypatch):+ run(draft, monkeypatch)+ before = {p: (p.stat().st_mtime_ns, p.read_bytes()) for p in draft.rglob('*') if p.is_file()}+ studio.inspect_status(draft)+ assert {p: (p.stat().st_mtime_ns, p.read_bytes()) for p in before} == before+++def test_diagnostics_strip_terminal_controls_and_identifiers():+ text = studio.safe_text('\x1b[31mBLOCKING: false Nonce: ' + 'a' * 32)+ assert '\x1b' not in text and 'a' * 32 not in text+++def test_unfinished_run_marker_is_blocked_not_passed(draft, monkeypatch):+ run(draft, monkeypatch)+ marker = preflight._incomplete_report(str(draft), True, 'run started and has not finished')+ (draft / 'preflight-report.json').write_text(json.dumps(marker))+ status = studio.inspect_status(draft, draft.parent)+ assert status['status'] == 'blocked' and status['gates'] == [] and status['passed_count'] == 0+ assert 'did not finish' in status['diagnostics'][0]+++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')+ monkeypatch.setattr(sys, 'argv', ['blog_preflight.py', '--draft', str(draft), '--json',+ '--repair-attempt', '--project-root', str(draft.parent)])+ assert preflight.main() == preflight.EXIT_ITERATION_CAP+ report = json.loads((draft / 'preflight-report.json').read_text())+ assert report['draft'] == str(draft) and report['incomplete'] is True and report['blocked'] is True+ assert 'evidence' not in report and report['previous_gates']+ assert studio.inspect_status(draft, draft.parent)['status'] == 'blocked'+++def test_evidence_is_additive_and_optional_without_the_studio_module(draft, monkeypatch):+ for name in ('_anchored_draft', 'capture_inputs', 'capture_outputs', 'engine_identity'):+ monkeypatch.setattr(preflight, name, None)+ code, report = run(draft, monkeypatch)+ assert code == 0 and 'evidence' not in report+ assert set(report) == {'draft', 'strict', 'blocked', 'gates'}+ assert studio.inspect_status(draft)['status'] == 'unverified'+++def test_project_root_without_the_studio_module_is_refused(draft, monkeypatch, capsys):+ monkeypatch.setattr(preflight, '_anchored_draft', None)+ monkeypatch.setattr(sys, 'argv', ['blog_preflight.py', '--draft', str(draft), '--project-root', str(draft.parent)])+ assert preflight.main() == 1+ assert 'blog_studio_status.py' in capsys.readouterr().err+ assert not (draft / 'preflight-report.json').exists()+++def test_run_ids_are_unique_32_hex(draft, monkeypatch):+ first = run(draft, monkeypatch)[1]['evidence']['run_id']+ second = run(draft, monkeypatch)[1]['evidence']['run_id']+ assert first != second+ assert all(len(i) == 32 and set(i) <= set('0123456789abcdef') for i in (first, second))diff --git a/tests/test_blog_studio_integration.py b/tests/test_blog_studio_integration.pynew file mode 100644index 0000000..53e4f10--- /dev/null+++ b/tests/test_blog_studio_integration.py@@ -0,0 +1,220 @@+"""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+spawn both scripts as subprocesses and validate the output with a Python mirror+of ``parseStatus`` in hooks/logic.ts and the report checks in hooks/register.ts.++Chromium and network gates cannot run in a unit test, so the passing case runs+the real CLI through a small harness that stubs gates 2 to 5 only. Gate 1, the+argument parsing, project anchoring, evidence capture, report writing and the+status script are all real. The blocked case runs fully unpatched.+"""+from __future__ import annotations++import json+import os+import re+import subprocess+import sys+from pathlib import Path++import pytest++SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"+HEX32 = re.compile(r"^[0-9a-f]{32}$")+LABELS = {"passed", "blocked", "partial", "stale", "unverified", "error"}++pytestmark = pytest.mark.skipif(+ not all(hasattr(os, name) for name in ("O_NOFOLLOW", "O_DIRECTORY", "fchdir")),+ reason="project-contained execution needs Unix directory descriptors",+)++HARNESS = """+import sys+sys.path.insert(0, sys.argv[1])+import blog_preflight as p++def make(n):+ def gate(d, **kwargs):+ if n == 3:+ (d / "preview").mkdir(exist_ok=True)+ (d / "preview" / "desktop-1280.png").write_bytes(b"fixture screenshot")+ extra = {"score": 95} if n == 4 else {}+ return p._gate_result(n, p.GATE_NAMES[n], True, [], **extra)+ return gate++p.gate_2_format_completeness = make(2)+p.gate_3_visual_verification = make(3)+p.gate_4_content_review = make(4)+p.gate_5_asset_link_integrity = make(5)+sys.argv = ["blog_preflight.py"] + sys.argv[2:]+raise SystemExit(p.main())+"""+++def parse_status(raw: str) -> dict:+ """Mirror of parseStatus in plugins/blog-studio/hooks/logic.ts."""+ assert len(raw) <= 1024 * 1024+ x = json.loads(raw)+ assert isinstance(x, dict)+ assert x["schema_version"] == 1 and x["status"] in LABELS+ assert type(x["passed_count"]) is int and 0 <= x["passed_count"] <= 5+ assert isinstance(x["gates"], list) and len(x["gates"]) <= 5+ assert isinstance(x["artifacts"], list) and len(x["artifacts"]) <= 8192+ assert isinstance(x["diagnostics"], list) and len(x["diagnostics"]) <= 200+ assert x["checked_at"] is None or isinstance(x["checked_at"], str)+ seen = set()+ for g in x["gates"]:+ assert type(g["gate"]) is int and 1 <= g["gate"] <= 5 and g["gate"] not in seen+ assert isinstance(g["name"], str) and type(g["passed"]) is bool+ assert isinstance(g["violations"], list) and isinstance(g["warnings"], list)+ assert all(isinstance(v, str) for v in g["violations"] + g["warnings"])+ assert g["score"] is None or (type(g["score"]) in (int, float) and 0 <= g["score"] <= 100)+ seen.add(g["gate"])+ assert x["passed_count"] == sum(g["passed"] for g in x["gates"])+ assert all(isinstance(v, str) for v in x["artifacts"] + x["diagnostics"])+ if x["status"] == "passed":+ assert len(x["gates"]) == 5 and all(g["passed"] and not g["violations"] for g in x["gates"])+ assert any(g["gate"] == 4 and g["score"] is not None and g["score"] >= 90 for g in x["gates"])+ assert isinstance(x.get("run_id"), str) and HEX32.match(x["run_id"])+ assert isinstance(x["checked_at"], str)+ return x+++def check_report(report: dict, draft: Path, exit_code: int) -> str:+ """Mirror of the report checks in register.ts perform(); returns the run id."""+ run_id = (report.get("evidence") or {}).get("run_id")+ assert report["strict"] is True and report["draft"] == str(draft)+ assert type(report["blocked"]) is bool and exit_code in (0, 1) and (exit_code == 0) != report["blocked"]+ assert isinstance(run_id, str) and HEX32.match(run_id)+ return run_id+++def project(tmp_path):+ root = tmp_path / "project"+ draft = root / "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)+ env = {**os.environ, "CLAUDE_BLOG_REVIEW_STATE_DIR": str(tmp_path / "verifier")}+ return root, draft, env+++def preflight(root, draft, env, *, patched, extra=()):+ argv = [sys.executable]+ 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]+ proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=120)+ return proc, json.loads(proc.stdout)+++def status(root, draft, env, run_id=None):+ argv = [sys.executable, str(SCRIPTS / "blog_studio_status.py"), "--draft", str(draft), "--project-root", str(root)]+ if run_id:+ argv += ["--expected-run", run_id]+ proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)+ return proc, parse_status(proc.stdout)+++def test_real_scripts_pass_then_go_stale_after_the_article_changes(project):+ root, draft, env = project+ proc, report = preflight(root, draft, env, patched=True)+ assert proc.returncode == 0, proc.stderr+ run_id = check_report(report, draft, proc.returncode)+ assert report["evidence"]["requested_gates"] == report["evidence"]["completed_gates"] == [1, 2, 3, 4, 5]+ assert report["evidence"]["inputs_unchanged"] is True++ proc, passed = status(root, draft, env, run_id)+ assert proc.returncode == 0, proc.stderr+ assert passed["status"] == "passed" and passed["run_id"] == run_id and passed["passed_count"] == 5+ assert "post.md" in passed["artifacts"] and "capabilities.json" in passed["artifacts"]++ (draft / "post.md").write_text("edited after the check")+ proc, stale = status(root, draft, env, run_id)+ assert proc.returncode == 0+ assert stale["status"] == "stale" and stale["passed_count"] == 5+ assert "Article inputs" in stale["diagnostics"][0]+++def test_real_unpatched_preflight_blocks_and_status_agrees(project):+ root, draft, env = project+ proc, report = preflight(root, draft, env, patched=False)+ assert proc.returncode == 1+ run_id = check_report(report, draft, proc.returncode)+ assert report["blocked"] is True and [g["gate"] for g in report["gates"]][-1] in (1, 2)+ proc, blocked = status(root, draft, env, run_id)+ assert proc.returncode == 0+ assert blocked["status"] == "blocked" and blocked["run_id"] == run_id+ assert any(not g["passed"] and g["violations"] for g in blocked["gates"])+++def test_real_single_gate_run_is_partial(project):+ root, draft, env = project+ proc, report = preflight(root, draft, env, patched=False, extra=("--gate", "1"))+ run_id = check_report(report, draft, proc.returncode)+ assert status(root, draft, env, run_id)[1]["status"] == "partial"+++def test_expected_run_mismatch_is_an_error_status(project):+ root, draft, env = project+ proc, report = preflight(root, draft, env, patched=True)+ assert proc.returncode == 0+ other = "0" * 32 if report["evidence"]["run_id"] != "0" * 32 else "f" * 32+ proc, wrong = status(root, draft, env, other)+ assert proc.returncode == 1+ assert wrong["status"] == "error" and "run_id" not in wrong+ assert "does not match" in wrong["diagnostics"][0]+++def test_iteration_cap_exit_stays_additive_and_never_passes(project):+ root, draft, env = project+ assert preflight(root, draft, env, patched=True)[0].returncode == 0+ (draft / ".iteration-count").write_text("3\n")+ argv = [sys.executable, str(SCRIPTS / "blog_preflight.py"), "--draft", str(draft), "--strict", "--json",+ "--tools-json", "[]", "--project-root", str(root), "--repair-attempt"]+ 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.stderr+ marker = json.loads((draft / "preflight-report.json").read_text())+ assert marker["draft"] == str(draft) and marker["incomplete"] is True+ assert status(root, draft, env)[1]["status"] == "blocked"+++def test_preflight_without_project_root_still_works_and_adds_evidence(project):+ root, draft, env = project+ argv = [sys.executable, str(SCRIPTS / "blog_preflight.py"), "--draft", str(draft), "--strict", "--json",+ "--tools-json", "[]", "--gate", "1"]+ proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)+ report = json.loads(proc.stdout)+ assert proc.returncode == 0 and report["draft"] == str(draft.resolve())+ assert HEX32.match(report["evidence"]["run_id"])+++def test_isolated_mode_and_relative_dot_paths_still_anchor_and_record_evidence(project):+ # `python3 -I` drops the script directory from sys.path, and `--project-root .`+ # is how a user runs it from the project; neither may lose evidence or be refused.+ root, draft, env = project+ relative = str(draft.relative_to(root))+ argv = [sys.executable, "-I", str(SCRIPTS / "blog_preflight.py"), "--draft", "./" + relative, "--strict",+ "--json", "--tools-json", "[]", "--project-root", ".", "--gate", "1"]+ proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)+ assert proc.returncode == 0, proc.stderr+ run_id = check_report(json.loads(proc.stdout), draft, proc.returncode)+ argv = [sys.executable, "-I", str(SCRIPTS / "blog_studio_status.py"), "--draft", "./" + relative,+ "--project-root", ".", "--expected-run", run_id]+ proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)+ assert proc.returncode == 0, proc.stderr+ assert parse_status(proc.stdout)["status"] == "partial"+++def test_project_root_outside_the_draft_is_refused(project, tmp_path):+ root, draft, env = project+ other = tmp_path / "other"+ other.mkdir()+ argv = [sys.executable, str(SCRIPTS / "blog_preflight.py"), "--draft", str(draft), "--strict", "--json",+ "--project-root", str(other)]+ proc = subprocess.run(argv, cwd=root, env=env, capture_output=True, text=True, timeout=60)+ assert proc.returncode == 1 and "refused" in proc.stderr+ assert not (draft / "preflight-report.json").exists()