Skip to content

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

build(plugins): install Blog Studio from its own branch

Agrici Daniel245c6a2026e3
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index d53b6a7..4bb5c61 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -14,9 +14,20 @@
},
{
"name": "blog-studio",
- "source": "./plugins/blog-studio",
- "version": "0.2.0",
- "description": "Optional companion to claude-blog: article status band, live pipeline and five-gate review panel, history of past blogs, and an explicit Run checks control. A Claude Code mod; install it separately."
+ "source": {
+ "source": "git-subdir",
+ "url": "AgriciDaniel/claude-blog",
+ "path": "plugins/blog-studio",
+ "ref": "blog-studio",
+ "sha": "c1cc72f85aab4398d9e9dc76196928fb9be3dd15"
+ },
+ "version": "0.3.0",
+ "description": "Optional companion to claude-blog (needs claude-blog 2.3.2 or later): article status band, live pipeline and five-gate review panel, history of past blogs, and an explicit Run checks control. A Claude Code mod served from the blog-studio branch; install it separately.",
+ "author": {
+ "name": "AgriciDaniel",
+ "url": "https://github.com/AgriciDaniel"
+ },
+ "homepage": "https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio"
}
]
}
diff --git a/.github/scripts/validate_plugin_tolerate_reserved_name.py b/.github/scripts/validate_plugin_tolerate_reserved_name.py
index 0873a2c..1889d00 100644
--- a/.github/scripts/validate_plugin_tolerate_reserved_name.py
+++ b/.github/scripts/validate_plugin_tolerate_reserved_name.py
@@ -14,11 +14,6 @@ Policy, implemented below and covered by tests/test_dependency_plugin_validate_t
* Tolerated error 2: `.claude-plugin/plugin.json`, field `name`, same message.
* Tolerated warning: the plugin-root CLAUDE.md notice. The file is the
contributor guide for this repository and is not shipped as plugin context.
-* Tolerated warning (Claude Code 2.1.218 only, which predates mods): marketplace
- manifest, field `plugins[1] plugin.json → types`, message starting
- `Unknown field 'types'`. The optional blog-studio companion declares a
- `types` manifest key that mods-era Claude Code reads and the older validator
- reports as unknown ("Claude Code ignores it at load time").
* Every other error or warning, in any section, fails the run. Each tolerated
finding counts once per section, so a duplicate is also a failure.
* A non-zero CLI exit with no parseable error block fails (an unknown output
@@ -39,8 +34,6 @@ from pathlib import Path
RESERVED_NAME_PREFIX = 'Plugin name "claude-blog" is reserved'
ROOT_CLAUDE_MD_PREFIX = "CLAUDE.md at the plugin root is not loaded as project context"
-STUDIO_TYPES_FIELD = "plugins[1] plugin.json \u2192 types"
-STUDIO_TYPES_PREFIX = "Unknown field 'types'"
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
SECTION = re.compile(r"^Validating (?P<kind>[^:]+): (?P<target>.+?)\s*$")
@@ -148,13 +141,6 @@ def tolerated_key(finding: Finding) -> str | None:
and _is_root_claude_md(finding)
):
return "root-claude-md-warning"
- if (
- finding.level == "warning"
- and _is_marketplace(finding)
- and finding.field == STUDIO_TYPES_FIELD
- and finding.message.startswith(STUDIO_TYPES_PREFIX)
- ):
- return "blog-studio-types-field-warning"
return None
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 78e3298..014547b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -202,35 +202,6 @@ 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-latest
steps:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c607fb..6b8201b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- Blog Studio moved off main to the `blog-studio` branch of this repository (`plugins/blog-studio`), because Claude Desktop refuses a plugin folder with a nested plugin manifest ("plugin.json must be at .claude-plugin/plugin.json at the plugin root ... found nested"), and the claude-blog plugin folder is the whole repository. The marketplace now installs Studio 0.3.0 from that branch with a `git-subdir` source pinned to a commit. The install id and commands are unchanged: `/plugin marketplace add AgriciDaniel/claude-blog` and then `/plugin install blog-studio@agricidaniel-blog`. Studio 0.3.0 needs claude-blog 2.3.2 or later. Main drops the `blog-studio` CI job, the `plugins/` coverage in `consistency_check.py` and `validate_public_release.py`, and the plugin validator's tolerance for the Studio `types` field. `validate_public_release.py` now checks the pinned entry's shape and rejects nested plugin manifests, and `tests/test_manifest_layout.py` covers both. The engine side stays on main: `scripts/blog_studio_status.py`, `blog_preflight.py --project-root` and `--manual-check`, still covered by `tests/test_blog_studio.py` and `tests/test_blog_studio_integration.py`.
+- Remove `brain/.claude-plugin/` (`plugin.json` and `marketplace.json`), a nested manifest left from when the brain was planned as its own plugin repository. It pointed at a repository that does not exist, nothing installs the brain as a plugin, and Claude Desktop refuses the claude-blog folder while it is there. The brain keeps its own `install.sh`.
- Ignore `/reports/`, where `/blog audit` writes its output.
- New README with six animated scenes (`assets/readme/`) starring the three bots, rebuilt around install, commands, team, pricing and how a post ships. Font credits for the embedded Geist, Geist Mono, Silkscreen and Pixelify Sans subsets are in NOTICE, and the OFL 1.1 text ships in `assets/readme/OFL.txt`.
- Add a plugin icon (`.claude-plugin/icon.png`); Claude Code 2.1.312 and later warn without one.
diff --git a/CLAUDE.md b/CLAUDE.md
index 227f141..d5bd349 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -23,14 +23,13 @@ claude-blog/
docs/CONTRIBUTORS.md # Pro Hub Challenge attribution and integration decisions
CHANGELOG.md # Keep a Changelog format
.claude-plugin/plugin.json # Plugin manifest (v2.3.2)
- .claude-plugin/marketplace.json # Marketplace catalog for distribution (claude-blog + optional blog-studio)
- plugins/blog-studio/ # Optional Claude Code mod companion (status band, pipeline panel); own README, tests, version 0.2.0
+ .claude-plugin/marketplace.json # Marketplace catalog: claude-blog (./) + optional blog-studio (git-subdir, blog-studio branch, pinned sha)
.mcp.example.json # MCP config example (tracked; .mcp.json is gitignored)
pyproject.toml # Python packaging (3.11+)
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 plugin
+ scripts/blog_studio_status.py # Read-only preflight evidence inspector; engine contract for Blog Studio (blog-studio branch)
scripts/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)
@@ -191,6 +190,25 @@ Submit at: claude.ai/settings/plugins/submit or platform.claude.com/plugins/subm
/plugin install claude-blog@agricidaniel-blog
```
+### Blog Studio (blog-studio branch)
+Blog Studio, the optional status band and pipeline panel, lives in
+`plugins/blog-studio` on the `blog-studio` branch of this repository
+(https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio), not on main. Claude Desktop refuses a plugin folder that holds a
+nested plugin manifest, and the claude-blog plugin folder is the whole
+repository. The marketplace entry installs Studio from that branch with a
+`git-subdir` source pinned to a commit `sha`; bump the `sha` (and `version`)
+in `.claude-plugin/marketplace.json` for each Studio release. The install id
+and commands are unchanged:
+```
+/plugin marketplace add AgriciDaniel/claude-blog
+/plugin install blog-studio@agricidaniel-blog
+```
+Studio 0.3.0 needs claude-blog 2.3.2 or later (it passes `--manual-check`). Its
+engine contract stays on main: `scripts/blog_studio_status.py`,
+`blog_preflight.py --project-root` and `--manual-check`, covered by
+`tests/test_blog_studio_integration.py`. `tests/test_manifest_layout.py` fails
+if any nested `.claude-plugin/plugin.json` appears on main.
+
### Standalone Install (no marketplace)
```bash
curl -fsSLo install.sh \
diff --git a/README.md b/README.md
index 8af26de..81db4ed 100644
--- a/README.md
+++ b/README.md
@@ -355,7 +355,7 @@ Claude Blog runs inside Claude Code, so your drafts are sent to Claude, the same
**Requirements.** Claude Code and Python 3.11 or newer. PDF rendering and screenshots need the `presentation` extra in `pyproject.toml`.
-**Blog Studio.** [`plugins/blog-studio`](plugins/blog-studio) is an optional second plugin in the same marketplace: a live status band, a pipeline and five-gate panel, a history of past posts and a **Run checks** button. Install it with `/plugin install blog-studio@agricidaniel-blog`. The standalone installers never enable it.
+**Blog Studio.** An optional companion plugin in the same marketplace: a live status band, a pipeline and five-gate panel, a history of past posts and a **Run checks** button. Install it with `/plugin install blog-studio@agricidaniel-blog`. It lives on the [`blog-studio` branch](https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio), needs claude-blog 2.3.2 or later, and the standalone installers never enable it.
**Known warning.** `claude plugin validate` on Claude Code 2.1.292 and later reports the name `claude-blog` as reserved. The plugin still installs and loads, and CI tolerates exactly that one finding. See [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md#plugin-validate-reports-claude-blog-as-reserved).
diff --git a/brain/.claude-plugin/marketplace.json b/brain/.claude-plugin/marketplace.json
deleted file mode 100644
index 2f4211d..0000000
--- a/brain/.claude-plugin/marketplace.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "name": "agricidaniel-claude-blog-brain",
- "owner": {
- "name": "Daniel Agrici"
- },
- "metadata": {
- "description": "Claude Blog Brain template and skill layer",
- "version": "0.2.0"
- },
- "plugins": [
- {
- "name": "claude-blog-brain",
- "source": "./",
- "description": "Obsidian brain for blog content creation, optimization, and management dual-optimized for Google rankings (E-E-A-T, the 2026 core updates) and AI citations (GEO/AEO), spanning writing, rewriting and freshness, SERP-informed briefs and outlines, editorial calendars and strategy, semantic topic clusters, schema and internal linking, multilingual publishing, the FLOW framework, factchecking, personas, distribution, and the blog delivery contract, grounded in the claude-blog skill.",
- "version": "0.2.0",
- "author": {
- "name": "Daniel Agrici"
- },
- "repository": "https://github.com/AgriciDaniel/claude-blog-brain",
- "license": "MIT",
- "category": "claude-blog",
- "tags": [
- "obsidian",
- "brain",
- "claude-blog"
- ],
- "keywords": [
- "claude-blog-brain",
- "claude-blog",
- "obsidian"
- ]
- }
- ]
-}
diff --git a/brain/.claude-plugin/plugin.json b/brain/.claude-plugin/plugin.json
deleted file mode 100644
index 256cfbe..0000000
--- a/brain/.claude-plugin/plugin.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "name": "claude-blog-brain",
- "version": "0.2.0",
- "description": "Claude Blog Brain Obsidian brain for blog content creation, optimization, and management dual-optimized for Google rankings (E-E-A-T, the 2026 core updates) and AI citations (GEO/AEO), spanning writing, rewriting and freshness, SERP-informed briefs and outlines, editorial calendars and strategy, semantic topic clusters, schema and internal linking, multilingual publishing, the FLOW framework, factchecking, personas, distribution, and the blog delivery contract, grounded in the claude-blog skill.",
- "author": {
- "name": "Daniel Agrici",
- "url": "https://github.com/AgriciDaniel"
- },
- "homepage": "https://github.com/AgriciDaniel/claude-blog-brain",
- "repository": "https://github.com/AgriciDaniel/claude-blog-brain",
- "license": "MIT",
- "keywords": [
- "claude-blog-brain",
- "obsidian",
- "brain",
- "claude-blog"
- ],
- "skills": [
- "./SKILL.md"
- ],
- "allowed-tools": [
- "Read",
- "Grep",
- "Glob",
- "Bash",
- "Write",
- "Edit"
- ]
-}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index cbfffb1..3dd1027 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -207,7 +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 |
+| `blog_studio_status.py` | Read-only inspector for the saved preflight report's `evidence` object; prints the status JSON the optional [Blog Studio](https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio) plugin displays (`--draft`, `--project-root`, `--expected-run`) | v2.3.2 |
| `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.md
index 0051d72..99dfa74 100644
--- a/docs/INSTALLATION.md
+++ b/docs/INSTALLATION.md
@@ -288,6 +288,23 @@ Pixabay/Unsplash/Pexels. AI image generation is an optional enhancement.
---
+## Optional: Blog Studio
+
+Blog Studio adds a live status band, a pipeline and five-gate panel, a history
+of past posts and a Run checks control. It is a separate plugin in the same
+marketplace, served from the `blog-studio` branch of this repository
+(https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio) and pinned to a commit:
+
+```
+/plugin marketplace add AgriciDaniel/claude-blog
+/plugin install blog-studio@agricidaniel-blog
+```
+
+Studio 0.3.0 needs claude-blog 2.3.2 or later, because its Run checks passes
+`blog_preflight.py --manual-check`.
+
+---
+
## Verification
After installation, verify everything is in place:
diff --git a/plugins/blog-studio/.claude-plugin/plugin.json b/plugins/blog-studio/.claude-plugin/plugin.json
deleted file mode 100644
index bc86a59..0000000
--- a/plugins/blog-studio/.claude-plugin/plugin.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "name": "blog-studio",
- "version": "0.2.0",
- "description": "Optional article status band, review panel and explicit preflight controls for Claude Blog.",
- "author": {
- "name": "AgriciDaniel",
- "url": "https://github.com/AgriciDaniel"
- },
- "homepage": "https://github.com/AgriciDaniel/claude-blog",
- "repository": "https://github.com/AgriciDaniel/claude-blog",
- "license": "MIT",
- "types": "./types/index.d.ts"
-}
diff --git a/plugins/blog-studio/.gitignore b/plugins/blog-studio/.gitignore
deleted file mode 100644
index 18acf53..0000000
--- a/plugins/blog-studio/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-node_modules/
-.reference-types/
-.claude-plugin/types/
diff --git a/plugins/blog-studio/README.md b/plugins/blog-studio/README.md
deleted file mode 100644
index 51bbc3c..0000000
--- a/plugins/blog-studio/README.md
+++ /dev/null
@@ -1,217 +0,0 @@
-# Blog Studio
-
-Blog Studio is an optional companion to `claude-blog`. It adds a compact article
-status band, a live pipeline and five-gate review panel, a history of past blogs,
-and an explicit **Run checks** control.
-Version 0.2.0. It ships in the claude-blog repository as a second plugin of the
-same marketplace, and it is not part of the `claude-blog` plugin itself.
-
-## Install
-
-```
-/plugin marketplace add AgriciDaniel/claude-blog
-/plugin install blog-studio@agricidaniel-blog
-```
-
-Neither the core plugin nor the standalone installers enable it, and nothing
-loads until you install it.
-
-## Use
-
-Blog Studio is a Claude Code mod (function-hook plugin), so it needs a Claude Code
-release with mods support. It was developed and checked on the Linux CLI,
-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 shared
-terminal/Desktop element set. Desktop fixture tests do not establish native
-Desktop support. Codex does not run Claude Code mods.
-
-Once installed:
-
-1. Configure the absolute scripts directory from a trusted engine installation
- using `/blog-studio configure /path/to/claude-blog/scripts`. It is remembered for
- every session and project until `/blog-studio configure reset`. Setting the
- existing `CLAUDE_BLOG_SCRIPTS_DIR` before starting a session overrides it. The directory
- must include both `blog_preflight.py` and `blog_studio_status.py`.
-2. Select an existing project-relative article directory with
- `/blog-studio select outputs/article`. Spaces in the directory are accepted
- literally; do not wrap the path in shell quotes.
-3. Open `/blog-studio`, then choose **Refresh** or **Run checks**. Refresh only
- inspects saved evidence. Run checks invokes the existing strict five-gate
- preflight, including its browser and public-link checks.
-
-Python 3.11 or newer must be available as `python3` on PATH with the engine's
-already-installed optional dependencies. The mod never installs them. Configure
-PATH before the session to select a virtual environment. No shell is used.
-
-| Command | Behavior |
-|---|---|
-| `/blog-studio` | Open the pipeline and gates panel, or show the text fallback |
-| `/blog-studio status` | Show cached state, last check time and the pipeline line |
-| `/blog-studio history` | List past blogs from every project, newest first, with date, time, status and gate count |
-| `/blog-studio history scan [folder]` | Backfill the history from `preflight-report.json` files under a folder (default: this project) |
-| `/blog-studio open <number>` | Select a blog from the history, in this or another project |
-| `/blog-studio demo` | Show a sample pipeline mid-draft, to judge the design without an agent |
-| `/blog-studio reset` | Clear the pipeline view |
-| `/blog-studio select <directory>` | Select a project-relative draft |
-| `/blog-studio configure <scripts>` | Pin trusted absolute engine helpers |
-| `/blog-studio refresh` | Inspect files and saved evidence without network or writes |
-| `/blog-studio check` | Run all strict preflight gates, then verify the saved run |
-
-The panel includes Select draft, Refresh, Run checks, and Close. Escape closes
-the panel. Duplicate runs are refused. Checks time out after ten minutes and
-status inspection after thirty seconds. Selection and cached results clear on
-workspace/session changes, clear, resume, and branch. Reload keeps a selection
-only 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 or
-workspace switch; its result cannot populate the new session's panel.
-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 after
-launch cannot redirect its report writes to a different directory.
-
-## The live pipeline
-
-While the agent writes a blog, the band and panel follow it through seven stages in
-order: Research, Outline, Draft, Visuals, Render, Review and Gates. The band is one
-row: a progress bar, a stage rail (`✓` done, `▸` working, `·` waiting, `✗` failed) and
-a clock. It shortens itself on narrow terminals and yields to surveys and other bands.
-
-The stages are **inferred**, never claimed. Blog Studio watches tool calls read-only
-and without any model call: web search and fetch, writes of Markdown, SVG and image
-files, the `blog-researcher`, `blog-writer`, `blog-reviewer` and `blog-seo` subagents,
-and the engine scripts `generate_hero.py`, `blog_render.py` and `blog_preflight.py`.
-A stage is marked done when a later one starts, or when the preflight evidence proves
-it. Evidence always wins over inference, and a passing preflight marks every stage
-verified. A failing render or preflight command marks that stage failed. When the agent
-writes a draft outside the selected folder, the panel offers it as "Use this draft".
-
-Colors are host theme keys only, so light and dark themes both work. Every status also
-has its own glyph and word, so nothing depends on color alone.
-
-## History of past blogs
-
-Every blog Blog Studio sees is recorded in the mod's own machine-wide store, newest
-activity first: drafts the agent writes, drafts you select, and drafts you check (with
-their result). The panel lists the latest five under **Recent blogs**, with a date, time,
-status glyph and gate count; **All blogs (h)** shows 25. Keys 1 to 9 open an entry.
-`/blog-studio history scan <folder>` adds older blogs from their delivery reports, dated
-by the report's file time. History holds paths and results only, never article text.
-
-A blog from another project is re-validated before it opens: absolute root, relative
-draft, and no symlinks anywhere on the path. Checks then run anchored to that project,
-and the panel shows its root. A stored record that fails validation is dropped.
-
-## Reading the results
-
-**Preflight passed** means the saved run was strict, requested and completed all
-five gates, and its local input/output fingerprints still match. It describes
-that recorded check, not publication approval or continuing network availability.
-Run Refresh after edits made outside Claude. Starting a new turn clears cached
-proof, and turn completion performs a read-only refresh for the selected draft.
-
-Other states are Blocked, Partial, Stale, Unverified, Running, and Execution
-error. Later gates after a fail-fast blocker remain Not checked. Legacy reports
-are readable, but freshness is Unverified. Single-gate passes and preview runs
-cannot become full preflight success. Missing helpers, malformed output,
-truncation, crashes, timeouts, and mismatched run identities remain visible.
-
-The panel displays gate diagnostics, reviewer score, and relative artifact
-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. 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 format
-
-`preflight-report.json` keeps its existing fields and adds `evidence`, version 1:
-run identity, UTC start/end times, requested/completed gates, contract version,
-engine identity, input fingerprints, an unchanged-input flag, and generated
-output fingerprints. Existing stdout modes, flags and exit statuses remain.
-
-The input snapshot conservatively includes regular files below the selected
-draft, including local CSS, scripts, images, fonts and review/config files.
-It excludes `preflight-report.json`, `capabilities.json`, `.iteration-count`,
-the four canonical screenshots under `preview`, and temporary files for those
-generated reports. Other resources below `preview` remain fingerprinted inputs.
-The verifier state is fingerprinted outside the draft without exposing its
-contents. Engine scripts and the delivery contract/reviewer instructions are
-fingerprinted too. Python runtime changes invalidate saved evidence.
-
-Hashing streams large files. Limits are 4,096 files and 512 MiB per snapshot,
-with a 1 MiB report limit. Symlinks, unsupported file types, unavailable files,
-and limit exhaustion cannot establish freshness. Generated capabilities and
-preview artifacts receive a separate post-run snapshot.
-
-Fingerprints are freshness evidence, not signatures. An actor able to forge
-reports can forge metadata. Delivery still requires the canonical preflight and
-review process; the UI does not add an approval authority.
-
-## Capability footprint
-
-The module registers only session lifecycle, turn lifecycle, its own command,
-and Pane/AbovePrompt rendering hooks. It reads the pinned scripts environment
-variable, path metadata, session root/id/surfaces and tool names. It stores
-session-scoped plain state and starts only the configured Python helpers with
-fixed argument vectors. Render handlers only read cached state and draw.
-
-There are no tool permission hooks, prompt rewriting, transcript reads, model
-calls, HTTP calls, cross-session messaging, automatic dependency installation,
-or persistent configuration changes. The checker retains its own existing
-rendering and network behavior. The status band composes with other mods and
-yields to surveys or slots too small to share.
-
-Mods run with the user's permissions. A disposable project is not isolation.
-Read `hooks/` before installing, as with any plugin, and try it first in a project without secrets if you want extra margin.
-[Official permissions guidance](https://code.claude.com/docs/en/plugins/mods/overview)
-
-## Development and acceptance gates
-
-The [manifest](.claude-plugin/plugin.json) and [hook entry](hooks/hooks.json)
-define the optional package. Its [development dependencies](package.json) and
-[lockfile](package-lock.json) stay separate from the core. The
-[source pin](dev/types-source.json) identifies the public reference declarations;
-[reference](tsconfig.reference.json) and [native](tsconfig.json) configurations
-keep the two type checks distinct.
-
-```bash
-npm ci --ignore-scripts --no-audit --no-fund
-npm run typecheck:reference
-claude plugin validate --strict --json .
-claude plugin test .
-```
-
-The reference type check covers production code using hash-pinned official
-public 2.1.277 declarations, plus a small explicitly provisional state-method
-contract. That public file predates the current state API. The reference check
-does not type-check test-kit code against an obsolete kit contract. The actual
-2.1.294 test kit executes those tests without a session, sign-in, or network.
-[Official testing documentation](https://code.claude.com/docs/en/plugins/mods/test)
-
-Fresh host-generated 2.1.294 typings are a separate required native gate:
-
-```bash
-npm run typecheck:native
-```
-
-This command requires the generated `.claude-plugin/types/claude-code/index.d.ts`
-with the exact target build header, and checks production plus test code without
-the provisional reference shim. Do not substitute old captures or change their
-version header. Generated types and development dependencies are ignored and
-excluded from maintained-source scans.
-
-Still open (honest status): native acceptance on your own terminal theme and
-glyphs, pane height on very tall terminals, reload and branch/resume behavior
-under real agent work, and the Desktop app (fixture tests only). Do not describe
-fixture drawings as native paint.
-[Official Mods reference](https://code.claude.com/docs/en/plugins/mods/reference)
-
-Rollback is `/plugin uninstall blog-studio@agricidaniel-blog`. Nothing else in the
-profile is touched, and the stored history is per plugin and holds paths and
-results only, never article text.
diff --git a/plugins/blog-studio/dev/native-types.mjs b/plugins/blog-studio/dev/native-types.mjs
deleted file mode 100644
index 4821a94..0000000
--- a/plugins/blog-studio/dev/native-types.mjs
+++ /dev/null
@@ -1,3 +0,0 @@
-import { readFile } from 'node:fs/promises'
-const source = await readFile(new URL('../.claude-plugin/types/claude-code/index.d.ts', import.meta.url), 'utf8')
-if (!source.startsWith('// Written by Claude Code 2.1.294.')) throw new Error('Native gate requires fresh Claude Code 2.1.294 generated typings')
diff --git a/plugins/blog-studio/dev/reference-state.d.ts b/plugins/blog-studio/dev/reference-state.d.ts
deleted file mode 100644
index c691a84..0000000
--- a/plugins/blog-studio/dev/reference-state.d.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// Provisional state-method typing for the pinned public 2.1.277 reference,
-// which predates $.state. Based on the current official Mods reference.
-// The native type check excludes this file and requires host-generated types.
-import type { HistoryState, RunState, StudioState } from '../types'
-type Values = { studio: StudioState; run: RunState; history: HistoryState }
-declare module 'claude-code' {
- interface EngineInterface {
- state: {
- get<K extends keyof Values>(ref: { plugin: 'blog-studio'; key: K }): Promise<{ value: Values[K] | undefined; version: number }>
- set<K extends keyof Values>(ref: { plugin: 'blog-studio'; key: K }, value: Values[K],
- options?: { ifVersion: number }): Promise<{ isSet: boolean; version: number }>
- }
- }
-}
diff --git a/plugins/blog-studio/dev/reference-types.mjs b/plugins/blog-studio/dev/reference-types.mjs
deleted file mode 100644
index c657dfa..0000000
--- a/plugins/blog-studio/dev/reference-types.mjs
+++ /dev/null
@@ -1,18 +0,0 @@
-// Fetch only the hash-pinned public declaration file. No mod is loaded.
-import { readFile, mkdir, writeFile } from 'node:fs/promises'
-import { createHash } from 'node:crypto'
-const source = JSON.parse(await readFile(new URL('./types-source.json', import.meta.url), 'utf8'))
-const folder = new URL('../.reference-types/', import.meta.url)
-const target = new URL('claude-code.d.ts', folder)
-let data
-try { data = await readFile(target) } catch { /* First reference check downloads its development input. */ }
-const hash = bytes => createHash('sha256').update(bytes).digest('hex')
-if (!data || hash(data) !== source.sha256) {
- const response = await fetch(source.url, { signal: AbortSignal.timeout(30_000) })
- if (!response.ok) throw new Error('Public type reference unavailable: ' + response.status)
- data = Buffer.from(await response.arrayBuffer())
- if (data.length > 2 * 1024 * 1024 || hash(data) !== source.sha256) throw new Error('Public typing reference hash mismatch')
- await mkdir(folder, { recursive: true })
- await writeFile(target, data)
-}
-console.log('Reference type check: public Claude Code 2.1.277 declarations plus provisional state typing. Native 2.1.294 typing remains a separate gate.')
diff --git a/plugins/blog-studio/dev/types-source.json b/plugins/blog-studio/dev/types-source.json
deleted file mode 100644
index 8c369dc..0000000
--- a/plugins/blog-studio/dev/types-source.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "url": "https://raw.githubusercontent.com/anthropics/claude-code/684800b206824dfd0cc8a876e8604b20f72c3617/mods/types/claude-code.d.ts",
- "revision": "684800b206824dfd0cc8a876e8604b20f72c3617",
- "sha256": "8ae1244d19d4b393261605fe72d517b66be0d7e1c214c378cdec5107e8b0b46c",
- "retrieved_at": "2026-10-08",
- "source_kind": "official repository, not host-generated"
-}
diff --git a/plugins/blog-studio/hooks/history.ts b/plugins/blog-studio/hooks/history.ts
deleted file mode 100644
index 67e2656..0000000
--- a/plugins/blog-studio/hooks/history.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import type { HistoryEntry, Status } from '../types'
-import { clean, relativeDraft } from './logic'
-
-export const MAX_STORED = 100
-export const MAX_SHOWN = 30
-export const KEY_PREFIX = 'entry:'
-
-/** FNV-1a over the absolute location, so one draft folder is one entry. */
-export function entryId(root: string, draft: string): string {
- let h = 0x811c9dc5
- for (const c of root + '\n' + draft) { h ^= c.charCodeAt(0); h = Math.imul(h, 0x01000193) >>> 0 }
- return h.toString(16).padStart(8, '0')
-}
-
-export function makeEntry(root: string, draft: string, now: number, source: HistoryEntry['source'],
- status: Status | null = null, lastSeen = now): HistoryEntry {
- return { id: entryId(root, draft), root, draft, name: clean(draft.split('/').pop() ?? draft, 80),
- firstSeen: lastSeen, lastSeen, source, status: status?.status ?? null, passed: status?.passed_count ?? 0,
- score: status?.gates.find(g => g.gate === 4)?.score ?? null }
-}
-
-/** Newest activity first. Merging keeps the earliest firstSeen and never lets a bare sighting erase a known result. */
-export function mergeEntries(list: HistoryEntry[], entry: HistoryEntry): HistoryEntry[] {
- const old = list.find(e => e.id === entry.id)
- const merged: HistoryEntry = old ? { ...entry, firstSeen: Math.min(old.firstSeen, entry.firstSeen),
- lastSeen: Math.max(old.lastSeen, entry.lastSeen),
- ...(entry.status === null ? { status: old.status, passed: old.passed, score: old.score } : {}) } : entry
- return sortEntries([...list.filter(e => e.id !== entry.id), merged])
-}
-
-export function sortEntries(list: HistoryEntry[]): HistoryEntry[] {
- return [...list].sort((a, b) => b.lastSeen - a.lastSeen || a.name.localeCompare(b.name))
-}
-
-export function validEntry(value: unknown): value is HistoryEntry {
- if (!value || typeof value !== 'object') return false
- const e = value as Record<string, unknown>
- if (typeof e.id !== 'string' || typeof e.root !== 'string' || typeof e.draft !== 'string' || typeof e.name !== 'string' ||
- typeof e.firstSeen !== 'number' || typeof e.lastSeen !== 'number' || typeof e.passed !== 'number') return false
- if (!e.root.startsWith('/') || e.root.length > 2000 || /[\x00-\x1f\x7f\\]/.test(e.root)) return false
- try { relativeDraft(e.draft) } catch { return false }
- return true
-}
-
-export function formatWhen(ms: number): string {
- const d = new Date(ms)
- const two = (n: number) => String(n).padStart(2, '0')
- return two(d.getMonth() + 1) + '-' + two(d.getDate()) + ' ' + two(d.getHours()) + ':' + two(d.getMinutes())
-}
-
-export function statusGlyph(status: HistoryEntry['status']): string {
- return status === 'passed' ? '✓' : status === 'blocked' || status === 'error' ? '✗' : status === 'stale' || status === 'partial' ? '!' : '·'
-}
-
-/** Splits an absolute draft folder into the project root it is anchored to and its relative path. */
-export function splitDraft(absolute: string, workspace: string): { root: string; draft: string } | null {
- const ws = workspace === '/' ? '' : workspace.replace(/\/$/, '')
- if (ws && absolute.startsWith(ws + '/')) {
- try { return { root: workspace, draft: relativeDraft(absolute.slice(ws.length + 1)) } } catch { return null }
- }
- const parts = absolute.split('/').filter(Boolean)
- if (parts.length < 2) return null
- const draft = parts.pop() as string
- try { return { root: '/' + parts.join('/'), draft: relativeDraft(draft) } } catch { return null }
-}
-
-/** Parses `find -printf '%T@\t%h\n'` output into folders and modification times, newest first. */
-export function parseFound(out: string, limit = 300): { path: string; mtimeMs: number }[] {
- const rows: { path: string; mtimeMs: number }[] = []
- for (const line of out.split('\n')) {
- const [t, path] = line.split('\t')
- const seconds = Number(t)
- if (!path || !path.startsWith('/') || !Number.isFinite(seconds) || /[\x00-\x1f\x7f\\]/.test(path)) continue
- rows.push({ path, mtimeMs: Math.round(seconds * 1000) })
- }
- return rows.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit)
-}
-
-/** A folder called 03-article says little, so lead with the project it sits in. */
-export function title(e: Pick<HistoryEntry, 'root' | 'name'>): string {
- const project = clean(e.root.split('/').filter(Boolean).pop() ?? '', 60)
- return project && project !== e.name ? project + ' / ' + e.name : e.name
-}
diff --git a/plugins/blog-studio/hooks/hooks.json b/plugins/blog-studio/hooks/hooks.json
deleted file mode 100644
index b75b48c..0000000
--- a/plugins/blog-studio/hooks/hooks.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "description": "Blog Studio status and check controls",
- "modules": [
- "./register.ts"
- ]
-}
diff --git a/plugins/blog-studio/hooks/logic.ts b/plugins/blog-studio/hooks/logic.ts
deleted file mode 100644
index 73a61f4..0000000
--- a/plugins/blog-studio/hooks/logic.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import type { Status, StudioState } from '../types'
-
-export const EMPTY: StudioState = {
- workspace: '', sessionId: '', scripts: null, draft: null,
- generation: 0, projectRoot: null, busy: false, status: null, message: null,
-}
-export const LABELS = {
- passed: 'Preflight passed', blocked: 'Blocked', partial: 'Partial', stale: 'Stale',
- unverified: 'Unverified', error: 'Execution error',
-} as const
-
-export function clean(value: string, limit = 500): string {
- return value.slice(0, 8192)
- .replace(/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|$))/g, '')
- .replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')
- .replace(/\b[0-9a-fA-F]{32}\b/g, '[redacted identifier]')
- .replace(/\/(?:var\/)?home\/[^/\s]+/g, '[home]')
- .slice(0, limit)
-}
-
-export function relativeDraft(value: string): string {
- const path = value.trim()
- if (!path || path.length > 1000 || path.startsWith('/') || path.includes('\\') || /[\x00-\x1f\x7f]/.test(path)) {
- throw new Error('Select a project-relative draft directory.')
- }
- const parts = path.split('/')
- if (parts.some(p => !p || p === '.' || p === '..')) throw new Error('Draft traversal and empty path components are refused.')
- return parts.join('/')
-}
-
-export function absoluteScripts(value: string): string {
- const path = value.trim().replace(/\/$/, '')
- if (!path.startsWith('/') || path.length > 2000 || /[\x00-\x1f\x7f\\]/.test(path) || path.split('/').slice(1).some(p => !p || p === '.' || p === '..')) {
- throw new Error('Configure an absolute trusted scripts directory.')
- }
- return path
-}
-
-export function absoluteRoot(value: string): string {
- const path = value.trim().replace(/\/$/, '') || '/'
- if (!path.startsWith('/') || path.length > 2000 || /[\x00-\x1f\x7f\\]/.test(path) || path.split('/').slice(1).some((p, i, a) => path !== '/' && (p === '.' || p === '..' || (!p && i < a.length)))) {
- throw new Error('Project root must be an absolute path.')
- }
- return path
-}
-
-export function parseStatus(raw: string, stderr = ''): Status {
- if (raw.length > 1024 * 1024) throw new Error('Status response exceeds size limit.')
- const value = jsonResponse(raw, stderr)
- if (!value || typeof value !== 'object') throw new Error('Invalid status response.')
- const x = value as Record<string, unknown>
- if (x.schema_version !== 1 || typeof x.status !== 'string' || !Object.hasOwn(LABELS, x.status) ||
- !Number.isInteger(x.passed_count) || Number(x.passed_count) < 0 || Number(x.passed_count) > 5 ||
- !Array.isArray(x.gates) || x.gates.length > 5 || !Array.isArray(x.artifacts) || x.artifacts.length > 8192 ||
- !Array.isArray(x.diagnostics) || x.diagnostics.length > 200 ||
- !(x.checked_at === null || typeof x.checked_at === 'string')) throw new Error('Invalid status fields.')
- const seen = new Set<number>()
- const gates = x.gates.map((g: unknown) => {
- if (!g || typeof g !== 'object') throw new Error('Invalid gate result.')
- const row = g as Record<string, unknown>
- const n = row.gate
- if (typeof n !== 'number' || !Number.isInteger(n) || n < 1 || n > 5 || seen.has(n) ||
- typeof row.name !== 'string' || typeof row.passed !== 'boolean' ||
- !Array.isArray(row.violations) || !Array.isArray(row.warnings) ||
- !(row.score === null || (typeof row.score === 'number' && Number.isFinite(row.score) && row.score >= 0 && row.score <= 100))) throw new Error('Invalid gate fields.')
- seen.add(n)
- return { gate: n, name: clean(row.name), passed: row.passed, score: row.score as number | null,
- violations: strings(row.violations), warnings: strings(row.warnings) }
- })
- if (Number(x.passed_count) !== gates.filter(g => g.passed).length) throw new Error('Gate count contradicts results.')
- if (x.status === 'passed' && (gates.length !== 5 || gates.some(g => !g.passed || g.violations.length) ||
- !gates.some(g => g.gate === 4 && g.score !== null && g.score >= 90) || typeof x.run_id !== 'string' ||
- !/^[0-9a-f]{32}$/.test(x.run_id) || typeof x.checked_at !== 'string')) throw new Error('Incomplete passing status.')
- return { schema_version: 1, status: x.status as Status['status'], label: LABELS[x.status as keyof typeof LABELS],
- passed_count: Number(x.passed_count), checked_at: x.checked_at === null ? null : clean(x.checked_at as string), gates,
- artifacts: strings(x.artifacts, 8192), diagnostics: strings(x.diagnostics),
- ...(typeof x.run_id === 'string' ? { run_id: x.run_id } : {}) }
-}
-
-export function jsonResponse(raw: string, stderr = ''): unknown {
- try { return JSON.parse(raw) } catch {
- throw new Error('Helper returned malformed or incomplete JSON. No passing result was accepted.' +
- (stderr ? ' Diagnostic: ' + clean(stderr, 500) : ''))
- }
-}
-
-function strings(value: unknown[], max = 200): string[] {
- if (value.length > max || value.some(v => typeof v !== 'string')) throw new Error('Invalid diagnostic list.')
- return (value as string[]).map(v => clean(v, 1000))
-}
-
-export function summary(s: StudioState): string {
- if (!s.draft) return 'Blog Studio: select a draft with /blog-studio select <directory>.'
- if (s.busy) return 'Blog Studio: ' + clean(s.draft, 90) + ' | ' + (s.message ?? 'Working...')
- const status = s.status
- return 'Blog Studio: ' + clean(s.draft, 90) + ' | ' + (status?.label ?? 'Unverified') +
- ' | ' + (status?.passed_count ?? 0) + '/5 gates | Last checked: ' + (status?.checked_at ?? 'unknown') +
- (s.message ? ' | ' + clean(s.message) : '')
-}
diff --git a/plugins/blog-studio/hooks/pipeline.ts b/plugins/blog-studio/hooks/pipeline.ts
deleted file mode 100644
index e89e290..0000000
--- a/plugins/blog-studio/hooks/pipeline.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import type { RunState, Stage, StageId } from '../types'
-import { clean, relativeDraft } from './logic'
-
-export const STAGES: readonly { id: StageId; label: string }[] = [
- { id: 'research', label: 'Research' }, { id: 'outline', label: 'Outline' }, { id: 'draft', label: 'Draft' },
- { id: 'visuals', label: 'Visuals' }, { id: 'render', label: 'Render' }, { id: 'review', label: 'Review' },
- { id: 'gates', label: 'Gates' },
-]
-
-export type Signal =
- | { kind: 'start'; skill: string }
- | { kind: 'stage'; stage: StageId; note: string; draft?: string }
-
-const START_SKILLS = new Set(['blog', 'blog-write', 'blog-rewrite', 'pro-blog', 'youtube-to-blog', 'blog-multilingual'])
-const SKILL_STAGE: Record<string, StageId> = {
- 'blog-outline': 'outline', 'blog-brief': 'outline', 'blog-notebooklm': 'research', 'blog-discourse': 'research',
- 'blog-chart': 'visuals', 'blog-image': 'visuals', banana: 'visuals',
- 'blog-seo-check': 'review', 'blog-factcheck': 'review', 'blog-analyze': 'review', 'blog-geo': 'review',
-}
-const AGENT_STAGE: Record<string, StageId> = {
- 'blog-researcher': 'research', 'blog-writer': 'draft', 'blog-translator': 'draft',
- 'blog-reviewer': 'review', 'blog-seo': 'review',
-}
-const NOT_DRAFT = /^(brand|voice|discourse|readme|claude|agents|memory|skill|changelog)$/i
-
-function tail(name: string): string {
- return name.split(':').pop() ?? name
-}
-
-function text(value: unknown, limit = 200): string {
- return typeof value === 'string' ? value.slice(0, limit) : ''
-}
-
-export function draftDirectory(filePath: string, workspace: string): string | null {
- const root = workspace === '/' ? '' : workspace.replace(/\/$/, '')
- if (!filePath.startsWith(root + '/')) return null
- const parts = filePath.slice(root.length + 1).split('/')
- parts.pop()
- if (!parts.length) return null
- try { return relativeDraft(parts.join('/')) } catch { return null }
-}
-
-export function skillSignal(skill: string): Signal | null {
- const name = tail(skill)
- if (START_SKILLS.has(name)) return { kind: 'start', skill: clean(name, 40) }
- const stage = SKILL_STAGE[name]
- return stage ? { kind: 'stage', stage, note: clean('/' + name, 60) } : null
-}
-
-/** Inference only: classifies one tool call by name and arguments, never by running anything. */
-export function classify(tool: string, input: Record<string, unknown>, workspace: string): Signal | null {
- if (tool === 'Skill') return skillSignal(text(input.skill, 120))
- if (tool === 'WebSearch') return { kind: 'stage', stage: 'research', note: 'web search' }
- if (tool === 'WebFetch') {
- let host = ''
- try { host = new URL(text(input.url, 500)).hostname } catch { /* not a URL */ }
- return { kind: 'stage', stage: 'research', note: host ? clean('read ' + host, 60) : 'web fetch' }
- }
- if (tool === 'Agent' || tool === 'Task') {
- const stage = AGENT_STAGE[tail(text(input.subagent_type, 80))]
- return stage ? { kind: 'stage', stage, note: clean(tail(text(input.subagent_type, 80)), 40) } : null
- }
- if (tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit') {
- const file = text(input.file_path, 1000)
- const base = file.split('/').pop() ?? ''
- const stem = base.replace(/\.[^.]*$/, '')
- if (/^review\.md$/i.test(base)) return { kind: 'stage', stage: 'review', note: 'review.md' }
- if (/\.(svg|png|jpe?g|webp)$/i.test(base)) return { kind: 'stage', stage: 'visuals', note: clean(base, 40) }
- if (/\.mdx?$/i.test(base) && /outline|brief/i.test(base)) return { kind: 'stage', stage: 'outline', note: clean(base, 40) }
- if (/\.mdx?$/i.test(base) && !NOT_DRAFT.test(stem)) {
- const draft = draftDirectory(file, workspace)
- return { kind: 'stage', stage: 'draft', note: clean('write ' + base, 60), ...(draft ? { draft } : {}) }
- }
- return null
- }
- if (tool === 'Bash') {
- const cmd = text(input.command, 2000)
- if (/blog_preflight/.test(cmd)) return { kind: 'stage', stage: 'gates', note: 'preflight' }
- if (/blog_render/.test(cmd)) return { kind: 'stage', stage: 'render', note: 'render html and pdf' }
- if (/generate_hero|blog_chart|chart_generator|banana/.test(cmd)) return { kind: 'stage', stage: 'visuals', note: 'images and charts' }
- if (/analyze_blog|lint_prose|ai_citation|quality_gate|cognitive_load/.test(cmd)) return { kind: 'stage', stage: 'review', note: 'quality scripts' }
- if (/discourse_research|notebooklm|last30days/.test(cmd)) return { kind: 'stage', stage: 'research', note: 'research scripts' }
- return null
- }
- if (tool.startsWith('mcp__')) {
- if (/dataforseo|notebooklm|exa|firecrawl|perplexity|search/i.test(tool)) return { kind: 'stage', stage: 'research', note: 'research tool' }
- if (/banana|nano|imagen|gemini/i.test(tool)) return { kind: 'stage', stage: 'visuals', note: 'image tool' }
- }
- return null
-}
-
-function blankStage(): Stage {
- return { state: 'pending', n: 0, startedAt: null, endedAt: null, note: null }
-}
-
-export function emptyRun(workspace = '', sessionId = ''): RunState {
- return { workspace, sessionId, skill: null, startedAt: null, endedAt: null, working: false,
- stages: Object.fromEntries(STAGES.map(s => [s.id, blankStage()])) as RunState['stages'],
- detected: null, scores: [], setup: false, historyOpen: false }
-}
-
-export function reduce(run: RunState, signal: Signal, now: number): RunState {
- if (signal.kind === 'start') {
- return { ...emptyRun(run.workspace, run.sessionId), skill: signal.skill, startedAt: now, working: true,
- scores: run.scores, setup: run.setup, historyOpen: run.historyOpen }
- }
- const index = STAGES.findIndex(s => s.id === signal.stage)
- const stages = { ...run.stages }
- STAGES.forEach((s, i) => {
- const cur = stages[s.id]
- if (i < index && cur.state === 'active') stages[s.id] = { ...cur, state: 'done', endedAt: now }
- })
- const cur = stages[signal.stage]
- stages[signal.stage] = { state: 'active', n: cur.n + 1, startedAt: cur.state === 'active' ? cur.startedAt : now,
- endedAt: null, note: signal.note }
- return { ...run, startedAt: run.startedAt ?? now, endedAt: null, working: true, stages,
- detected: signal.draft ?? run.detected }
-}
-
-export function fail(run: RunState, stage: StageId, now: number): RunState {
- const cur = run.stages[stage]
- return { ...run, stages: { ...run.stages, [stage]: { ...cur, state: 'failed', endedAt: now } } }
-}
-
-export function pause(run: RunState, now: number): RunState {
- return { ...run, working: false, endedAt: run.startedAt ? now : null }
-}
-
-export function doneCount(run: RunState): number {
- return STAGES.filter(s => run.stages[s.id].state === 'done').length
-}
-
-export function currentStage(run: RunState): { id: StageId; label: string } | null {
- let found: { id: StageId; label: string } | null = null
- for (const s of STAGES) if (run.stages[s.id].state === 'active' || run.stages[s.id].state === 'failed') found = s
- return found
-}
-
-export function hasRun(run: RunState): boolean {
- return run.startedAt !== null
-}
-
-/** Sample data for /blog-studio demo: a run caught mid-draft, so the design can be judged without an agent. */
-export function demoRun(base: RunState, now: number): RunState {
- const at = (ago: number, taken: number): Pick<Stage, 'startedAt' | 'endedAt'> => ({ startedAt: now - ago, endedAt: now - ago + taken })
- const stages = emptyRun().stages
- stages.research = { state: 'done', n: 14, ...at(134_000, 52_000), note: 'read example.com' }
- stages.outline = { state: 'done', n: 2, ...at(82_000, 9_000), note: 'outline.md' }
- stages.draft = { state: 'active', n: 3, startedAt: now - 73_000, endedAt: null, note: 'write preview-post.md' }
- return { ...base, skill: 'preview', startedAt: now - 134_000, endedAt: null, working: true, stages,
- detected: null, scores: [62, 71, 84] }
-}
diff --git a/plugins/blog-studio/hooks/register.ts b/plugins/blog-studio/hooks/register.ts
deleted file mode 100644
index 279685c..0000000
--- a/plugins/blog-studio/hooks/register.ts
+++ /dev/null
@@ -1,471 +0,0 @@
-import type { EngineInterface, Register, Timer } from 'claude-code'
-import type { HistoryEntry, HistoryState, RunState, StudioState, Status } from '../types'
-import { absoluteRoot, absoluteScripts, clean, EMPTY, jsonResponse, parseStatus, relativeDraft, summary } from './logic'
-import { classify, demoRun, emptyRun, fail, pause, reduce, skillSignal, type Signal } from './pipeline'
-import { formatWhen, KEY_PREFIX, makeEntry, MAX_SHOWN, MAX_STORED, mergeEntries, parseFound, sortEntries, splitDraft, statusGlyph, title, validEntry } from './history'
-import { bandDetail, bandRow, effective, el, pane, pipelineLine, type PaneActions } from './view'
-
-const PANE = 'blog-studio-review'
-const REF = { plugin: 'blog-studio', key: 'studio' } as const
-const RUN = { plugin: 'blog-studio', key: 'run' } as const
-const HIST = { plugin: 'blog-studio', key: 'history' } as const
-const CONFIG = 'config'
-const HELPER = 'blog_studio_status.py'
-const CHECKER = 'blog_preflight.py'
-
-async function held($: EngineInterface) {
- const result = await $.state.get(REF)
- return { value: result.value ?? { ...EMPTY }, version: result.version }
-}
-
-async function heldRun($: EngineInterface) {
- const result = await $.state.get(RUN)
- return { value: result.value ?? emptyRun(), version: result.version }
-}
-
-// Display-only bookkeeping: a lost race only drops one counter tick, so retry twice and give up quietly.
-async function updateRun($: EngineInterface, change: (run: RunState) => RunState) {
- for (let attempt = 0; attempt < 3; attempt++) {
- const current = await heldRun($)
- let base = current.value
- if (!base.workspace) base = { ...base, workspace: (await $.session.root()).replace(/\/$/, '') || '/', sessionId: await $.session.id() }
- if ((await $.state.set(RUN, change(base), { ifVersion: current.version })).isSet) return
- }
-}
-
-let ticker: Timer | null = null
-
-function startTicker($: EngineInterface) {
- if (ticker) return
- ticker = $.clock.every(1000, () => { $.ui.invalidate('ui.render') })
-}
-
-function stopTicker() {
- ticker?.cancel()
- ticker = null
-}
-
-const rootOf = (s: StudioState) => s.projectRoot ?? s.workspace
-
-async function heldHistory($: EngineInterface) {
- const result = await $.state.get(HIST)
- return { value: result.value ?? { entries: [], loaded: false } as HistoryState, version: result.version }
-}
-
-async function publishHistory($: EngineInterface, change: (entries: HistoryEntry[]) => HistoryEntry[]) {
- for (let attempt = 0; attempt < 3; attempt++) {
- const current = await heldHistory($)
- const entries = change(current.value.entries).slice(0, MAX_SHOWN)
- if ((await $.state.set(HIST, { entries, loaded: true }, { ifVersion: current.version })).isSet) return
- }
-}
-
-// Durable history lives in $.store, one key per draft folder. $.state mirrors the newest few so drawing never does I/O.
-async function loadHistory($: EngineInterface) {
- const keys = (await $.store.keys()).filter(k => k.startsWith(KEY_PREFIX))
- const entries: HistoryEntry[] = []
- for (const key of keys) { const v = await $.store.get(key); if (validEntry(v)) entries.push(v) }
- const sorted = sortEntries(entries)
- await publishHistory($, () => sorted)
-}
-
-async function recordEntries($: EngineInterface, incoming: HistoryEntry[]) {
- const merged: HistoryEntry[] = []
- for (const entry of incoming) {
- const old = await $.store.get(KEY_PREFIX + entry.id)
- const next = mergeEntries(validEntry(old) ? [old] : [], entry)[0]
- if (!next) continue
- await $.store.set(KEY_PREFIX + next.id, next)
- merged.push(next)
- }
- const keys = (await $.store.keys()).filter(k => k.startsWith(KEY_PREFIX))
- if (keys.length > MAX_STORED) {
- const all: HistoryEntry[] = []
- for (const key of keys) { const v = await $.store.get(key); if (validEntry(v)) all.push(v); else await $.store.delete(key) }
- for (const stale of sortEntries(all).slice(MAX_STORED)) await $.store.delete(KEY_PREFIX + stale.id)
- }
- await publishHistory($, entries => merged.reduce(mergeEntries, entries))
-}
-
-async function remember($: EngineInterface, entry: HistoryEntry) {
- try { await recordEntries($, [entry]) } catch { /* history is a convenience, never a failure */ }
-}
-
-async function savedScripts($: EngineInterface): Promise<string | null> {
- try {
- const value = await $.store.get(CONFIG)
- const scripts = value && typeof value === 'object' ? (value as { scripts?: unknown }).scripts : null
- return typeof scripts === 'string' ? absoluteScripts(scripts) : null
- } catch { return null }
-}
-
-async function context($: EngineInterface) {
- const current = await held($)
- const workspace = (await $.session.root()).replace(/\/$/, '') || '/'
- const sessionId = await $.session.id()
- if (current.value.workspace === workspace && current.value.sessionId === sessionId) return current
- const pinned = await $.env.get('CLAUDE_BLOG_SCRIPTS_DIR')
- const value = { ...EMPTY, workspace, sessionId, generation: current.value.generation + 1,
- scripts: pinned ? absoluteScripts(pinned) : await savedScripts($) }
- const written = await $.state.set(REF, value, { ifVersion: current.version })
- if (!written.isSet) throw new Error('Session changed. Try again.')
- return { value, version: written.version }
-}
-
-async function noLinks($: EngineInterface, absolute: string, kind: 'file' | 'dir') {
- let path = ''
- const parts = absolute.split('/').filter(Boolean)
- for (let i = 0; i < parts.length; i++) {
- path += '/' + parts[i]
- const info = await $.fs.stat(path).catch(() => undefined)
- if (!info || info.isLink || info.kind !== (i === parts.length - 1 ? kind : 'dir')) {
- throw new Error('Missing or unsafe path. Symlinks are refused.')
- }
- }
-}
-
-async function prepare($: EngineInterface, s: StudioState) {
- if (!s.scripts) throw new Error('Configure the trusted claude-blog scripts directory first.')
- if (!s.draft) throw new Error('Select a draft first.')
- const root = rootOf(s)
- const draft = (root === '/' ? '' : root) + '/' + relativeDraft(s.draft)
- const scripts = absoluteScripts(s.scripts)
- if (scripts === draft || scripts.startsWith(draft + '/')) throw new Error('Executable helpers cannot come from the selected draft.')
- await noLinks($, draft, 'dir')
- await noLinks($, scripts + '/' + HELPER, 'file')
- await noLinks($, scripts + '/' + CHECKER, 'file')
- return { draft, scripts }
-}
-
-function response(raw: { stdout: string; stderr: string; exitCode: number }): string {
- const flags = raw as typeof raw & { isStdoutTruncated?: boolean; isStderrTruncated?: boolean }
- if (flags.isStdoutTruncated || flags.isStderrTruncated || raw.stdout.length >= 4 * 1024 * 1024) {
- throw new Error('Checker output was truncated. No passing result was accepted. ' + clean(raw.stderr))
- }
- return raw.stdout
-}
-
-async function inspect($: EngineInterface, s: StudioState, runId?: string): Promise<Status> {
- const paths = await prepare($, 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)
- if (out.exitCode !== 0 && status.status !== 'error') throw new Error('Status inspector failed.')
- return 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
- if (s.busy) return 'Checks are already running.'
- // Reserve this state version before any process starts. A later selection,
- // reset or reload changes the version, so this operation cannot publish late.
- const reservation = await $.state.set(REF, { ...s, busy: true, message: check ? 'Running checks...' : 'Refreshing evidence...' }, { ifVersion: snapshot.version })
- if (!reservation.isSet) return 'State changed. Try again.'
- let status: Status | null = null
- let message: string | null = null
- try {
- let runId: string | undefined
- if (check) {
- const paths = await prepare($, s)
- const tools = (await $.tool.list()).map(t => t.name)
- // -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 }
- if (r.strict !== true || r.draft !== paths.draft || typeof r.blocked !== 'boolean' ||
- (out.exitCode !== 0 && out.exitCode !== 1) || (out.exitCode === 0) === r.blocked ||
- typeof r.evidence?.run_id !== 'string' || !/^[0-9a-f]{32}$/.test(r.evidence.run_id)) {
- throw new Error('Checker exit status or report was inconsistent. ' + clean(out.stderr))
- }
- runId = r.evidence.run_id
- }
- status = await inspect($, s, runId)
- } catch (error) {
- message = clean(error instanceof Error ? error.message : String(error))
- 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 }
- const written = await $.state.set(REF, final, { ifVersion: reservation.version })
- if (written.isSet && s.draft) {
- const result = status.status === 'error' ? null : status
- await remember($, makeEntry(rootOf(s), s.draft, Date.now(), check ? 'checked' : 'selected', result))
- const score = status.gates.find(g => g.gate === 4)?.score
- if (check && typeof score === 'number') {
- try { await updateRun($, run => (run.scores.at(-1) === score ? run : { ...run, scores: [...run.scores, score].slice(-8) })) } catch { /* display only */ }
- }
- }
- return written.isSet ? summary(final) : 'Previous check result was discarded after a state change.'
-}
-
-async function select($: EngineInterface, raw: string): Promise<string> {
- const current = await context($)
- const s = current.value
- if (s.busy) throw new Error('Wait for the current check before changing the selection.')
- const draft = relativeDraft(raw)
- await noLinks($, (s.workspace === '/' ? '' : s.workspace) + '/' + draft, 'dir')
- const next = { ...s, draft, projectRoot: null, status: null, message: null, generation: s.generation + 1 }
- if (!(await $.state.set(REF, next, { ifVersion: current.version })).isSet) throw new Error('Selection changed. Try again.')
- await remember($, makeEntry(s.workspace, draft, Date.now(), 'selected'))
- return summary(next)
-}
-
-// A past blog may live in another project. Its recorded root is re-validated like a fresh selection,
-// and the checks run anchored to that root, which the panel shows.
-async function open($: EngineInterface, entry: HistoryEntry): Promise<string> {
- const current = await context($)
- const s = current.value
- if (s.busy) throw new Error('Wait for the current check before changing the selection.')
- const root = absoluteRoot(entry.root)
- const draft = relativeDraft(entry.draft)
- await noLinks($, root, 'dir')
- await noLinks($, (root === '/' ? '' : root) + '/' + draft, 'dir')
- const next = { ...s, draft, projectRoot: root === s.workspace ? null : root, status: null, message: null, generation: s.generation + 1 }
- if (!(await $.state.set(REF, next, { ifVersion: current.version })).isSet) throw new Error('Selection changed. Try again.')
- await remember($, { ...entry, lastSeen: Date.now(), source: 'selected', status: null })
- return summary(next) + (next.projectRoot ? '\nProject root: ' + clean(next.projectRoot, 200) : '')
-}
-
-async function pick($: EngineInterface, ref: string): Promise<string> {
- const entries = (await heldHistory($)).value.entries
- const number = /^[0-9]{1,3}$/.test(ref) ? Number(ref) : 0
- const entry = number ? entries[number - 1] : entries.find(e => e.id === ref)
- if (!entry) throw new Error(number ? 'No blog number ' + number + '. Run /blog-studio history.' : 'That blog is no longer in the history.')
- return open($, entry)
-}
-
-function historyText(entries: HistoryEntry[]): string {
- if (!entries.length) return 'Blog Studio: no blogs in the history yet. They are added as the agent writes or you select them. Backfill with /blog-studio history scan <folder>.'
- return 'Blog Studio history (newest first):\n' + entries.slice(0, 20).map((e, i) =>
- String(i + 1).padStart(2) + '. ' + formatWhen(e.lastSeen) + ' ' + statusGlyph(e.status) + ' ' + title(e) +
- (e.status ? ' ' + e.passed + '/5 gates' : '')).join('\n') +
- '\nOpen one with /blog-studio open <number>. Remove one with /blog-studio history forget <number>.'
-}
-
-async function forget($: EngineInterface, ref: string): Promise<string> {
- const entries = (await heldHistory($)).value.entries
- const number = /^[0-9]{1,3}$/.test(ref) ? Number(ref) : 0
- const entry = number ? entries[number - 1] : undefined
- if (!entry) throw new Error('Give the number from /blog-studio history.')
- await $.store.delete(KEY_PREFIX + entry.id)
- await publishHistory($, list => list.filter(e => e.id !== entry.id))
- return 'Blog Studio: removed ' + title(entry) + ' from the history. The files were not touched.'
-}
-
-async function scan($: EngineInterface, raw: string): Promise<string> {
- const s = (await context($)).value
- const root = raw ? absoluteRoot(raw) : s.workspace
- await noLinks($, root, 'dir')
- const out = await $.process.run(['find', root, '-maxdepth', '7', '-name', 'preflight-report.json', '-not', '-path', '*/node_modules/*',
- '-not', '-path', '*/.*', '-printf', '%T@\\t%h\\n'], { cwd: s.workspace, timeoutMs: 30_000 })
- if (out.exitCode !== 0 && !out.stdout) throw new Error('Scan failed. It needs GNU find. ' + clean(out.stderr, 200))
- const now = Date.now()
- const entries = parseFound(out.stdout, 100).flatMap(row => {
- const place = splitDraft(row.path, s.workspace)
- return place ? [makeEntry(place.root, place.draft, now, 'scan', null, row.mtimeMs)] : []
- })
- if (!entries.length) return 'Blog Studio: no delivered drafts found under ' + clean(root, 120) + '.'
- await recordEntries($, entries)
- return 'Blog Studio: added ' + entries.length + ' draft' + (entries.length === 1 ? '' : 's') + ' from ' + clean(root, 120) + '. Run /blog-studio history.'
-}
-
-async function configure($: EngineInterface, raw: string): Promise<string> {
- const current = await context($)
- const s = current.value
- if (s.busy) throw new Error('Wait for the current check before configuring helpers.')
- if (raw.trim() === 'reset') {
- await $.store.delete(CONFIG)
- const pinned = await $.env.get('CLAUDE_BLOG_SCRIPTS_DIR')
- const cleared = { ...s, scripts: pinned ? absoluteScripts(pinned) : null, status: null, message: null, generation: s.generation + 1 }
- if (!(await $.state.set(REF, cleared, { ifVersion: current.version })).isSet) throw new Error('Configuration changed. Try again.')
- return 'Blog Studio: remembered engine location cleared.'
- }
- const scripts = absoluteScripts(raw)
- await noLinks($, scripts + '/' + HELPER, 'file')
- await noLinks($, scripts + '/' + CHECKER, 'file')
- const next = { ...s, scripts, status: null, message: null, generation: s.generation + 1 }
- if (!(await $.state.set(REF, next, { ifVersion: current.version })).isSet) throw new Error('Configuration changed. Try again.')
- await $.store.set(CONFIG, { scripts })
- return 'Trusted blog-engine helpers configured and remembered for every session. /blog-studio configure reset forgets them.'
-}
-
-async function uiAction($: EngineInterface, action: () => Promise<unknown>) {
- try { await action() } catch (error) {
- $.ui.toast(clean(error instanceof Error ? error.message : String(error)))
- }
-}
-
-function paneActions($: EngineInterface): PaneActions {
- return {
- refresh: async () => { await uiAction($, () => perform($, false)) },
- check: async () => { await uiAction($, () => perform($, true)) },
- useDetected: async () => {
- await uiAction($, async () => {
- const run = (await heldRun($)).value
- if (run.detected) await select($, run.detected)
- })
- },
- toggleSetup: async () => { await updateRun($, run => ({ ...run, setup: !run.setup })) },
- toggleHistory: async () => { await updateRun($, run => ({ ...run, historyOpen: !run.historyOpen })) },
- openEntry: async (id: string) => { await uiAction($, () => pick($, id)) },
- selectDraft: async value => { await uiAction($, () => select($, value)) },
- configureScripts: async value => { await uiAction($, () => configure($, value)) },
- close: async () => { await $.ui.close({ id: PANE }) },
- }
-}
-
-async function observe($: EngineInterface, signal: Signal | null) {
- if (!signal) return
- await updateRun($, run => reduce(run, signal, Date.now()))
- startTicker($)
-}
-
-export const register: Register = on => {
- on('session.start', async ($, e, next) => {
- const current = await context($)
- const s = current.value
- // Reload preserves selection but invalidates in-flight work and cached proof.
- await $.state.set(REF, { ...s, busy: false, status: null, message: null, generation: s.generation + 1 }, { ifVersion: current.version })
- try { if (!(await heldHistory($)).value.loaded) await loadHistory($) } catch { /* history is a convenience */ }
- try {
- await $.command.register({ name: 'blog-studio', description: 'Open the blog pipeline and delivery checks',
- argumentHint: '[status|select <directory>|open <n>|history [scan <folder>|forget <n>]|configure <scripts>|refresh|check|demo|reset]', immediate: true })
- } catch { $.ui.toast('Blog Studio could not register /blog-studio because the name is already taken.') }
- return next(e)
- })
- on('session.end', async ($, e, next) => {
- stopTicker()
- const current = await held($)
- await $.state.set(REF, { ...EMPTY, generation: current.value.generation + 1 })
- await $.state.set(RUN, emptyRun())
- return next(e)
- })
- on('turn.start', async ($, e, next) => {
- const current = await held($)
- if (current.value.draft && !current.value.busy) {
- await $.state.set(REF, { ...current.value, status: null, message: 'Refresh evidence after this turn.' }, { ifVersion: current.version })
- }
- return next(e)
- })
- on('turn.complete', async ($, e, next) => {
- if (!e.agentId) {
- stopTicker()
- try { await updateRun($, run => (run.startedAt === null ? run : pause(run, Date.now()))) } catch { /* display only */ }
- }
- const current = await held($)
- if (current.value.draft && !current.value.busy) await perform($, false)
- return next(e)
- })
- // Observers: read-only, no model calls, and they always fall through to the real call.
- on('skill.prompt', async ($, e, next) => {
- try { await observe($, skillSignal(e.skill)) } catch { /* display only */ }
- return next(e)
- })
- on('tool.call', async ($, e, next) => {
- let signal: Signal | null = null
- try {
- const run = (await heldRun($)).value
- const workspace = run.workspace || (await $.session.root()).replace(/\/$/, '')
- signal = classify(e.tool, e as unknown as Record<string, unknown>, workspace)
- await observe($, signal)
- if (signal?.kind === 'stage' && signal.draft && signal.draft !== run.detected) {
- await remember($, makeEntry(workspace || '/', signal.draft, Date.now(), 'observed'))
- }
- } catch { signal = null }
- const result = await next(e)
- if (signal?.kind === 'stage' && (signal.stage === 'render' || signal.stage === 'gates') &&
- (result as { isError?: boolean }).isError) {
- const stage = signal.stage
- try { await updateRun($, run => fail(run, stage, Date.now())) } catch { /* display only */ }
- }
- return result
- })
- on('command.run', { command: 'blog-studio' }, async ($, e) => {
- try {
- const input = e.args.trim()
- const space = input.indexOf(' ')
- const action = space < 0 ? input : input.slice(0, space)
- const value = space < 0 ? '' : input.slice(space + 1).trim()
- if (action === 'select') return { text: await select($, value) }
- if (action === 'configure') return { text: await configure($, value) }
- if (action === 'history') {
- if (value.startsWith('scan')) return { text: await scan($, value.slice(4).trim()) }
- if (value.startsWith('forget')) return { text: await forget($, value.slice(6).trim()) }
- return { text: historyText((await heldHistory($)).value.entries) }
- }
- if (action === 'open') return { text: await pick($, value) }
- if (action === 'demo') {
- await updateRun($, run => demoRun(run, Date.now()))
- startTicker($)
- return { text: 'Blog Studio: showing a sample pipeline. Run /blog-studio reset to clear it.' }
- }
- if (action === 'reset') {
- stopTicker()
- await updateRun($, run => ({ ...emptyRun(run.workspace, run.sessionId), setup: run.setup, historyOpen: run.historyOpen }))
- return { text: 'Blog Studio: pipeline cleared.' }
- }
- if (action === 'check' || action === 'refresh') return { text: await perform($, action === 'check') }
- const text = async () => {
- const s = (await context($)).value
- const run = (await heldRun($)).value
- return summary(s) + (run.startedAt === null ? '' : '\n' + pipelineLine(effective(run, s.status, s.busy, Date.now())))
- }
- if (action === 'status') return { text: await text() }
- if (action) return { text: 'Usage: /blog-studio [status|select <directory>|open <n>|history [scan <folder>|forget <n>]|configure <scripts>|refresh|check|demo|reset]' }
- const surfaces = await $.session.surfaces()
- if (!surfaces.some(surface => surface === 'terminal' || surface === 'desktop')) {
- return { text: (await text()) + '\nThis surface has no Blog Studio panel. Use the text subcommands.' }
- }
- const opened: unknown = await $.ui.open({ id: PANE, title: 'Blog Studio', focus: true, closeOnEscape: true })
- return opened && typeof opened === 'object' && 'isPlaced' in opened && opened.isPlaced === true ? {} : { text: (await text()) + '\nPanel unavailable. Use the text subcommands.' }
- } catch (error) { return { text: 'Blog Studio: ' + clean(error instanceof Error ? error.message : String(error)) } }
- })
- on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
- const s = (await held($)).value
- const run = (await heldRun($)).value
- const tracked = run.startedAt !== null
- if ((!s.draft && !tracked) || e.props.hasSurvey || e.props.maxRows < 2 || (e.surface !== 'terminal' && e.surface !== 'desktop')) return next(e)
- const ui = $.ui.resolve(e)
- const theirs = await next(e)
- const now = Date.now()
- const stages = effective(run, s.status, s.busy, now)
- const detail = e.props.maxRows >= 3 ? bandDetail(s, run, stages, e.props.bodyColumns) : null
- return ui.Box({ flexDirection: 'column', children: [theirs,
- ui.Box({ flexDirection: 'row', children: [
- ui.Box({ flexDirection: 'row', flexGrow: 1, children: bandRow(s, run, stages, e.props.bodyColumns - 14, now).map(seg => el(ui, seg)) }),
- ui.Button({ key: 'open-studio', label: 'Open (o)', hotkey: 'o', onPress: async () => {
- await uiAction($, () => $.ui.open({ id: PANE, title: 'Blog Studio', focus: true, closeOnEscape: true }))
- } }),
- ] }),
- ...(detail ? [el(ui, { t: detail, dim: true })] : []),
- ] })
- })
- on('ui.render', { component: 'Pane' }, async ($, e, next) => {
- if (e.requestId !== PANE || (e.surface !== 'terminal' && e.surface !== 'desktop')) return next(e)
- const s = (await held($)).value
- const run = (await heldRun($)).value
- const ui = $.ui.resolve(e)
- const now = Date.now()
- const history = (await heldHistory($)).value.entries
- return pane(ui, s, run, effective(run, s.status, s.busy, now), history, Math.max(24, e.props.bodyColumns - 2), now, paneActions($))
- })
-}
diff --git a/plugins/blog-studio/hooks/view.ts b/plugins/blog-studio/hooks/view.ts
deleted file mode 100644
index ab76950..0000000
--- a/plugins/blog-studio/hooks/view.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-import type { EngineInterface, ThemeKey } from 'claude-code'
-import type { HistoryEntry, RunState, StageId, StageState, Status, StudioState } from '../types'
-import { clean } from './logic'
-import { formatWhen, statusGlyph, title } from './history'
-import { STAGES } from './pipeline'
-
-type Full = Extract<ReturnType<EngineInterface['ui']['resolve']>, { Input: unknown }>
-type Ui = Pick<Full, 'Box' | 'Text' | 'Button'>
-type TextProps = Parameters<Ui['Text']>[0]
-
-export type Seg = { t: string; c?: ThemeKey; dim?: boolean; bold?: boolean }
-export type EffStage = {
- id: StageId; label: string; state: StageState; word: string; n: number; ms: number | null
- note: string | null; evidence: boolean
-}
-
-const rootOf = (s: StudioState) => s.projectRoot ?? s.workspace
-
-export const GLYPH: Record<StageState, string> = { done: '✓', active: '▸', failed: '✗', pending: '·' }
-const COLOR: Record<StageState, ThemeKey> = { done: 'success', active: 'claude', failed: 'error', pending: 'inactive' }
-const GATE_NAMES = ['Capability Discovery', 'Format Completeness', 'Visual Verification', 'Content Review', 'Asset + Link Integrity']
-const SPARK = '▁▂▃▄▅▆▇█'
-
-/** Collapses the same finding reported once per viewport into one line: "mobile + tablet: message". */
-export function groupViolations(list: string[]): string[] {
- const order: string[] = []
- const seen = new Map<string, string[]>()
- for (const v of list) {
- const m = /^(mobile|tablet|desktop(?:-dark)?):\s*([\s\S]*)$/.exec(v)
- const key = m?.[2] ?? v
- if (!seen.has(key)) { seen.set(key, []); order.push(key) }
- if (m?.[1]) seen.get(key)?.push(m[1])
- }
- return order.map(key => { const where = seen.get(key) ?? []; return where.length ? where.join(' + ') + ': ' + key : key })
-}
-
-export function bar(fraction: number, width: number): string {
- const w = Math.max(0, width)
- const filled = Math.max(0, Math.min(w, Math.round(fraction * w)))
- return '━'.repeat(filled) + '─'.repeat(w - filled)
-}
-
-export function spark(values: number[]): string {
- return values.slice(-8).map(v => SPARK[Math.max(0, Math.min(7, Math.floor(v / 12.5)))]).join('')
-}
-
-export function duration(ms: number | null): string {
- if (ms === null || ms < 0) return ''
- const total = Math.floor(ms / 1000)
- return Math.floor(total / 60) + ':' + String(total % 60).padStart(2, '0')
-}
-
-/** Combines what the agent was seen doing (inference) with what the preflight proved (evidence). */
-export function effective(run: RunState, status: Status | null, busy: boolean, now: number): EffStage[] {
- const gate = (n: number) => status?.gates.find(g => g.gate === n)
- const rows = STAGES.map(({ id, label }) => {
- const cur = run.stages[id]
- let state = cur.state
- let word = state === 'done' ? 'done' : state === 'active' ? (run.working ? 'working' : 'paused')
- : state === 'failed' ? 'failed' : 'waiting'
- let evidence = false
- if (status?.status === 'passed') { state = 'done'; word = 'verified'; evidence = true }
- else {
- const proved = (id === 'visuals' || id === 'render') ? gate(2)?.passed && gate(3)?.passed !== false
- : id === 'review' ? gate(4)?.passed : false
- if (proved && state !== 'done') { state = 'done'; word = 'verified'; evidence = true }
- if (id === 'gates') {
- if (busy) { state = 'active'; word = 'checking' }
- else if (status?.status === 'blocked' || status?.status === 'error') { state = 'failed'; word = status.status === 'error' ? 'error' : 'blocked' }
- else if (status?.status === 'stale') { state = 'pending'; word = 'stale' }
- else if (status?.status === 'partial') { state = 'active'; word = 'partial' }
- }
- }
- const ms = cur.startedAt === null ? null : (cur.endedAt ?? now) - cur.startedAt
- return { id, label, state, word, n: cur.n, ms: state === 'pending' ? null : ms, note: cur.note, evidence }
- })
- return rows
-}
-
-export function ratio(stages: EffStage[]): { done: number; fraction: number } {
- const done = stages.filter(s => s.state === 'done').length
- const active = stages.some(s => s.state === 'active') ? 0.5 : 0
- return { done, fraction: (done + active) / stages.length }
-}
-
-export function glyphRail(stages: EffStage[]): string {
- return stages.map(s => GLYPH[s.state]).join('')
-}
-
-export function pipelineLine(stages: EffStage[]): string {
- return 'Pipeline: ' + stages.map(s => GLYPH[s.state] + s.label).join(' ')
-}
-
-function chip(status: Status | null, busy: boolean): Seg {
- if (busy) return { t: 'Checking', c: 'claude' }
- const label = status?.label ?? 'Unverified'
- const c: ThemeKey = status?.status === 'passed' ? 'success' : status?.status === 'blocked' || status?.status === 'error' ? 'error'
- : status?.status === 'stale' || status?.status === 'partial' ? 'warning' : 'inactive'
- return { t: label, c }
-}
-
-export function el(ui: Ui, seg: Seg, wrap: 'truncate-end' | 'wrap' = 'truncate-end') {
- const props: TextProps = { wrap, children: [seg.t] }
- if (seg.c) props.color = seg.c
- if (seg.dim) props.dimColor = true
- if (seg.bold) props.bold = true
- return ui.Text(props)
-}
-
-function row(ui: Ui, segs: Seg[], gap = 0) {
- return ui.Box({ flexDirection: 'row', gap, children: segs.map(s => el(ui, s)) })
-}
-
-function railSegs(stages: EffStage[], labels: boolean): Seg[] {
- const out: Seg[] = []
- stages.forEach((s, i) => {
- out.push({ t: GLYPH[s.state] + (labels ? ' ' + s.label : ''), c: COLOR[s.state], bold: s.state === 'active' })
- if (labels && i < stages.length - 1) out.push({ t: ' ' })
- })
- return out
-}
-
-/** One band row. Wide: bar, labelled rail, clock. Medium: bar, glyph rail. Narrow: glyph rail and stage. */
-export function bandRow(s: StudioState, run: RunState, stages: EffStage[], columns: number, now: number): Seg[] {
- const tracked = run.startedAt !== null
- const status = s.status
- const clock = tracked ? duration((run.endedAt ?? now) - (run.startedAt ?? now)) : ''
- const title: Seg[] = [{ t: 'Blog ', c: 'claude', bold: true }]
- if (!tracked) {
- const c = chip(status, s.busy)
- return [...title, { t: '▎ ', c: 'inactive' }, { t: clean(s.draft ?? '', Math.max(8, columns - 40)), dim: true },
- { t: ' ' }, c, { t: ' ' + (status?.passed_count ?? 0) + '/5', dim: true }]
- }
- const { done, fraction } = ratio(stages)
- const active = stages.find(x => x.state === 'active') ?? [...stages].reverse().find(x => x.state === 'failed')
- const where: Seg = active
- ? { t: ' ' + active.label + (active.state === 'failed' ? ' failed' : run.working ? '' : ' (paused)'), c: COLOR[active.state], bold: true }
- : { t: done === stages.length ? ' complete' : '', c: 'success', bold: true }
- const count: Seg = { t: ' ' + done + '/' + stages.length, dim: true }
- const time: Seg = { t: clock ? ' ' + clock : '', dim: true }
- if (columns >= 100) {
- return [...title, { t: bar(fraction, 10), c: 'claude' }, count, { t: ' ' }, ...railSegs(stages, true), time]
- }
- if (columns >= 62) {
- return [...title, { t: bar(fraction, 8), c: 'claude' }, count, { t: ' ' }, ...railSegs(stages, false), where, time]
- }
- return [...title, ...railSegs(stages, false), where]
-}
-
-/** Dim second line: the newest thing seen, or the first thing blocking delivery. */
-export function bandDetail(s: StudioState, run: RunState, stages: EffStage[], columns: number): string | null {
- const blocker = s.status?.gates.find(g => !g.passed)?.violations[0]
- if (blocker && !s.busy) return clean('✗ ' + blocker, Math.max(8, columns))
- const current = stages.find(x => x.state === 'active')
- if (current?.note) return clean('▸ ' + current.label + ' · ' + current.note, Math.max(8, columns))
- return null
-}
-
-export type PaneActions = {
- refresh: () => Promise<void>; check: () => Promise<void>; useDetected: () => Promise<void>
- toggleSetup: () => Promise<void>; toggleHistory: () => Promise<void>; openEntry: (id: string) => Promise<void>; selectDraft: (value: string) => Promise<void>
- configureScripts: (value: string) => Promise<void>; close: () => Promise<void>
-}
-
-export function pane(ui: Full, s: StudioState, run: RunState, stages: EffStage[], history: HistoryEntry[], width: number, now: number, act: PaneActions) {
- const W = Math.max(24, width)
- const status = s.status
- const { done, fraction } = ratio(stages)
- const tracked = run.startedAt !== null
- const active = stages.find(x => x.state === 'active') ?? [...stages].reverse().find(x => x.state === 'failed')
- const elapsed = tracked ? duration((run.endedAt ?? now) - (run.startedAt ?? now)) : ''
- const rule = (label: string, right = ''): ReturnType<Ui['Box']> => {
- const fill = Math.max(2, W - label.length - right.length - 4)
- return row(ui, [{ t: label, c: 'claude', bold: true }, { t: ' ' + '─'.repeat(fill) + ' ', c: 'inactive' }, { t: right, dim: true }])
- }
- const children: ReturnType<Ui['Box']>[] = []
-
- children.push(ui.Box({ flexDirection: 'row', justifyContent: 'space-between', children: [
- el(ui, { t: '✎ Blog Studio', c: 'claude', bold: true }),
- el(ui, active ? { t: (active.state === 'failed' ? '✗ ' : run.working ? '▸ ' : '❚❚ ') + active.label + (elapsed ? ' · ' + elapsed : ''),
- c: COLOR[active.state] } : { t: tracked ? 'complete' + (elapsed ? ' · ' + elapsed : '') : 'idle', c: tracked ? 'success' : 'inactive' }),
- ] }))
- children.push(row(ui, [{ t: bar(fraction, Math.max(10, W - 16)), c: 'claude' },
- { t: ' ' + done + '/' + stages.length + ' · ' + Math.round(fraction * 100) + '%', dim: true }]))
-
- children.push(rule('PIPELINE', tracked ? 'what the agent is doing, inferred' : 'starts when the agent begins a blog'))
- const noteRoom = Math.max(0, W - 36)
- for (const st of stages) {
- const segs: Seg[] = [
- { t: GLYPH[st.state] + ' ', c: COLOR[st.state], bold: st.state === 'active' },
- { t: st.label.padEnd(9), c: st.state === 'pending' ? 'inactive' : 'text', bold: st.state === 'active' },
- { t: st.word.padEnd(9), c: COLOR[st.state] },
- { t: (st.n && !st.evidence ? '×' + st.n : '').padEnd(5), dim: true },
- { t: duration(st.ms).padEnd(6), dim: true },
- ]
- if (st.state === 'active' && st.note && noteRoom > 8) segs.push({ t: clean(st.note, noteRoom), dim: true })
- children.push(row(ui, segs))
- }
-
- const failedCount = status?.gates.filter(g => !g.passed).length ?? 0
- const passedCount = status?.passed_count ?? 0
- children.push(rule('DELIVERY GATES', status ? '✓' + passedCount + ' ✗' + failedCount + ' ·' + (5 - passedCount - failedCount) : 'not checked'))
- for (let n = 1; n <= 5; n++) {
- const g = status?.gates.find(x => x.gate === n)
- const state: StageState = g ? (g.passed ? 'done' : 'failed') : 'pending'
- children.push(row(ui, [{ t: GLYPH[state] + ' ', c: COLOR[state] }, { t: n + ' ', dim: true },
- { t: clean(g?.name ?? GATE_NAMES[n - 1] ?? '', W - 6),
- c: g ? 'text' : 'inactive' }]))
- if (g?.score != null) {
- const ok = g.score >= 90
- const barWidth = Math.max(8, Math.min(24, W - 34))
- children.push(row(ui, [{ t: ' ' }, { t: bar(g.score / 100, barWidth), c: ok ? 'success' : 'warning' },
- { t: ' ' + g.score + '/100', c: ok ? 'success' : 'warning', bold: true }, { t: ' needs 90', dim: true },
- ...(run.scores.length > 1 ? [{ t: ' ' + spark(run.scores), c: 'claude' as ThemeKey }] : [])]))
- }
- const blockers = groupViolations(g?.violations ?? [])
- for (const v of blockers.slice(0, 3)) children.push(el(ui, { t: ' ✗ ' + clean(v, 300), c: 'error' }, 'wrap'))
- if (blockers.length > 3) children.push(el(ui, { t: ' +' + (blockers.length - 3) + ' more', dim: true }))
- for (const v of groupViolations(g?.warnings ?? []).slice(0, 2)) children.push(el(ui, { t: ' ! ' + clean(v, 300), c: 'warning', dim: true }, 'wrap'))
- }
- if (status?.diagnostics.length) for (const d of status.diagnostics.slice(0, 3)) children.push(el(ui, { t: '! ' + clean(d, 400), c: 'warning' }, 'wrap'))
- if (s.message && !s.busy) children.push(el(ui, { t: clean(s.message, 400), dim: true }, 'wrap'))
-
- children.push(rule('DRAFT'))
- children.push(row(ui, [{ t: s.draft ? clean(s.draft, W - 4) : 'none selected', c: s.draft ? 'text' : 'warning' }]))
- if (s.projectRoot) children.push(el(ui, { t: 'project ' + clean(s.projectRoot, Math.max(8, W - 10)), dim: true }))
- if (s.draft) {
- const when = status?.checked_at?.match(/T(\d\d:\d\d)/)?.[1]
- children.push(row(ui, [chip(status, s.busy), { t: ' · ' + passedCount + '/5 gates · last check ' + (when ? when + 'Z' : 'never'), dim: true }]))
- }
- if (status?.artifacts.length) {
- const names = status.artifacts.slice(0, 6).map(a => clean(a, 40))
- children.push(el(ui, { t: 'files ' + names.join(', ') + (status.artifacts.length > 6 ? ' +' + (status.artifacts.length - 6) : ''), dim: true }, 'wrap'))
- }
- if (run.detected && run.detected !== s.draft) {
- children.push(ui.Box({ flexDirection: 'row', gap: 1, children: [
- el(ui, { t: 'seen: ' + clean(run.detected, Math.max(8, W - 24)), dim: true }),
- ui.Button({ key: 'use-detected', label: 'Use this draft (u)', hotkey: 'u', onPress: act.useDetected }),
- ] }))
- }
-
- if (s.busy) {
- children.push(el(ui, { t: '◐ ' + clean(s.message ?? 'Working...', 80) + ' (buttons are off until it finishes)', c: 'claude' }, 'wrap'))
- } else {
- children.push(ui.Box({ flexDirection: W < 48 ? 'column' : 'row', gap: 1, children: [
- ...(s.draft ? [
- ui.Button({ key: 'refresh', label: 'Refresh (r)', hotkey: 'r', onPress: act.refresh }),
- ui.Button({ key: 'check', label: 'Run checks (c)', hotkey: 'c', variant: 'primary', onPress: act.check }),
- ] : []),
- ui.Button({ key: 'setup', label: (run.setup ? 'Hide settings' : 'Settings') + ' (s)', hotkey: 's', dimColor: true, onPress: act.toggleSetup }),
- ui.Button({ key: 'close', label: 'Close', role: 'dismiss', dimColor: true, onPress: act.close }),
- ] }))
- children.push(rule('RECENT BLOGS', history.length ? history.length + ' saved' : ''))
- if (!history.length) {
- children.push(el(ui, { t: 'None yet. Blogs appear as the agent writes them. Backfill: /blog-studio history scan <folder>', dim: true }, 'wrap'))
- } else {
- const shown = history.slice(0, run.historyOpen ? 25 : 5)
- shown.forEach((e, i) => {
- const current = e.root === rootOf(s) && e.draft === s.draft
- const label = (i + 1) + ' ' + formatWhen(e.lastSeen) + ' ' + statusGlyph(e.status) + ' ' + clean(title(e), Math.max(8, W - 26)) +
- (e.status ? ' ' + e.passed + '/5' : '')
- children.push(ui.Button({ key: 'hist-' + e.id, label, ...(i < 9 ? { hotkey: String(i + 1) } : {}),
- ...(current ? { variant: 'primary' as const } : { dimColor: true }), onPress: () => act.openEntry(e.id) }))
- })
- if (history.length > 5) children.push(ui.Button({ key: 'hist-toggle', label: (run.historyOpen ? 'Fewer' : 'All ' + history.length + ' blogs') + ' (h)',
- hotkey: 'h', dimColor: true, onPress: act.toggleHistory }))
- }
- if (!s.draft || !s.scripts || run.setup) {
- children.push(rule('SETTINGS'))
- children.push(ui.Input({ key: 'draft', label: 'Draft folder', placeholder: 'outputs/article', onSubmit: act.selectDraft }))
- children.push(ui.Input({ key: 'scripts', label: 'Engine scripts', placeholder: s.scripts ? clean(s.scripts, 60) : '/path/to/claude-blog/scripts',
- onSubmit: act.configureScripts }))
- }
- }
- return ui.Box({ flexDirection: 'column', gap: 0, children })
-}
diff --git a/plugins/blog-studio/package-lock.json b/plugins/blog-studio/package-lock.json
deleted file mode 100644
index 8d14992..0000000
--- a/plugins/blog-studio/package-lock.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "name": "blog-studio-dev",
- "version": "0.2.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "blog-studio-dev",
- "version": "0.2.0",
- "devDependencies": {
- "typescript": "5.9.3"
- }
- },
- "node_modules/typescript": {
- "version": "5.9.3",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
- "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc",
- "tsserver": "bin/tsserver"
- },
- "engines": {
- "node": ">=14.17"
- }
- }
- }
-}
diff --git a/plugins/blog-studio/package.json b/plugins/blog-studio/package.json
deleted file mode 100644
index d15f299..0000000
--- a/plugins/blog-studio/package.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "name": "blog-studio-dev",
- "version": "0.2.0",
- "private": true,
- "type": "module",
- "scripts": {
- "typecheck:reference": "node dev/reference-types.mjs && tsc -p tsconfig.reference.json",
- "typecheck:native": "node dev/native-types.mjs && tsc -p tsconfig.json",
- "test": "claude plugin test ."
- },
- "devDependencies": {
- "typescript": "5.9.3"
- }
-}
diff --git a/plugins/blog-studio/tests/studio.test.ts b/plugins/blog-studio/tests/studio.test.ts
deleted file mode 100644
index 34c58ad..0000000
--- a/plugins/blog-studio/tests/studio.test.ts
+++ /dev/null
@@ -1,611 +0,0 @@
-import { expect, mock, test } from 'claude-code/testing'
-import type { On } from 'claude-code'
-import { absoluteScripts, clean, jsonResponse, parseStatus, relativeDraft } from '../hooks/logic'
-import { classify, doneCount, emptyRun, fail, reduce, skillSignal } from '../hooks/pipeline'
-import { entryId, formatWhen, title, makeEntry, mergeEntries, parseFound, sortEntries, splitDraft, validEntry } from '../hooks/history'
-import { bandRow, bar, duration, effective, groupViolations, spark } from '../hooks/view'
-
-const THEME_KEYS = new Set(['text', 'inverseText', 'inactive', 'subtle', 'suggestion', 'remember', 'success', 'error', 'warning', 'merged', 'claude', 'permission', 'planMode', 'autoAccept', 'promptBorder', 'bashBorder', 'ide'])
-const RUN = { origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 80 } } as const
-// Mirrors the host's ProcessRunResult: truncation flags are always present.
-const done = (r: { exitCode: number; stdout: string; stderr: string; isStdoutTruncated?: boolean }) =>
- ({ isStdoutTruncated: false, isStderrTruncated: false, ...r })
-const PANE = { plugin: 'blog-studio', component: 'Pane', requestId: 'blog-studio-review',
- viewport: { columns: 80, rows: 30, isFullscreen: false },
- props: { title: 'Blog Studio', isFocused: true, bodyColumns: 70, placement: 'inline',
- scroll: { offset: 0, bodyRows: 20 }, view: {} } } as const
-const BAND = { plugin: 'blog-studio', component: 'AbovePrompt',
- viewport: { columns: 80, rows: 30, isFullscreen: false },
- props: { hasSurvey: false, isWorking: false, maxRows: 3, bodyColumns: 80,
- scroll: { offset: 0, bodyRows: 3 }, view: {} } } as const
-const PASS = {
- schema_version: 1, status: 'passed', label: 'Preflight passed', checked_at: '2026-10-08T10:00:00+00:00',
- passed_count: 5, run_id: 'a'.repeat(32), diagnostics: [], artifacts: ['article.md', 'hero.webp', 'preview/desktop.png'],
- gates: [1, 2, 3, 4, 5].map(n => ({ gate: n, name: 'Fixture gate', passed: true, violations: [], warnings: [], score: n === 4 ? 90 : null })),
-}
-
-function host(on: On, options: { surface?: 'terminal' | 'desktop' | null; link?: string; collision?: boolean; missing?: string; absent?: string; env?: string | null; store?: Record<string, unknown>; workspace?: () => string; sessionId?: () => string } = {}) {
- const opened: string[] = []
- const messages: string[] = []
- on('session.start', ($, e) => ({ cwd: e.cwd }))
- on('session.end', ($, e) => ({ sessionId: e.sessionId }))
- on('session.root', () => ({ value: options.workspace?.() ?? '/work' }))
- on('session.id', () => ({ value: options.sessionId?.() ?? 'fixture-session' }))
- on('session.surfaces', () => ({ value: options.surface === null ? [] : [options.surface ?? 'terminal'] }))
- mock.store(on, options.store)
- on('env.get', () => ({ value: options.env === undefined ? '/trusted/scripts' : options.env ?? undefined }))
- on('command.register', ($, e) => options.collision ? { deny: 'taken' } : { value: { command: e.name } })
- on('fs.stat', ($, e) => {
- if (e.path === options.absent) throw new Error('ENOENT: no such file or directory')
- return { value: { kind: e.path === options.missing ? 'other' : e.path.endsWith('.py') ? 'file' : 'dir',
- size: 10, mtimeMs: 0, isLink: e.path === options.link } }
- })
- on('ui.open', ($, e) => { opened.push(e.id); return { value: { isPlaced: true } } })
- on('ui.close', () => ({ value: undefined }))
- on('ui.toast', ($, e) => { messages.push(e.text); return { value: undefined } })
- on('tool.list', () => ({ value: [] }))
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['Other mod'] }))
- return { opened, messages }
-}
-
-for (const surface of ['terminal', 'desktop'] as const) {
- for (const width of [32, 80, 160]) {
- test('panel controls and five gates on ' + surface + ' at ' + width + ' columns', async ($, on) => {
- const h = host(on, { surface })
- on('process.run', () => ({ value: done({ exitCode: 0, stdout: JSON.stringify(PASS), stderr: '' }) }))
- await $.session.start({ cwd: '/work', surface, isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: '', ...RUN })
- expect(h.opened).toEqual(['blog-studio-review'])
- const ui = await $.ui.mount({ ...PANE, surface, props: { ...PANE.props, bodyColumns: width } })
- expect(await ui.find({ key: 'draft' })).toBeDefined()
- await ui.input({ key: 'draft', text: 'outputs/article' })
- await ui.press({ key: 'refresh' })
- expect(await ui.find({ type: 'Text', text: /Preflight passed/ })).toBeDefined()
- expect(await ui.findAll({ type: 'Text', text: 'Fixture gate' })).toHaveLength(5)
- expect(await ui.find({ type: 'Text', text: /90\/100/ })).toBeDefined()
- expect(await ui.find({ type: 'Text', text: /hero\.webp/ })).toBeDefined()
- // Colors must be host theme keys so light and dark both work: never hex values or ANSI names.
- const drawn = JSON.stringify(await ui.drawn())
- const colors = [...drawn.matchAll(/"(?:color|backgroundColor|borderColor)":"([^"]*)"/g)].map(m => m[1] ?? '')
- expect(colors.length).toBeGreaterThan(0)
- expect(colors.filter(c => !THEME_KEYS.has(c))).toEqual([])
- await ui.press({ key: 'close' })
- await ui.unmount()
- })
- }
-}
-
-test('band preserves another mod and yields to surveys and tiny slots', async ($, on) => {
- host(on)
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- let band = await $.ui.mount({ ...BAND, surface: 'terminal' })
- expect(await band.find({ type: 'Text', text: 'Other mod' })).toBeDefined()
- expect(await band.find({ key: 'open-studio' })).toBeUndefined()
- await band.unmount()
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- band = await $.ui.mount({ ...BAND, surface: 'terminal' })
- expect(await band.find({ type: 'Text', text: 'Other mod' })).toBeDefined()
- expect(await band.find({ key: 'open-studio' })).toBeDefined()
- await band.press({ key: 'open-studio' })
- await band.unmount()
- for (const props of [{ ...BAND.props, hasSurvey: true }, { ...BAND.props, maxRows: 1 }]) {
- const survey = await $.ui.mount({ ...BAND, surface: 'terminal', props })
- expect(await survey.find({ key: 'open-studio' })).toBeUndefined()
- await survey.unmount()
- }
-})
-
-test('Run checks button executes the checker and inspector, then redraws', async ($, on) => {
- host(on)
- const calls: string[] = []
- on('process.run', ($, e) => {
- 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 })
- const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })
- await ui.input({ key: 'draft', text: 'outputs/article' })
- await ui.press({ key: 'check' })
- expect(calls).toEqual(['/trusted/scripts/blog_preflight.py', '/trusted/scripts/blog_studio_status.py'])
- expect(await ui.find({ type: 'Text', text: /Preflight passed/ })).toBeDefined()
- await ui.unmount()
-})
-
-for (const missing of ['/trusted/scripts/blog_studio_status.py', '/trusted/scripts/blog_preflight.py']) {
- test('missing trusted helper cannot execute: ' + missing, async ($, on) => {
- host(on, { missing })
- let calls = 0
- on('process.run', () => { calls++; throw new Error('must not run') })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- const result = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- expect(result).toMatchObject({ text: expect.stringContaining('Execution error') })
- expect(calls).toBe(0)
- })
-}
-
-for (const status of ['blocked', 'partial', 'stale', 'unverified', 'error']) {
- test('refresh preserves nonpassing inspector status: ' + status, async ($, on) => {
- host(on)
- on('process.run', () => ({ value: done({ exitCode: status === 'error' ? 1 : 0, stderr: '',
- stdout: JSON.stringify({ ...PASS, status, passed_count: 0,
- gates: [{ gate: 1, name: 'Capability', passed: false, score: null, violations: ['Missing browser'], warnings: [] }] }) }) }))
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- const result = await $.command.run({ command: 'blog-studio', args: 'refresh', ...RUN })
- expect(result).not.toMatchObject({ text: expect.stringContaining('Preflight passed') })
- const band = await $.ui.mount({ ...BAND, surface: 'terminal' })
- expect(await band.find({ type: 'Text', text: /Missing browser/ })).toBeDefined()
- await band.unmount()
- })
-}
-
-const STUDIO = { workspace: '/work', sessionId: 'fixture', scripts: '/trusted', draft: 'article', generation: 1, projectRoot: null, busy: false,
- message: null, status: PASS as never } as const
-
-test('idle band keeps draft, status and gate count', () => {
- const run = emptyRun('/work', 'fixture')
- const text = bandRow(STUDIO, run, effective(run, PASS as never, false, 0), 80, 0).map(x => x.t).join('')
- expect(text).toContain('article')
- expect(text).toContain('Preflight passed')
- expect(text).toContain('5/5')
-})
-
-for (const columns of [24, 40, 62, 100, 140]) {
- test('running band fits and keeps the stage rail at ' + columns + ' columns', () => {
- let run = reduce(emptyRun('/work', 'fixture'), { kind: 'start', skill: 'blog-write' }, 0)
- run = reduce(run, { kind: 'stage', stage: 'research', note: 'r' }, 1000)
- run = reduce(run, { kind: 'stage', stage: 'draft', note: 'd' }, 61_000)
- const idle = { ...STUDIO, status: null }
- const text = bandRow(idle, run, effective(run, null, false, 62_000), columns, 62_000).map(x => x.t).join('')
- expect(text.length).toBeLessThanOrEqual(Math.max(columns, 30))
- expect(text).toContain('✓')
- expect(text).toContain('▸')
- expect(text).toContain('Draft')
- })
-}
-
-test('verified gate evidence completes stages the agent was only inferred to run', () => {
- const run = reduce(emptyRun('/work', 'fixture'), { kind: 'stage', stage: 'draft', note: 'd' }, 0)
- const stages = effective(run, PASS as never, false, 5)
- expect(stages.every(x => x.state === 'done' && x.word === 'verified')).toBe(true)
-})
-
-test('malformed JSON errors do not echo article or helper output', () => {
- expect(() => jsonResponse('private article body')).toThrow()
- try { jsonResponse('private article body') } catch (error) {
- expect(String(error)).not.toContain('private article body')
- }
-})
-
-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[2]?.endsWith('blog_preflight.py')
- const broken = stage === 'checker' ? isChecker : !isChecker
- return { 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,
- draft: '/work/outputs/article', evidence: { run_id: PASS.run_id } }) }) }
- })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- const result = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- expect(result).toMatchObject({ text: expect.stringContaining('Missing browser') })
- expect(result).not.toMatchObject({ text: expect.stringContaining('private article body') })
- expect(result).not.toMatchObject({ text: expect.stringContaining('/var/home/owner') })
- expect(result).not.toMatchObject({ text: expect.stringContaining('c'.repeat(32)) })
- })
-}
-
-test('same-session reload preserves selection but invalidates proof', async ($, on) => {
- host(on)
- on('process.run', () => ({ value: done({ exitCode: 0, stdout: JSON.stringify(PASS), stderr: '' }) }))
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- await $.command.run({ command: 'blog-studio', args: 'refresh', ...RUN })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- const out = await $.command.run({ command: 'blog-studio', args: 'status', ...RUN })
- expect(out).toMatchObject({ text: expect.stringContaining('outputs/article | Unverified') })
-})
-
-test('branch into another session clears selection', async ($, on) => {
- let sessionId = 'fixture-session'
- host(on, { sessionId: () => sessionId })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- sessionId = 'branched-session'
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- const out = await $.command.run({ command: 'blog-studio', args: 'status', ...RUN })
- expect(out).toMatchObject({ text: expect.stringContaining('select a draft') })
-})
-
-test('check invokes strict canonical script with no shell then verifies run identity', async ($, on) => {
- host(on)
- const calls: string[][] = []
- const 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[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, 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'])
-})
-
-for (const failure of ['timeout', 'malformed', 'truncated', 'wrong-exit', 'missing-report']) {
- test('check failure stays visible: ' + failure, async ($, on) => {
- host(on)
- on('process.run', () => {
- if (failure === 'timeout') throw new Error('python3 unavailable or process timed out')
- 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' }) }
- })
- 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('Execution error') })
- expect(out).not.toMatchObject({ text: expect.stringContaining('Preflight passed') })
- })
-}
-
-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 })
- let calls = 0
- on('process.run', () => { calls++; throw new Error('must not run') })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- expect(calls).toBe(0)
- })
-}
-
-test('selecting a nonexistent draft gives the plain path message, not a raw filesystem error', async ($, on) => {
- host(on, { absent: '/work/outputs/nonexistent' })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- const result = await $.command.run({ command: 'blog-studio', args: 'select outputs/nonexistent', ...RUN })
- expect(result).toMatchObject({ text: expect.stringContaining('Missing or unsafe path') })
- expect(JSON.stringify(result)).not.toContain('ENOENT')
-})
-
-test('headless commands return text without opening a pane', async ($, on) => {
- const h = host(on, { surface: null })
- await $.session.start({ cwd: '/work', surface: null, isInteractive: false })
- const out = await $.command.run({ command: 'blog-studio', args: '', ...RUN })
- expect(out).toMatchObject({ text: expect.stringContaining('text subcommands') })
- expect(h.opened).toEqual([])
-})
-
-test('registration collision still returns session.start and reports the problem', async ($, on) => {
- const h = host(on, { collision: true })
- const out = await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- expect(out).toMatchObject({ cwd: '/work' })
- expect(h.messages).toHaveLength(1)
-})
-
-test('path parsers refuse traversal and diagnostics do not reveal nonces or controls', () => {
- for (const path of ['../escape', '/outside', 'a/../escape', 'a//b', './a', 'a\\b', '']) {
- expect(() => relativeDraft(path)).toThrow()
- }
- expect(relativeDraft('outputs/article with spaces')).toBe('outputs/article with spaces')
- expect(() => absoluteScripts('/trusted/../draft')).toThrow()
- const secret = 'b'.repeat(32)
- expect(clean('\x1b[31mNonce: ' + secret)).not.toContain(secret)
- expect(clean('\x1b[31mtext')).not.toContain('\x1b')
- expect(clean('private /var/home/owner/file')).not.toContain('/var/home/owner')
-})
-
-test('malformed and contradictory status cannot pass', () => {
- for (const raw of ['null', '{}', '{broken', JSON.stringify({ ...PASS, status: 'toString' }),
- JSON.stringify({ ...PASS, passed_count: 4 }), JSON.stringify({ ...PASS, gates: PASS.gates.slice(0, 4) })]) {
- expect(() => parseStatus(raw)).toThrow()
- }
-})
-
-for (const reason of ['clear', 'resume'] as const) {
- test('selection cleared on session ' + reason, async ($, on) => {
- host(on)
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- await $.session.end({ reason, sessionId: 'fixture-session', resume: { id: 'fixture-session' } })
- const status = await $.command.run({ command: 'blog-studio', args: 'status', ...RUN })
- expect(status).toMatchObject({ text: expect.stringContaining('select a draft') })
- })
-}
-
-test('workspace switch clears selection', async ($, on) => {
- let workspace = '/work'
- host(on, { workspace: () => workspace })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- workspace = '/another-project'
- const status = await $.command.run({ command: 'blog-studio', args: 'status', ...RUN })
- expect(status).toMatchObject({ text: expect.stringContaining('select a draft') })
-})
-
-for (const change of ['clear', 'workspace'] as const) {
- test('late completion discarded after ' + change + ', duplicate check refused', async ($, on) => {
- let workspace = '/work'
- host(on, { workspace: () => workspace })
- let release: (() => void) | undefined
- let began: (() => void) | undefined
- const started = new Promise<void>(resolve => { began = resolve })
- const waiting = new Promise<void>(resolve => { release = resolve })
- let calls = 0
- on('process.run', async () => {
- calls++
- if (calls === 1) { began?.(); await waiting }
- return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(calls === 1 ?
- { 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 check = $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- await started
- const duplicate = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- expect(duplicate).toMatchObject({ text: 'Checks are already running.' })
- if (change === 'clear') await $.session.end({ reason: 'clear', sessionId: 'fixture-session', resume: { id: 'fixture-session' } })
- else workspace = '/another-project'
- release?.()
- const result = await check
- expect(result).toMatchObject({ text: expect.stringContaining('discarded') })
- const status = await $.command.run({ command: 'blog-studio', args: 'status', ...RUN })
- expect(status).not.toMatchObject({ text: expect.stringContaining('Preflight passed') })
- })
-}
-
-test('trusted configuration is explicit and selected draft helpers cannot execute', async ($, on) => {
- host(on)
- let calls = 0
- on('process.run', () => { calls++; throw new Error('must not run') })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- await $.command.run({ command: 'blog-studio', args: 'configure /work/outputs/article/scripts', ...RUN })
- const out = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- expect(out).toMatchObject({ text: expect.stringContaining('Execution error') })
- expect(calls).toBe(0)
-})
-
-test('classifier maps blog tool calls to ordered stages and ignores everything else', () => {
- const at = (tool: string, input: Record<string, unknown>) => classify(tool, input, '/work')
- expect(at('WebSearch', { query: 'x' })).toMatchObject({ kind: 'stage', stage: 'research' })
- expect(at('WebFetch', { url: 'https://example.com/a' })).toMatchObject({ stage: 'research', note: 'read example.com' })
- expect(at('Agent', { subagent_type: 'claude-blog:blog-reviewer' })).toMatchObject({ stage: 'review' })
- expect(at('Agent', { subagent_type: 'general-purpose' })).toBeNull()
- expect(at('Write', { file_path: '/work/out/post/outline.md' })).toMatchObject({ stage: 'outline' })
- expect(at('Write', { file_path: '/work/out/post/post.md' })).toMatchObject({ stage: 'draft', draft: 'out/post' })
- expect(at('Write', { file_path: '/work/BRAND.md' })).toBeNull()
- expect(at('Write', { file_path: '/elsewhere/post.md' })).toMatchObject({ stage: 'draft' })
- expect((at('Write', { file_path: '/elsewhere/post.md' }) as { draft?: string }).draft).toBeUndefined()
- expect(at('Write', { file_path: '/work/out/post/chart.svg' })).toMatchObject({ stage: 'visuals' })
- expect(at('Write', { file_path: '/work/out/post/review.md' })).toMatchObject({ stage: 'review' })
- expect(at('Bash', { command: 'python3 s/generate_hero.py --x' })).toMatchObject({ stage: 'visuals' })
- expect(at('Bash', { command: 'python3 s/blog_render.py --md a.md' })).toMatchObject({ stage: 'render' })
- expect(at('Bash', { command: 'python3 s/blog_preflight.py --draft d' })).toMatchObject({ stage: 'gates' })
- expect(at('Bash', { command: 'ls -la' })).toBeNull()
- expect(at('Read', { file_path: '/work/a.md' })).toBeNull()
- expect(skillSignal('claude-blog:blog-write')).toMatchObject({ kind: 'start' })
- expect(skillSignal('claude-blog:blog-outline')).toMatchObject({ stage: 'outline' })
- expect(skillSignal('commit')).toBeNull()
-})
-
-test('stages advance in order, finish earlier work, allow revisits, and restart on a new run', () => {
- let run = reduce(emptyRun('/work', 's'), { kind: 'start', skill: 'blog-write' }, 1000)
- run = reduce(run, { kind: 'stage', stage: 'research', note: 'a' }, 2000)
- run = reduce(run, { kind: 'stage', stage: 'draft', note: 'b' }, 5000)
- expect(run.stages.research).toMatchObject({ state: 'done', endedAt: 5000, n: 1 })
- expect(run.stages.draft).toMatchObject({ state: 'active', startedAt: 5000 })
- expect(run.stages.outline.state).toBe('pending')
- run = reduce(run, { kind: 'stage', stage: 'research', note: 'again' }, 6000)
- expect(run.stages.research).toMatchObject({ state: 'active', n: 2 })
- expect(doneCount(run)).toBe(0)
- run = fail(run, 'research', 7000)
- expect(run.stages.research.state).toBe('failed')
- run = reduce(run, { kind: 'start', skill: 'blog-rewrite' }, 9000)
- expect(run.stages.research.state).toBe('pending')
- expect(run.startedAt).toBe(9000)
-})
-
-test('view helpers stay inside their bounds', () => {
- expect(bar(0.5, 10)).toBe('━━━━━─────')
- expect(bar(2, 4)).toBe('━━━━')
- expect(bar(-1, 4)).toBe('────')
- expect(spark([0, 50, 100])).toBe('▁▅█')
- expect(duration(75_000)).toBe('1:15')
- expect(duration(null)).toBe('')
-})
-
-test('observers follow the agent through real hooks and never block a tool call', async ($, on) => {
- host(on)
- on('tool.call', () => ({ result: 'ok' }))
- on('process.run', () => ({ value: done({ exitCode: 0, stdout: JSON.stringify(PASS), stderr: '' }) }))
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.tool.call({ tool: 'WebSearch', query: 'topic', mode: 'standard' })
- const written = await $.tool.call({ tool: 'Write', file_path: '/work/outputs/post/post.md', content: 'x' })
- expect(written).toMatchObject({ result: 'ok' })
- const band = await $.ui.mount({ ...BAND, surface: 'terminal' })
- expect(await band.find({ type: 'Text', text: /Draft/ })).toBeDefined()
- expect(await band.find({ type: 'Text', text: /2\/7|1\/7/ })).toBeDefined()
- await band.unmount()
- const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })
- expect(await ui.find({ key: 'use-detected' })).toBeDefined()
- await ui.press({ key: 'use-detected' })
- expect(await ui.find({ key: 'check' })).toBeDefined()
- await ui.unmount()
-})
-
-test('a failing render marks that stage failed without changing the tool result', async ($, on) => {
- host(on)
- on('tool.call', () => ({ result: 'boom', isError: true }))
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- const result = await $.tool.call({ tool: 'Bash', command: 'python3 blog_render.py --md a.md' })
- expect(result).toMatchObject({ result: 'boom', isError: true })
- const band = await $.ui.mount({ ...BAND, surface: 'terminal' })
- expect(await band.find({ type: 'Text', text: /Render/ })).toBeDefined()
- expect(await band.find({ type: 'Text', text: /✗/ })).toBeDefined()
- await band.unmount()
-})
-
-test('the same blocker from every viewport collapses to one line', () => {
- expect(groupViolations([
- 'mobile: 1 console error', 'tablet: 1 console error', 'desktop: 1 console error', 'no hero image found',
- ])).toEqual(['mobile + tablet + desktop: 1 console error', 'no hero image found'])
- expect(groupViolations([])).toEqual([])
-})
-
-test('history entries are stable, merge without losing results, and sort newest first', () => {
- expect(entryId('/work', 'a')).toBe(entryId('/work', 'a'))
- expect(entryId('/work', 'a')).not.toBe(entryId('/work', 'b'))
- const known = { ...makeEntry('/work', 'a', 5000, 'checked', PASS as never), lastSeen: 5000 }
- const seen = makeEntry('/work', 'a', 9000, 'observed')
- const merged = mergeEntries([known], seen)
- expect(merged).toHaveLength(1)
- expect(merged[0]).toMatchObject({ lastSeen: 9000, firstSeen: 5000, status: 'passed', passed: 5, score: 90 })
- const old = makeEntry('/work', 'old', 1000, 'scan', null, 1000)
- expect(sortEntries([old, known, seen]).map(e => e.draft)).toEqual(['a', 'a', 'old'])
- expect(formatWhen(new Date(2026, 9, 8, 19, 5).getTime())).toBe('10-08 19:05')
-})
-
-test('history validation rejects unsafe or malformed records', () => {
- const good = makeEntry('/work', 'outputs/a', 1, 'observed')
- expect(validEntry(good)).toBe(true)
- expect(validEntry({ ...good, root: 'relative' })).toBe(false)
- expect(validEntry({ ...good, draft: '../escape' })).toBe(false)
- expect(validEntry({ ...good, draft: '/abs' })).toBe(false)
- expect(validEntry({ ...good, lastSeen: 'x' })).toBe(false)
- expect(validEntry(null)).toBe(false)
-})
-
-test('absolute draft folders split into a project root and a relative draft', () => {
- expect(splitDraft('/work/outputs/a', '/work')).toEqual({ root: '/work', draft: 'outputs/a' })
- expect(splitDraft('/other/proj/blog-a', '/work')).toEqual({ root: '/other/proj', draft: 'blog-a' })
- expect(splitDraft('/lonely', '/work')).toBeNull()
- expect(parseFound('1760000000.5\t/x/a\nbad line\n1770000000\t/x/b\n1770000001\trelative\n'))
- .toEqual([{ path: '/x/b', mtimeMs: 1770000000000 }, { path: '/x/a', mtimeMs: 1760000000500 }])
-})
-
-test('history follows the agent, backfills by scan, and opens a past blog in another project', async ($, on) => {
- host(on)
- on('tool.call', () => ({ result: 'ok' }))
- const argvs: string[][] = []
- on('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[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) }) }
- })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.tool.call({ tool: 'Write', file_path: '/work/outputs/post/post.md', content: 'x' })
- let listed = await $.command.run({ command: 'blog-studio', args: 'history', ...RUN })
- expect(listed).toMatchObject({ text: expect.stringContaining('post') })
- const scanned = await $.command.run({ command: 'blog-studio', args: 'history scan /other', ...RUN })
- expect(scanned).toMatchObject({ text: expect.stringContaining('added 1 draft') })
- expect(argvs.find(a => a[0] === 'find')).toEqual(expect.arrayContaining(['/other', '-maxdepth', '7', '-name', 'preflight-report.json']))
- listed = await $.command.run({ command: 'blog-studio', args: 'history', ...RUN })
- const text = (listed as { text: string }).text
- expect(text.indexOf('post')).toBeLessThan(text.indexOf('blog-a'))
- const 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[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') })
-})
-
-test('the history list in the panel opens a blog and an unsafe stored record is refused', async ($, on) => {
- host(on, { link: '/other/proj/blog-a' })
- on('tool.call', () => ({ result: 'ok' }))
- on('process.run', ($$, e) => ({ value: done({ exitCode: 0, stderr: '', stdout: e.argv[0] === 'find'
- ? '1760000000.0\t/other/proj/blog-a\n1750000000.0\t/other/proj/blog-b\n' : JSON.stringify(PASS) }) }))
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.command.run({ command: 'blog-studio', args: 'history scan /other', ...RUN })
- const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })
- const rows = await ui.findAll({ type: 'Button', text: /blog-/ })
- expect(rows.length).toBe(2)
- const refused = await $.command.run({ command: 'blog-studio', args: 'open 1', ...RUN })
- expect(refused).toMatchObject({ text: expect.stringContaining('unsafe path') })
- const fine = await $.command.run({ command: 'blog-studio', args: 'open 2', ...RUN })
- expect(fine).toMatchObject({ text: expect.stringContaining('blog-b') })
- await ui.unmount()
-})
-
-test('the engine location is remembered across sessions and can be forgotten', async ($, on) => {
- let sessionId = 'one'
- const argvs: string[][] = []
- host(on, { env: null, sessionId: () => sessionId })
- on('process.run', ($$, e) => {
- argvs.push([...e.argv])
- 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) }) }
- })
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- const set = await $.command.run({ command: 'blog-studio', args: 'configure /trusted/scripts', ...RUN })
- expect(set).toMatchObject({ text: expect.stringContaining('remembered') })
- sessionId = '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[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'
- await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })
- const refused = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })
- expect(refused).toMatchObject({ text: expect.stringContaining('Configure the trusted claude-blog scripts directory first') })
-})
-
-test('generic folder names lead with their project, and forgetting removes only the history record', async ($, on) => {
- expect(title({ root: '/x/YouTube Scout', name: '03-article' })).toBe('YouTube Scout / 03-article')
- expect(title({ root: '/x/post', name: 'post' })).toBe('post')
- host(on)
- on('tool.call', () => ({ result: 'ok' }))
- await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })
- await $.tool.call({ tool: 'Write', file_path: '/work/outputs/post/post.md', content: 'x' })
- const gone = await $.command.run({ command: 'blog-studio', args: 'history forget 1', ...RUN })
- expect(gone).toMatchObject({ text: expect.stringContaining('files were not touched') })
- const after = await $.command.run({ command: 'blog-studio', args: 'history', ...RUN })
- expect(after).toMatchObject({ text: expect.stringContaining('no blogs in the history yet') })
- const bad = await $.command.run({ command: 'blog-studio', args: 'history forget 7', ...RUN })
- expect(bad).toMatchObject({ text: expect.stringContaining('Give the number') })
-})
diff --git a/plugins/blog-studio/tsconfig.json b/plugins/blog-studio/tsconfig.json
deleted file mode 100644
index 0636a24..0000000
--- a/plugins/blog-studio/tsconfig.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2023",
- "lib": [
- "es2023"
- ],
- "types": [],
- "module": "esnext",
- "moduleResolution": "bundler",
- "strict": true,
- "noUncheckedIndexedAccess": true,
- "noEmit": true,
- "skipLibCheck": true
- },
- "include": [
- ".claude-plugin/types/**/*.d.ts",
- "hooks",
- "types",
- "tests"
- ]
-}
diff --git a/plugins/blog-studio/tsconfig.reference.json b/plugins/blog-studio/tsconfig.reference.json
deleted file mode 100644
index d3bee57..0000000
--- a/plugins/blog-studio/tsconfig.reference.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "include": [
- "dev/reference-state.d.ts",
- "hooks",
- "types"
- ],
- "exclude": [
- ".claude-plugin/types"
- ],
- "files": [
- ".reference-types/claude-code.d.ts"
- ]
-}
diff --git a/plugins/blog-studio/types/index.d.ts b/plugins/blog-studio/types/index.d.ts
deleted file mode 100644
index f27ac0b..0000000
--- a/plugins/blog-studio/types/index.d.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-export type Gate = { gate: number; name: string; passed: boolean; score: number | null; violations: string[]; warnings: string[] }
-export type Status = {
- schema_version: 1
- status: 'passed' | 'blocked' | 'partial' | 'stale' | 'unverified' | 'error'
- label: string
- checked_at: string | null
- passed_count: number
- gates: Gate[]
- artifacts: string[]
- diagnostics: string[]
- run_id?: string
-}
-export type StudioState = {
- workspace: string
- sessionId: string
- scripts: string | null
- draft: string | null
- generation: number
- projectRoot: string | null
- busy: boolean
- status: Status | null
- message: string | null
-}
-export type StageId = 'research' | 'outline' | 'draft' | 'visuals' | 'render' | 'review' | 'gates'
-export type StageState = 'pending' | 'active' | 'done' | 'failed'
-export type Stage = { state: StageState; n: number; startedAt: number | null; endedAt: number | null; note: string | null }
-export type RunState = {
- workspace: string
- sessionId: string
- skill: string | null
- startedAt: number | null
- endedAt: number | null
- working: boolean
- stages: Record<StageId, Stage>
- detected: string | null
- scores: number[]
- setup: boolean
- historyOpen: boolean
-}
-export type HistoryEntry = {
- id: string
- root: string
- draft: string
- name: string
- firstSeen: number
- lastSeen: number
- status: Status['status'] | null
- passed: number
- score: number | null
- source: 'observed' | 'selected' | 'checked' | 'scan'
-}
-export type HistoryState = { entries: HistoryEntry[]; loaded: boolean }
-declare module 'claude-code' {
- interface PluginState { 'blog-studio': { studio: StudioState; run: RunState; history: HistoryState } }
-}
diff --git a/scripts/blog_studio_status.py b/scripts/blog_studio_status.py
index e4f5ed5..a0fa0e7 100644
--- a/scripts/blog_studio_status.py
+++ b/scripts/blog_studio_status.py
@@ -1,6 +1,9 @@
#!/usr/bin/env python3
"""Inspect saved preflight evidence without rendering, network calls or writes.
+Blog Studio (plugins/blog-studio on the blog-studio branch of this repository)
+runs this script to show a draft's status; it is engine contract and stays on main.
+
Fingerprints describe the files checked, not authenticated approval. The
preflight remains the delivery authority. Legacy reports have unknown freshness.
diff --git a/scripts/check_secrets.py b/scripts/check_secrets.py
index 68d9d49..d9b7729 100644
--- a/scripts/check_secrets.py
+++ b/scripts/check_secrets.py
@@ -18,6 +18,10 @@ SHA_FIELD_RE = re.compile(
re.IGNORECASE,
)
GIT_REVISION_FIELD_RE = re.compile(r'"revision"\s*:\s*"[0-9a-f]{40}"', re.IGNORECASE)
+# The marketplace pins Blog Studio's git-subdir source to a full commit. Only a
+# lowercase 40-hex "sha" field in the marketplace manifest is adjudicated.
+MARKETPLACE_PATH = ".claude-plugin/marketplace.json"
+MARKETPLACE_SHA_FIELD_RE = re.compile(r'^\s*"sha"\s*:\s*"[0-9a-f]{40}"\s*,?\s*$')
ACTION_PIN_RE = re.compile(r"uses:\s*[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+@[0-9a-f]{40}\b")
ACTION_EXPECTATION_RE = re.compile(
r'"actions/(?:checkout|setup-node|setup-python)"\s*:\s*"[0-9a-f]{40}"'
@@ -136,6 +140,7 @@ def is_adjudicated(path: str, finding: dict[str, object], line: str) -> bool:
or ACTION_PIN_RE.search(line)
or ACTION_EXPECTATION_RE.search(line)
or reviewed_commit
+ or (path == MARKETPLACE_PATH and MARKETPLACE_SHA_FIELD_RE.fullmatch(line) is not None)
)
if finding_type == "Secret Keyword":
return is_placeholder_value(line)
diff --git a/scripts/consistency_check.py b/scripts/consistency_check.py
index b0f1518..a359468 100644
--- a/scripts/consistency_check.py
+++ b/scripts/consistency_check.py
@@ -16,9 +16,7 @@ import sys
from pathlib import Path
from urllib.parse import unquote
-SCANNED_ROOTS = ("docs", "skills", "agents", ".github", "plugins")
-# Vendored or generated trees below plugins/ that are not project documentation.
-SKIPPED_PARTS = {"node_modules", ".reference-types"}
+SCANNED_ROOTS = ("docs", "skills", "agents", ".github")
RESOURCE_ROOTS = ("docs", "skills", "agents", "scripts")
EXPLICIT_PATH_RE = re.compile(
r"`((?:skills|agents|scripts|docs)/[A-Za-z0-9_./-]+)`"
@@ -47,11 +45,7 @@ def _markdown_sources(root: Path) -> list[Path]:
for directory in SCANNED_ROOTS:
base = root / directory
if base.is_dir():
- 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()
- )
+ sources.extend(base.rglob("*.md"))
return sorted({path for path in sources if path.is_file()})
diff --git a/scripts/validate_public_release.py b/scripts/validate_public_release.py
index e817e4b..c4bf95f 100644
--- a/scripts/validate_public_release.py
+++ b/scripts/validate_public_release.py
@@ -22,6 +22,19 @@ PUBLIC_SLUG = f"{PUBLIC_PLUGIN_IDENTIFIER}@agricidaniel-blog"
PUBLIC_OWNER = "AgriciDaniel"
PUBLIC_OWNER_URL = "https://github.com/AgriciDaniel"
PUBLIC_MARKETPLACE = "agricidaniel-blog"
+# Blog Studio is served from the blog-studio branch of this repository, pinned
+# to a commit, because Claude Desktop refuses a plugin folder that holds a
+# nested .claude-plugin/plugin.json. The check below reads the entry only; it
+# never contacts the network.
+STUDIO_PLUGIN = "blog-studio"
+STUDIO_SOURCE = {
+ "source": "git-subdir",
+ "url": "AgriciDaniel/claude-blog",
+ "path": "plugins/blog-studio",
+ "ref": "blog-studio",
+}
+STUDIO_HOMEPAGE = f"{PUBLIC_REPOSITORY}/tree/blog-studio/plugins/blog-studio"
+COMMIT_SHA_RE = re.compile(r"[0-9a-f]{40}")
PUBLIC_RAW_INSTALL_SH = (
"https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.sh"
)
@@ -116,17 +129,11 @@ 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__", "node_modules", ".reference-types"}
- for part in path.parts
- ):
- continue
- if ".claude-plugin/types/" in path.as_posix():
+ if path.is_symlink() or any(part in {".venv", "__pycache__"} for part in path.parts):
continue
relative = path.relative_to(root).as_posix()
contents.setdefault(relative, path.read_text(encoding="utf-8"))
@@ -349,13 +356,11 @@ def validate(root: Path) -> dict:
)
marketplace_text = contents.get(".claude-plugin/marketplace.json", "")
- marketplace: dict = {}
try:
marketplace = json.loads(marketplace_text)
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"}
)
@@ -395,33 +400,52 @@ def validate(root: Path) -> dict:
"file": ".claude-plugin/marketplace.json",
}
)
+ entries = [entry for entry in plugins if isinstance(entry, dict)] if isinstance(plugins, list) else []
+ # Only claude-blog may live inside the plugin root; any other local
+ # source would put a second plugin.json inside the claude-blog folder.
+ for entry in entries:
+ if entry.get("name") != PUBLIC_PLUGIN_IDENTIFIER and not isinstance(entry.get("source"), dict):
+ errors.append(
+ {
+ "kind": "local_companion_source",
+ "file": ".claude-plugin/marketplace.json",
+ "plugin": str(entry.get("name")),
+ }
+ )
+ studio_entries = [entry for entry in entries if entry.get("name") == STUDIO_PLUGIN]
+ if studio_entries:
+ studio = studio_entries[0]
+ source = studio.get("source")
+ if (
+ len(studio_entries) != 1
+ or not isinstance(source, dict)
+ or set(source) != {*STUDIO_SOURCE, "sha"}
+ or any(source.get(key) != value for key, value in STUDIO_SOURCE.items())
+ or not isinstance(source.get("sha"), str)
+ or not COMMIT_SHA_RE.fullmatch(source["sha"])
+ or not isinstance(studio.get("version"), str)
+ or studio.get("homepage") != STUDIO_HOMEPAGE
+ ):
+ errors.append(
+ {
+ "kind": "invalid_studio_distribution",
+ "file": ".claude-plugin/marketplace.json",
+ "plugin": STUDIO_PLUGIN,
+ }
+ )
- # 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
+ root_manifest = root / ".claude-plugin" / "plugin.json"
+ for manifest in sorted(root.rglob("plugin.json")):
+ relative_parts = set(manifest.relative_to(root).parts)
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")
+ manifest.parent.name == ".claude-plugin"
+ and manifest != root_manifest
+ and not {".git", ".venv", "node_modules"} & relative_parts
):
errors.append(
{
- "kind": "invalid_studio_distribution",
- "file": "plugins/blog-studio/.claude-plugin/plugin.json",
+ "kind": "nested_plugin_manifest",
+ "file": manifest.relative_to(root).as_posix(),
}
)
diff --git a/skills/blog/references/blog-delivery-contract.md b/skills/blog/references/blog-delivery-contract.md
index 9ec0d85..8a72e86 100644
--- a/skills/blog/references/blog-delivery-contract.md
+++ b/skills/blog/references/blog-delivery-contract.md
@@ -346,7 +346,9 @@ cannot evidence.
## Optional status companion
-Blog Studio reads the additive `evidence` object in `preflight-report.json`
+Blog Studio (an optional plugin on the `blog-studio` branch of this repository,
+installed as `blog-studio@agricidaniel-blog`; it needs claude-blog 2.3.2 or
+later) 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
diff --git a/tests/fixtures/plugin_validate/v2.1.218-shipped-tree.txt b/tests/fixtures/plugin_validate/v2.1.218-shipped-tree.txt
index c823021..c004c97 100644
--- a/tests/fixtures/plugin_validate/v2.1.218-shipped-tree.txt
+++ b/tests/fixtures/plugin_validate/v2.1.218-shipped-tree.txt
@@ -1,7 +1,3 @@
Validating marketplace manifest: /home/runner/work/claude-blog/claude-blog/.claude-plugin/marketplace.json
-⚠ Found 1 warning:
-
- ❯ plugins[1] plugin.json → types: Unknown field 'types'. Claude Code ignores it at load time.
-
-✔ Validation passed with warnings
+✔ Validation passed
diff --git a/tests/test_blog_studio_integration.py b/tests/test_blog_studio_integration.py
index c391eec..e7c7e32 100644
--- a/tests/test_blog_studio_integration.py
+++ b/tests/test_blog_studio_integration.py
@@ -1,6 +1,11 @@
"""Run the real engine scripts the way the Blog Studio plugin does.
-plugins/blog-studio/hooks/register.ts runs ``python3 -E blog_preflight.py`` with
+Blog Studio lives in plugins/blog-studio on the blog-studio branch of this
+repository, not on main, and this file reads nothing from it. The parser and
+report checks below mirror that branch's hooks/register.ts and hooks/logic.ts,
+so a change to the engine contract shows up here without a Studio checkout.
+
+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 tests
@@ -56,7 +61,7 @@ raise SystemExit(p.main())
def parse_status(raw: str) -> dict:
- """Mirror of parseStatus in plugins/blog-studio/hooks/logic.ts."""
+ """Mirror of parseStatus in hooks/logic.ts on the blog-studio branch."""
assert len(raw) <= 1024 * 1024
x = json.loads(raw)
assert isinstance(x, dict)
diff --git a/tests/test_dependency_plugin_validate_tolerance.py b/tests/test_dependency_plugin_validate_tolerance.py
index 129827a..205be73 100644
--- a/tests/test_dependency_plugin_validate_tolerance.py
+++ b/tests/test_dependency_plugin_validate_tolerance.py
@@ -35,22 +35,17 @@ def _sample(name: str) -> str:
return (SAMPLES / name).read_text(encoding="utf-8")
-def test_old_cli_pass_tolerates_only_the_studio_types_warning():
+def test_old_cli_pass_is_a_pass():
ok, tolerated, blocking = tolerance.evaluate(_sample("v2.1.218-shipped-tree.txt"), 0)
- assert ok and not blocking
- assert tolerated == ["blog-studio-types-field-warning"]
-
-
-def test_the_types_warning_is_tolerated_only_once_and_only_on_the_studio_entry():
- text = _sample("v2.1.218-shipped-tree.txt")
- ok, _t, blocking = tolerance.evaluate(text + text.split("\n", 2)[2], 0)
- assert not ok and any("duplicate" in item or "plugins[1]" in item for item in blocking)
- other = text.replace("plugins[1]", "plugins[0]")
- ok, _t, blocking = tolerance.evaluate(other, 0)
- assert not ok and any("plugins[0] plugin.json" in item for item in blocking)
- other_field = text.replace("types: Unknown field 'types'", "hooks: Unknown field 'hooks'")
- ok, _t, blocking = tolerance.evaluate(other_field, 0)
- assert not ok
+ assert ok and not tolerated and not blocking
+
+
+def test_unknown_manifest_field_warning_is_not_tolerated():
+ # The marketplace ships one plugin, so no second entry has a tolerated warning.
+ extra = "\n⚠ Found 1 warning:\n\n ❯ plugins[1] plugin.json → types: Unknown field 'types'. Claude Code ignores it at load time.\n"
+ text = _sample("v2.1.218-shipped-tree.txt").replace("\n✔ Validation passed", extra + "\n✔ Validation passed")
+ ok, tolerated, blocking = tolerance.evaluate(text, 0)
+ assert not ok and not tolerated and any("plugins[1] plugin.json" in item for item in blocking)
@pytest.mark.parametrize("version", ["2.1.292", "2.1.296"])
diff --git a/tests/test_manifest_layout.py b/tests/test_manifest_layout.py
new file mode 100644
index 0000000..20da602
--- /dev/null
+++ b/tests/test_manifest_layout.py
@@ -0,0 +1,47 @@
+"""Marketplace layout that Claude Desktop accepts.
+
+Claude Desktop refuses a plugin folder that holds a second plugin manifest
+("plugin.json must be at .claude-plugin/plugin.json at the plugin root ...
+found nested"). The claude-blog entry uses ``source: "./"``, so the whole
+repository is its plugin folder and only the root manifest may exist. Blog
+Studio is therefore served from the blog-studio branch, pinned to a commit.
+"""
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+MARKETPLACE = ROOT / ".claude-plugin" / "marketplace.json"
+
+
+def test_no_nested_plugin_manifest_below_the_repository_root():
+ root_manifest = (ROOT / ".claude-plugin" / "plugin.json").resolve()
+ nested = [
+ path.relative_to(ROOT).as_posix()
+ for path in ROOT.rglob("plugin.json")
+ if path.parent.name == ".claude-plugin"
+ and path.resolve() != root_manifest
+ and not {".git", ".venv", "node_modules"} & set(path.relative_to(ROOT).parts)
+ ]
+ assert not nested, f"nested plugin manifests break Claude Desktop installs: {nested}"
+
+
+def test_blog_studio_installs_from_the_pinned_branch():
+ marketplace = json.loads(MARKETPLACE.read_text(encoding="utf-8"))
+ entries = {entry["name"]: entry for entry in marketplace["plugins"]}
+ assert marketplace["name"] == "agricidaniel-blog"
+ assert marketplace["plugins"][0]["name"] == "claude-blog"
+ assert marketplace["plugins"][0]["source"] == "./"
+ assert list(entries) == ["claude-blog", "blog-studio"]
+ studio = entries["blog-studio"]
+ source = studio["source"]
+ assert isinstance(source, dict), "blog-studio must not be a local path inside the plugin root"
+ assert source["source"] == "git-subdir"
+ assert source["url"] == "AgriciDaniel/claude-blog"
+ assert source["path"] == "plugins/blog-studio"
+ assert source["ref"] == "blog-studio"
+ assert re.fullmatch(r"[0-9a-f]{40}", source["sha"]), source.get("sha")
+ assert studio["version"] == "0.3.0"
+ assert studio["homepage"] == "https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio"
diff --git a/tests/test_release_safeguards.py b/tests/test_release_safeguards.py
index fb22a29..bc0299a 100644
--- a/tests/test_release_safeguards.py
+++ b/tests/test_release_safeguards.py
@@ -705,6 +705,67 @@ def test_public_release_validator_rejects_desynchronized_plugin_identity(
assert any(error["kind"] == expected_kind for error in result["errors"])
+_STUDIO_ENTRY = {
+ "name": "blog-studio",
+ "source": {
+ "source": "git-subdir",
+ "url": "AgriciDaniel/claude-blog",
+ "path": "plugins/blog-studio",
+ "ref": "blog-studio",
+ "sha": "c1cc72f8" * 5,
+ },
+ "version": "0.3.0",
+ "homepage": "https://github.com/AgriciDaniel/claude-blog/tree/blog-studio/plugins/blog-studio",
+}
+
+
+def _with_studio(root: Path, entry: dict) -> None:
+ path = root / ".claude-plugin" / "marketplace.json"
+ data = json.loads(path.read_text(encoding="utf-8"))
+ data["plugins"].append(entry)
+ path.write_text(json.dumps(data), encoding="utf-8")
+
+
+def test_public_release_validator_accepts_the_pinned_studio_entry(tmp_path: Path) -> None:
+ module = _load_module("release_studio_validator", ROOT / "scripts/validate_public_release.py")
+ _public_fixture(tmp_path)
+ _with_studio(tmp_path, _STUDIO_ENTRY)
+ assert module.validate(tmp_path)["status"] == "pass"
+
+
+ ("change", "expected_kind"),
+ [
+ ({"source": "./plugins/blog-studio"}, "local_companion_source"),
+ ({"source": {**_STUDIO_ENTRY["source"], "sha": "__STUDIO_SHA__"}}, "invalid_studio_distribution"),
+ ({"source": {**_STUDIO_ENTRY["source"], "sha": "C1CC72F8" * 5}}, "invalid_studio_distribution"),
+ ({"source": {**_STUDIO_ENTRY["source"], "ref": "main"}}, "invalid_studio_distribution"),
+ ({"source": {**_STUDIO_ENTRY["source"], "url": "Someone/claude-blog"}}, "invalid_studio_distribution"),
+ ({"homepage": "https://example.com"}, "invalid_studio_distribution"),
+ ],
+)
+def test_public_release_validator_rejects_a_bad_studio_entry(
+ tmp_path: Path, change: dict, expected_kind: str,
+) -> None:
+ module = _load_module("release_bad_studio_validator", ROOT / "scripts/validate_public_release.py")
+ _public_fixture(tmp_path)
+ _with_studio(tmp_path, {**_STUDIO_ENTRY, **change})
+ result = module.validate(tmp_path)
+ assert result["status"] == "fail"
+ assert any(error["kind"] == expected_kind for error in result["errors"])
+
+
+def test_public_release_validator_rejects_a_nested_plugin_manifest(tmp_path: Path) -> None:
+ module = _load_module("release_nested_validator", ROOT / "scripts/validate_public_release.py")
+ _public_fixture(tmp_path)
+ nested = tmp_path / "plugins" / "blog-studio" / ".claude-plugin"
+ nested.mkdir(parents=True)
+ (nested / "plugin.json").write_text('{"name": "blog-studio"}', encoding="utf-8")
+ result = module.validate(tmp_path)
+ assert result["status"] == "fail"
+ assert {"kind": "nested_plugin_manifest", "file": "plugins/blog-studio/.claude-plugin/plugin.json"} in result["errors"]
+
+
@pytest.mark.parametrize(
("surface", "unsafe"),
[
diff --git a/tests/test_scripts_wave3_gate.py b/tests/test_scripts_wave3_gate.py
index 0b69da1..6ae76ec 100644
--- a/tests/test_scripts_wave3_gate.py
+++ b/tests/test_scripts_wave3_gate.py
@@ -487,6 +487,15 @@ def test_secret_scan_skips_local_virtualenvs(monkeypatch):
def test_git_revision_field_is_adjudicated_but_a_bare_hex_secret_is_not():
hex_finding = {"type": "Hex High Entropy String"}
revision = ' "revision": "' + "ab12" * 10 + '",'
- assert SECRETS.is_adjudicated("plugins/x/dev/types-source.json", hex_finding, revision)
+ assert SECRETS.is_adjudicated("data/legacy-install-ownership.json", hex_finding, revision)
bare = ' "token": "' + "ab12" * 10 + '",'
- assert not SECRETS.is_adjudicated("plugins/x/dev/types-source.json", hex_finding, bare)
+ assert not SECRETS.is_adjudicated("data/legacy-install-ownership.json", hex_finding, bare)
+
+
+def test_marketplace_commit_pin_is_adjudicated_only_in_the_marketplace():
+ hex_finding = {"type": "Hex High Entropy String"}
+ pin = ' "sha": "' + "c1cc72f8" * 5 + '"'
+ assert SECRETS.is_adjudicated(".claude-plugin/marketplace.json", hex_finding, pin)
+ assert not SECRETS.is_adjudicated("docs/INSTALLATION.md", hex_finding, pin)
+ assert not SECRETS.is_adjudicated(".claude-plugin/marketplace.json", hex_finding, ' "token": "' + "c1cc72f8" * 5 + '"')
+ assert not SECRETS.is_adjudicated(".claude-plugin/marketplace.json", hex_finding, pin + ', "token": "' + "ab12" * 10 + '"')