Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.
Python agent-skillsaiai-citationsai-contentai-marketingai-marketing-hubblogblog-writingclaude-codeclaude-code-skillclaude-pluginclaude-skillcontent-creationcontent-optimizationcontent-strategyeeatgeomultilingualopen-sourceseo
feat(blog-studio): ship Blog Studio as an optional companion plugin (v2.3.1)
Agrici Danielb524cd6482e0
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 03613dc..d53b6a7 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -11,6 +11,12 @@"name": "claude-blog","source": "./","description": "AI-powered blog creation, optimization, and management with 32 skill directories (1 orchestrator + 31 sub-skills), 5 agents, FLOW framework integration, semantic topic-cluster execution, multilingual publishing, brand and discourse context auto-load, and 5-category scoring. Optimized for Google rankings and AI citations."+ },+ {+ "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."}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5c514d7..a601269 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "claude-blog","displayName": "Claude Blog","description": "AI-powered blog skill suite: 32 skill directories (1 orchestrator + 31 sub-skills) and 5 agents to write, rewrite, audit, and optimize content for Google rankings and AI citations (GEO/AEO). Includes the FLOW framework, topic clusters, multilingual publishing, Google API integration, personas, fact-checking, NotebookLM research, Gemini TTS narration, image generation, and 100-point scoring.",- "version": "2.3.0",+ "version": "2.3.1","author": {"name": "AgriciDaniel","url": "https://github.com/AgriciDaniel"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 727ae8c..059ff7d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [2.3.1] - 2026-10-13++### Added++- Ship Blog Studio 0.2.0 as an optional second plugin of the same marketplace+ (`plugins/blog-studio`, install with `/plugin install blog-studio@agricidaniel-blog`).+ It is a Claude Code mod: a status band, a live pipeline and five-gate review+ panel, a history of past blogs and a Run checks control that runs the strict+ preflight. Strict plugin validation passes and its 59 test-kit tests pass.+ It is not part of the `claude-blog` plugin and the standalone installers do+ not enable it.++### Changed++- Blog Studio refers to the engine as `claude-blog` in its messages and docs.+- Version 2.3.1 on every release surface; no change to the delivery gates,+ scripts or skills.+## [2.3.0] - 2026-10-13### Fixeddiff --git a/CITATION.cff b/CITATION.cffindex 6148e61..da9dcf5 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -11,7 +11,7 @@ authors:repository-code: "https://github.com/AgriciDaniel/claude-blog"url: "https://claude-blog.md"license: MIT-version: 2.3.0+version: 2.3.1date-released: "2026-10-13"keywords:- claude-codediff --git a/CLAUDE.md b/CLAUDE.mdindex 2112648..ee200d3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -22,8 +22,9 @@ claude-blog/CLAUDE.md # Project instructions (this file)docs/CONTRIBUTORS.md # Pro Hub Challenge attribution and integration decisionsCHANGELOG.md # Keep a Changelog format- .claude-plugin/plugin.json # Plugin manifest (v2.3.0)- .claude-plugin/marketplace.json # Marketplace catalog for distribution+ .claude-plugin/plugin.json # Plugin manifest (v2.3.1)+ .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.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/diff --git a/README.md b/README.mdindex e79b92c..5ddd9f7 100644--- a/README.md+++ b/README.md@@ -18,7 +18,7 @@<img src="https://img.shields.io/badge/Tests-pytest%20suite-brightgreen" alt="Tests: pytest suite, run it for the current count"></p>-**claude-blog is a Claude Code skill suite that writes, optimizes, audits, localizes, and refreshes blog content at scale.** Every article is evaluated for Google-aligned usefulness and internal AI citation readiness heuristics. Version 2.3.0 was prepared on 2026-10-13.+**claude-blog is a Claude Code skill suite that writes, optimizes, audits, localizes, and refreshes blog content at scale.** Every article is evaluated for Google-aligned usefulness and internal AI citation readiness heuristics. Version 2.3.1 was prepared on 2026-10-13.The core promise is simple: the user is never the first reviewer. A 5-gate Blog Delivery Contract scores every draft against a 100-point rubric, blocks delivery below 90, verifies artifacts and links, and iterates up to 3 times before escalation.@@ -49,7 +49,7 @@ The publishing workflow is documented inclaude-blog is a full-lifecycle blog engine for strategy, briefs, outlines, writing, rewriting, analysis, schema, AI citation readiness, site audits, topic clusters, multilingual publishing, audio narration, and content decay detection.-Current v2.3.0 shape: **32 skill directories = 1 orchestrator + 31 sub-skills; 30 user-facing /blog commands (`blog-chart` is internal, not a command).** It also includes 5 specialized agents, repository consistency and public-release validators, 22 core references, 12 templates, a pytest suite (run `python3 -m pytest --collect-only -q | tail -1` for the current count), and the bundled Claude Blog Brain at `./brain`.+Current v2.3.1 shape: **32 skill directories = 1 orchestrator + 31 sub-skills; 30 user-facing /blog commands (`blog-chart` is internal, not a command).** It also includes 5 specialized agents, repository consistency and public-release validators, 22 core references, 12 templates, a pytest suite (run `python3 -m pytest --collect-only -q | tail -1` for the current count), and the bundled Claude Blog Brain at `./brain`.Every draft ships as an artifact folder with the markdown source, rendered HTML, PDF, real `hero.<ext>`, 3 viewport screenshots, `review.md`, and `preflight-report.json`. The renderer uses XSS-safe JSON-LD handling, dark-mode-aware CSS, and the same source for every output format.@@ -306,7 +306,7 @@ Verify the downloaded wrapper before running it:```bashcurl -fsSL -o install.sh https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.sh-echo "6048c4deb5075082e880c0ed61dba9d95066c11f128e7f4bd599bffc402de391 install.sh" | sha256sum -c+echo "cd471aabcf08bd208d3377ee432add8f1addeb79d6767e6acb34518972df0164 install.sh" | sha256sum -cCLAUDE_BLOG_REF=<commit-sha-or-release-tag> bash install.sh```@@ -314,7 +314,7 @@ Integrity is only as pinned as `CLAUDE_BLOG_REF`. What the digests cover:each is the SHA-256 of that one file's bytes in this repository with CRLF lineendings normalized to LF, the form `raw.githubusercontent.com` serves(`install.sh`: the digest above; `install.ps1`:-`e39d21fc0e9f96f2bb65d7c06fd24a734d674009a47c00a9b8826a582093fbda`). A local+`aa80fa99aaacc5dec3acabcbd714801b4a3e63635c09db9264041f8b8f48dd97`). A localcopy with CRLF endings or edits will not match until normalized. They do notcover the code that does the work: the wrapper clones the repository at`CLAUDE_BLOG_REF` and hands over to that revision's own `install.sh`,@@ -354,6 +354,24 @@ Uninstall on Windows PowerShell:Installation details: [`docs/INSTALLATION.md`](docs/INSTALLATION.md).+### Blog Studio (optional companion)++[`plugins/blog-studio`](plugins/blog-studio) is a separate, optional Claude Code+mod in the same marketplace. It adds a status band, a live pipeline and five-gate+review panel, a history of past blogs, and a **Run checks** control that runs the+strict preflight. It is not part of the `claude-blog` plugin and the standalone+installers never enable it.++```text+/plugin marketplace add AgriciDaniel/claude-blog+/plugin install blog-studio@agricidaniel-blog+/blog-studio configure /path/to/claude-blog/scripts+```++It needs a Claude Code release with mods support (checked on 2.1.294 to 2.1.296,+Linux CLI; the Desktop app is fixture-tested only). See+[`plugins/blog-studio/README.md`](plugins/blog-studio/README.md).+## Known Issues- **`claude plugin validate` rejects the name `claude-blog` on newer Claude Code.**@@ -477,7 +495,7 @@ If you use claude-blog in research or production, please cite the project:title = {claude-blog: AI Blog Writing and SEO Optimization Skill for Claude Code},year = {2026},url = {https://github.com/AgriciDaniel/claude-blog},- version = {2.3.0},+ version = {2.3.1},license = {MIT}}```diff --git a/docs/DEMO.md b/docs/DEMO.mdindex a45e47a..a43f000 100644--- a/docs/DEMO.md+++ b/docs/DEMO.md@@ -1,4 +1,4 @@-# claude-blog v2.3.0: Demo Runbook+# claude-blog v2.3.1: Demo RunbookEnd-to-end demo flow that exercises every wired integration: YouTubeembedding (blog-google), keyword research (DataForSEO MCP), AI imagediff --git a/install.ps1 b/install.ps1index c765f95..24396fb 100644--- a/install.ps1+++ b/install.ps1@@ -20,7 +20,7 @@ param()$ErrorActionPreference = "Stop"-$ClaudeBlogVersion = "2.3.0"+$ClaudeBlogVersion = "2.3.1"function Write-Color($Color, $Text) { Write-Host $Text -ForegroundColor $Color }diff --git a/install.sh b/install.shindex 180269e..bcff038 100755--- a/install.sh+++ b/install.sh@@ -19,7 +19,7 @@ set -euo pipefailTEMP_DIR=""INSTALL_STATS_FILE=""-readonly CLAUDE_BLOG_VERSION="2.3.0"+readonly CLAUDE_BLOG_VERSION="2.3.1"count_files() {local path="$1"diff --git a/plugins/blog-studio/.claude-plugin/plugin.json b/plugins/blog-studio/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..bc86a59--- /dev/null+++ b/plugins/blog-studio/.claude-plugin/plugin.json@@ -0,0 +1,13 @@+{+ "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/.gitignorenew file mode 100644index 0000000..18acf53--- /dev/null+++ b/plugins/blog-studio/.gitignore@@ -0,0 +1,3 @@+node_modules/+.reference-types/+.claude-plugin/types/diff --git a/plugins/blog-studio/README.md b/plugins/blog-studio/README.mdnew file mode 100644index 0000000..e500a87--- /dev/null+++ b/plugins/blog-studio/README.md@@ -0,0 +1,210 @@+# 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. 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 passes `--project-root` to the checker. On Linux, the checker+opens the selected directory through descriptors without following symlinks+and anchors its working directory there. Replacing the selected path after+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. Manual checks do not consume repair iterations.++## 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.mjsnew file mode 100644index 0000000..4821a94--- /dev/null+++ b/plugins/blog-studio/dev/native-types.mjs@@ -0,0 +1,3 @@+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.tsnew file mode 100644index 0000000..c691a84--- /dev/null+++ b/plugins/blog-studio/dev/reference-state.d.ts@@ -0,0 +1,14 @@+// 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.mjsnew file mode 100644index 0000000..c657dfa--- /dev/null+++ b/plugins/blog-studio/dev/reference-types.mjs@@ -0,0 +1,18 @@+// 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.jsonnew file mode 100644index 0000000..8c369dc--- /dev/null+++ b/plugins/blog-studio/dev/types-source.json@@ -0,0 +1,7 @@+{+ "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.tsnew file mode 100644index 0000000..67e2656--- /dev/null+++ b/plugins/blog-studio/hooks/history.ts@@ -0,0 +1,83 @@+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.jsonnew file mode 100644index 0000000..b75b48c--- /dev/null+++ b/plugins/blog-studio/hooks/hooks.json@@ -0,0 +1,6 @@+{+ "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.tsnew file mode 100644index 0000000..73a61f4--- /dev/null+++ b/plugins/blog-studio/hooks/logic.ts@@ -0,0 +1,99 @@+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.tsnew file mode 100644index 0000000..e89e290--- /dev/null+++ b/plugins/blog-studio/hooks/pipeline.ts@@ -0,0 +1,152 @@+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.tsnew file mode 100644index 0000000..bbec3f6--- /dev/null+++ b/plugins/blog-studio/hooks/register.ts@@ -0,0 +1,456 @@+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', 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+}++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)+ const out = await $.process.run(['python3', paths.scripts + '/' + CHECKER, '--draft', paths.draft,+ '--strict', '--json', '--tools-json', JSON.stringify(tools), '--project-root', rootOf(s)], { cwd: rootOf(s), timeoutMs: 600_000 })+ 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 = { 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.tsnew file mode 100644index 0000000..ab76950--- /dev/null+++ b/plugins/blog-studio/hooks/view.ts@@ -0,0 +1,276 @@+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.jsonnew file mode 100644index 0000000..8d14992--- /dev/null+++ b/plugins/blog-studio/package-lock.json@@ -0,0 +1,29 @@+{+ "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.jsonnew file mode 100644index 0000000..d15f299--- /dev/null+++ b/plugins/blog-studio/package.json@@ -0,0 +1,14 @@+{+ "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.tsnew file mode 100644index 0000000..4f2eddb--- /dev/null+++ b/plugins/blog-studio/tests/studio.test.ts@@ -0,0 +1,584 @@+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[1] ?? '')+ return { value: done({ exitCode: 0, stderr: '', stdout: JSON.stringify(e.argv[1]?.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[1]?.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[1]?.endsWith('blog_preflight.py') ?+ { strict: true, blocked: false, draft: '/work/outputs/article', evidence: { run_id: PASS.run_id } } : PASS) }) }+ })+ await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true })+ await $.command.run({ command: 'blog-studio', args: 'select outputs/article', ...RUN })+ const out = await $.command.run({ command: 'blog-studio', args: 'check', ...RUN })+ expect(out).toMatchObject({ text: expect.stringContaining('Preflight passed') })+ expect(calls[0]?.slice(0, 6)).toEqual(['python3', '/trusted/scripts/blog_preflight.py', '--draft', '/work/outputs/article', '--strict', '--json'])+ expect(limits).toEqual([600_000, 30_000])+ expect(calls[1]).toContain('--expected-run')+ 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' ? 2 : 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 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[1]?.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[1]?.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[1]?.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[1] === '/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.jsonnew file mode 100644index 0000000..0636a24--- /dev/null+++ b/plugins/blog-studio/tsconfig.json@@ -0,0 +1,21 @@+{+ "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.jsonnew file mode 100644index 0000000..d3bee57--- /dev/null+++ b/plugins/blog-studio/tsconfig.reference.json@@ -0,0 +1,14 @@+{+ "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.tsnew file mode 100644index 0000000..f27ac0b--- /dev/null+++ b/plugins/blog-studio/types/index.d.ts@@ -0,0 +1,55 @@+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/pyproject.toml b/pyproject.tomlindex 17cfa68..f38abdc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -14,7 +14,7 @@ py-modules = [][project]name = "claude-blog"-version = "2.3.0"+version = "2.3.1"description = "AI-powered blog creation and optimization skill for Claude Code"readme = "README.md"license = {text = "MIT"}diff --git a/scripts/check_secrets.py b/scripts/check_secrets.pyindex 9152ea2..68d9d49 100644--- a/scripts/check_secrets.py+++ b/scripts/check_secrets.py@@ -17,6 +17,7 @@ SHA_FIELD_RE = re.compile(r'"(?:sha256|raw_snapshot_sha256|content_sha256|normalized_content_sha256|captured_excerpt_sha256|normalized_full_document_sha256)"\s*:\s*"[0-9a-f]{64}"',re.IGNORECASE,)+GIT_REVISION_FIELD_RE = re.compile(r'"revision"\s*:\s*"[0-9a-f]{40}"', re.IGNORECASE)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}"'@@ -131,6 +132,7 @@ def is_adjudicated(path: str, finding: dict[str, object], line: str) -> bool:)return bool(SHA_FIELD_RE.search(line)+ or GIT_REVISION_FIELD_RE.search(line)or ACTION_PIN_RE.search(line)or ACTION_EXPECTATION_RE.search(line)or reviewed_commitdiff --git a/scripts/validate_public_release.py b/scripts/validate_public_release.pyindex 786afed..3ebf46d 100644--- a/scripts/validate_public_release.py+++ b/scripts/validate_public_release.py@@ -16,7 +16,7 @@ import sysfrom pathlib import PathPUBLIC_REPOSITORY = "https://github.com/AgriciDaniel/claude-blog"-PUBLIC_VERSION = "2.3.0"+PUBLIC_VERSION = "2.3.1"PUBLIC_PLUGIN_IDENTIFIER = "claude-blog"PUBLIC_SLUG = f"{PUBLIC_PLUGIN_IDENTIFIER}@agricidaniel-blog"PUBLIC_OWNER = "AgriciDaniel"diff --git a/skills/blog-audio/SKILL.md b/skills/blog-audio/SKILL.mdindex c30ed56..f609e8c 100644--- a/skills/blog-audio/SKILL.md+++ b/skills/blog-audio/SKILL.md@@ -12,7 +12,7 @@ argument-hint: "[generate|voices|setup] [file-or-text] [--mode summary|full|diallicense: MITmetadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"---# Blog Audio: Gemini TTS Narration for Blog Postsdiff --git a/skills/blog-cluster/SKILL.md b/skills/blog-cluster/SKILL.mdindex 5270555..07a2108 100644--- a/skills/blog-cluster/SKILL.md+++ b/skills/blog-cluster/SKILL.md@@ -14,7 +14,7 @@ license: MITcompatibility: Requires Claude Code and claude-blog (provides blog-write, blog-chart, blog-image)metadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: bloguser-invocable: trueargument-hint: "[plan|execute] [seed-keyword|cluster-plan.json]"diff --git a/skills/blog-flow/SKILL.md b/skills/blog-flow/SKILL.mdindex bf43868..cc8a53a 100644--- a/skills/blog-flow/SKILL.md+++ b/skills/blog-flow/SKILL.md@@ -13,7 +13,7 @@ license: MITcompatibility: Requires Claude Code and Python 3.11+ for the sync scriptmetadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: blog---diff --git a/skills/blog-google/SKILL.md b/skills/blog-google/SKILL.mdindex ed704ef..6c748ac 100644--- a/skills/blog-google/SKILL.md+++ b/skills/blog-google/SKILL.md@@ -15,7 +15,7 @@ argument-hint: "[setup|pagespeed|crux|crux-history|gsc|inspect|index|ga4|nlp|youlicense: MITmetadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: blog---diff --git a/skills/blog-image/SKILL.md b/skills/blog-image/SKILL.mdindex 4fdef31..3656b31 100644--- a/skills/blog-image/SKILL.md+++ b/skills/blog-image/SKILL.md@@ -12,7 +12,7 @@ argument-hint: "[generate|edit|setup] [description-or-path]"license: MITmetadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"optional-mcp-package: "@ycse/nanobanana-mcp"---diff --git a/skills/blog-locale-audit/SKILL.md b/skills/blog-locale-audit/SKILL.mdindex 73d4835..a9d0609 100644--- a/skills/blog-locale-audit/SKILL.md+++ b/skills/blog-locale-audit/SKILL.md@@ -14,7 +14,7 @@ license: MITcompatibility: Standalone within claude-blog. Optional richer hreflang validation via claude-seo seo-hreflang.metadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: blog---diff --git a/skills/blog-localize/SKILL.md b/skills/blog-localize/SKILL.mdindex 3b2d256..6aa2eea 100644--- a/skills/blog-localize/SKILL.md+++ b/skills/blog-localize/SKILL.md@@ -15,7 +15,7 @@ license: MITcompatibility: Standalone within claude-blog. Invoked by blog-multilingual.metadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: blog---diff --git a/skills/blog-multilingual/SKILL.md b/skills/blog-multilingual/SKILL.mdindex 33aa1a9..0139039 100644--- a/skills/blog-multilingual/SKILL.md+++ b/skills/blog-multilingual/SKILL.md@@ -15,7 +15,7 @@ license: MITcompatibility: Requires claude-blog (blog-write). Optional integration with claude-seo (seo-hreflang) for richer hreflang validation.metadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: blog---diff --git a/skills/blog-notebooklm/SKILL.md b/skills/blog-notebooklm/SKILL.mdindex 2031767..15e2783 100644--- a/skills/blog-notebooklm/SKILL.md+++ b/skills/blog-notebooklm/SKILL.md@@ -13,7 +13,7 @@ argument-hint: "[ask|discover|library|setup|status|cleanup] [question-or-url]"license: MITmetadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"source: "https://github.com/PleasePrompto/notebooklm-skill"---diff --git a/skills/blog-translate/SKILL.md b/skills/blog-translate/SKILL.mdindex 418c703..4895f7e 100644--- a/skills/blog-translate/SKILL.md+++ b/skills/blog-translate/SKILL.md@@ -18,7 +18,7 @@ license: MITcompatibility: Standalone within claude-blog. Invoked by blog-multilingual.metadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"category: blog---diff --git a/skills/blog/SKILL.md b/skills/blog/SKILL.mdindex 4d41213..7de8c27 100644--- a/skills/blog/SKILL.md+++ b/skills/blog/SKILL.md@@ -14,7 +14,7 @@ license: MITcompatibility: Requires Claude Code and Python 3.11+ for quality scoringmetadata:author: AgriciDaniel- version: "2.3.0"+ version: "2.3.1"user-invocable: trueargument-hint: "[write|rewrite|analyze|brief|calendar|cannibalization|strategy|outline|seo-check|schema|repurpose|geo|image|audit|factcheck|persona|brand|discourse|taxonomy|notebooklm|audio|google|update|cluster|multilingual|translate|localize|locale-audit|flow|style|decay] [topic-or-file]"---diff --git a/tests/test_release_safeguards.py b/tests/test_release_safeguards.pyindex a2884c4..961da31 100644--- a/tests/test_release_safeguards.py+++ b/tests/test_release_safeguards.py@@ -578,7 +578,7 @@ def test_consistency_checker_discovers_skill_relative_resources_and_agents(def _public_fixture(root: Path) -> None:public = "https://github.com/AgriciDaniel/claude-blog"- version = "2.3.0"+ version = "2.3.1"raw_sh = ("https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.sh")@@ -738,7 +738,7 @@ def test_validator_does_not_depend_on_the_host_plugin_validator() -> None:marketplace = json.loads((ROOT / ".claude-plugin/marketplace.json").read_text(encoding="utf-8"))assert manifest["name"] == "claude-blog"assert marketplace["name"] == "agricidaniel-blog"- assert [entry["name"] for entry in marketplace["plugins"]] == ["claude-blog"]+ assert [entry["name"] for entry in marketplace["plugins"]] == ["claude-blog", "blog-studio"]assert "blog-engine" not in json.dumps([manifest, marketplace])@@ -860,7 +860,7 @@ def test_public_release_validator_rejects_version_collision(_public_fixture(tmp_path)pyproject = tmp_path / "pyproject.toml"pyproject.write_text(- pyproject.read_text(encoding="utf-8").replace("2.3.0", "2.1.0"),+ pyproject.read_text(encoding="utf-8").replace("2.3.1", "2.1.0"),encoding="utf-8",)report = module.validate(tmp_path)diff --git a/tests/test_scripts_wave3_gate.py b/tests/test_scripts_wave3_gate.pyindex 9f154b4..e4ea72d 100644--- a/tests/test_scripts_wave3_gate.py+++ b/tests/test_scripts_wave3_gate.py@@ -468,3 +468,11 @@ def test_secret_scan_skips_local_virtualenvs(monkeypatch):SECRETS.run_detect_secrets()excludes = [seen["command"][i + 1] for i, arg in enumerate(seen["command"]) if arg == "--exclude-files"]assert any(".venv" in pattern and "node_modules" in pattern for pattern in excludes)+++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)+ bare = ' "token": "' + "ab12" * 10 + '",'+ assert not SECRETS.is_adjudicated("plugins/x/dev/types-source.json", hex_finding, bare)diff --git a/tests/test_windows_installer_ownership.py b/tests/test_windows_installer_ownership.pyindex 51d660b..d11462b 100644--- a/tests/test_windows_installer_ownership.py+++ b/tests/test_windows_installer_ownership.py@@ -40,7 +40,7 @@ def test_wrappers_preserve_public_entrypoints_version_and_profile_defaults() ->uninstall = _read(UNINSTALL)assert install.startswith("#!/usr/bin/env pwsh")assert uninstall.startswith("#!/usr/bin/env pwsh")- assert '$ClaudeBlogVersion = "2.3.0"' in install+ assert '$ClaudeBlogVersion = "2.3.1"' in installassert "https://raw.githubusercontent.com/AgriciDaniel/claude-blog/main/install.ps1" in installassert 'Join-Path $env:USERPROFILE ".claude"' in installassert 'Join-Path $env:USERPROFILE ".claude"' in uninstalldiff --git a/uv.lock b/uv.lockindex bd83b95..a3d55c2 100644--- a/uv.lock+++ b/uv.lock@@ -439,7 +439,7 @@ wheels = [[[package]]name = "claude-blog"-version = "2.3.0"+version = "2.3.1"source = { editable = "." }[package.optional-dependencies]