Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(marketplace): serve seo-cockpit from its own branch (#344)

Agrici Daniel702283fed32f
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index ce78929..2e31fcd 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -60,14 +60,20 @@
},
{
"name": "seo-cockpit",
- "source": "./plugins/seo-cockpit",
+ "source": {
+ "source": "git-subdir",
+ "url": "AgriciDaniel/claude-seo",
+ "path": "plugins/seo-cockpit",
+ "ref": "seo-cockpit",
+ "sha": "cf97b4785f4241b9367d654c60c7207dc3afcf68"
+ },
"description": "Optional mods companion for claude-seo (needs Claude Code 2.1.287+). A spend guard that holds paid SEO API calls against the claude-seo budget, and zero-token /seo-spend and /seo-doctor commands.",
"author": {
"name": "AgriciDaniel",
"url": "https://github.com/AgriciDaniel"
},
"category": "marketing",
- "homepage": "https://github.com/AgriciDaniel/claude-seo/tree/main/plugins/seo-cockpit",
+ "homepage": "https://github.com/AgriciDaniel/claude-seo/tree/seo-cockpit/plugins/seo-cockpit",
"keywords": [
"seo",
"mods",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c2db82f..30f7f97 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
to confirm an unpatched build. A managed or static host with no PHP signal is
reported as not exposed.
+### Fixed
+
+- **Claude Desktop installs claude-seo again (#344).** The claude-seo plugin
+ folder is the whole repository, and since v2.4.2 it held a second plugin
+ manifest at `plugins/seo-cockpit/.claude-plugin/plugin.json`, which Claude
+ Desktop refuses ("plugin.json must be at .claude-plugin/plugin.json at the
+ plugin root ... found nested"). seo-cockpit now lives on the `seo-cockpit`
+ branch of this repository and the marketplace installs it from there with a
+ `git-subdir` source pinned to a commit. It stays optional, keeps its install
+ id (`seo-cockpit@agricidaniel-claude-seo`) and moves to 0.3.4 (author and
+ homepage fields only). A new test fails if any nested plugin manifest
+ returns to the claude-seo tree.
+
## [2.4.2] - 2026-10-04
seo-cockpit, Google sign-in through your own account, and a schema-hook fix.
diff --git a/docs/WORKFLOW-public-private.md b/docs/WORKFLOW-public-private.md
index a239a6f..e328488 100644
--- a/docs/WORKFLOW-public-private.md
+++ b/docs/WORKFLOW-public-private.md
@@ -110,6 +110,32 @@ documentation, and links to those materials. Workflow state is repository
specific. Any other difference must be reviewed and explained before release.
Never force-sync the repositories to make their SHAs or trees identical.
+## seo-cockpit branch
+
+seo-cockpit is a separate plugin, so its files must not sit inside the
+claude-seo plugin folder (the whole repository, `source: "./"`). Claude
+Desktop skips a plugin whose folder contains another plugin's
+`.claude-plugin/plugin.json` (issue #344). The cockpit therefore lives on the
+`seo-cockpit` branch, under `plugins/seo-cockpit/`, and `main` carries no
+`plugins/` folder. `tests/test_manifest_consistency.py` enforces both rules.
+
+- **Base.** The branch is built on public release history only, never on a
+ private commit, because the same commit is published on `origin`. It must
+ never contain `research/` or other private-only files.
+- **Marketplace entry.** Both marketplaces install the cockpit with a
+ `git-subdir` source: `url` `AgriciDaniel/claude-seo`, `path`
+ `plugins/seo-cockpit`, `ref` `seo-cockpit` and a pinned 40-character `sha`.
+ The private marketplace points at the public repository too, so this entry
+ is identical in both trees and is not part of the identity divergence.
+- **Cockpit release.** Commit the change on `seo-cockpit`, run
+ `claude plugin validate plugins/seo-cockpit --strict` and
+ `claude plugin test plugins/seo-cockpit`, push the branch to `origin` (and
+ `aimh`), then bump `sha` in `.claude-plugin/marketplace.json` on `main` in
+ the next claude-seo release. Users get the new cockpit only when that `sha`
+ moves, so cockpit updates stay release-controlled.
+- **Order.** Push the `seo-cockpit` branch before the `main` commit that pins
+ its `sha`, so no published marketplace points at a commit GitHub lacks.
+
## Why two repos?
- The **public** repo is the user-facing artifact. Everything visible
diff --git a/plugins/seo-cockpit/.claude-plugin/plugin.json b/plugins/seo-cockpit/.claude-plugin/plugin.json
deleted file mode 100644
index 9956c61..0000000
--- a/plugins/seo-cockpit/.claude-plugin/plugin.json
+++ /dev/null
@@ -1,76 +0,0 @@
-{
- "name": "seo-cockpit",
- "version": "0.3.3",
- "description": "Mods companion for claude-seo: a spend guard on paid SEO APIs, a live audit band with a receipt, an economy mode, a visual cockpit (Search Console, rankings, Core Web Vitals, audit, Maps, spend) and zero-token commands",
- "author": {
- "name": "Agrici Daniel"
- },
- "homepage": "https://github.com/AgriciDaniel/claude-seo",
- "license": "MIT",
- "userConfig": {
- "claudeSeoRoot": {
- "type": "directory",
- "title": "claude-seo folder",
- "description": "Where claude-seo is installed. Leave empty to find it next to this plugin.",
- "default": ""
- },
- "python": {
- "type": "string",
- "title": "Python command",
- "description": "Interpreter for the stdlib-only cost ledger script (python3, python, or a full path).",
- "default": "python3"
- },
- "spendGuard": {
- "type": "boolean",
- "title": "Spend guard",
- "description": "Hold paid SEO API calls (DataForSEO, Ahrefs, Firecrawl, image generation, Moz, and others; see the README) against the claude-seo budget before they run.",
- "default": true
- },
- "auditBand": {
- "type": "boolean",
- "title": "Audit band",
- "description": "Show a live line above the prompt while a /seo audit runs: agents running and done, findings written, spend, time.",
- "default": true
- },
- "economy": {
- "type": "boolean",
- "title": "Economy mode",
- "description": "Run the five Opus agents (content, geo, sxo, cluster, drift) on Sonnet to cut audit cost. Their analysis may be less thorough.",
- "default": false
- },
- "site": {
- "type": "string",
- "title": "Default site",
- "description": "The site the cockpit opens on when the folder shows none: claude-seo.md, sc-domain:claude-seo.md or https://claude-seo.md/. A site chosen in a folder, or that folder's audit, still comes first.",
- "default": ""
- },
- "pageUrl": {
- "type": "string",
- "title": "Page for Core Web Vitals",
- "description": "For the Vitals and drift views of the default site: a URL or origin. Leave empty to use the site's home page.",
- "default": ""
- },
- "auditsFolder": {
- "type": "directory",
- "title": "Audits folder",
- "description": "Where you keep your audits (the <site>-audit/ folders /seo audit writes). The cockpit finds the shown site's audit there from any folder.",
- "default": ""
- },
- "googleAccount": {
- "type": "string",
- "title": "Google account",
- "description": "Which Google sign-in claude-seo uses for Search Console. auto: claude-seo's own order (its sign-in, then a service account, then your gcloud account). gcloud: always your account from 'gcloud auth application-default login', for properties you own.",
- "options": [
- "auto",
- "gcloud"
- ],
- "default": "auto"
- },
- "googleApiKey": {
- "type": "string",
- "title": "Google API key",
- "description": "For Core Web Vitals (CrUX) and PageSpeed. Kept in Claude Code's secure storage. Leave empty to use claude-seo's own setup.",
- "sensitive": true
- }
- }
-}
diff --git a/plugins/seo-cockpit/.gitignore b/plugins/seo-cockpit/.gitignore
deleted file mode 100644
index c743e50..0000000
--- a/plugins/seo-cockpit/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-.claude-plugin/types/
diff --git a/plugins/seo-cockpit/README.md b/plugins/seo-cockpit/README.md
deleted file mode 100644
index 5244f00..0000000
--- a/plugins/seo-cockpit/README.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# seo-cockpit
-
-An optional mods companion for [claude-seo](../../README.md). It runs inside Claude Code as a mod (a function-hook plugin), so it can enforce things a skill can only ask for.
-
-Tested on Claude Code 2.1.288 and 2.1.289. Mods need Claude Code 2.1.287 or newer; on older builds, install claude-seo alone.
-
-## What it does (0.3.0)
-
-**Spend guard.** Before a paid SEO API call runs, seo-cockpit checks it against the claude-seo DataForSEO budget (`scripts/dataforseo_costs.py`):
-
-| The call | What happens |
-|---|---|
-| DataForSEO MCP tool or the Merchant script, budget says approved | Runs. Afterwards each billed endpoint is logged at its table price, and Claude is told not to log it again |
-| DataForSEO, budget says needs approval (warn endpoint, unknown endpoint, above threshold) | You are asked, with the price and today's spend |
-| DataForSEO, daily cap would be exceeded | Held. Claude gets the reason |
-| Free DataForSEO lookups (locations, languages, filters, categories, model lists) | Run, with no check and nothing logged |
-| Ahrefs, Firecrawl, image generation (MCP or script), Moz, Keywords Everywhere, Google Cloud NLP, Indexing API, and curl or WebFetch calls to SE Ranking, Profound or the DataForSEO API | You are asked: hold, run once, or allow until reload |
-| Anything goes wrong (claude-seo not found, Python missing, unreadable ledger) | Held, with the fix in the message |
-
-The guard fails closed: if it cannot check a paid call before it runs, the call does not run. A call that already ran keeps its real result.
-
-Shell lines are checked one command at a time, so a cost check chained in front of a paid script does not hide it. The Merchant script is priced by what it bills: `search` (Google, or Amazon with `--marketplace amazon`), `sellers`, or `compare` (both).
-
-What is logged: only calls that succeeded and have a price in the cost table. A failed call, or an endpoint with no listed price, is not logged; Claude is told to log the real cost from the response instead.
-
-**Audit band.** While a `/seo audit` runs, a line above the prompt shows it live:
-
-```
-seo audit example.com 3 running, 9 done findings 9 spend $0.42 4m12s
-```
-
-It starts from the `/seo audit <url>` prompt or command, or from the first file written into a `<domain>-audit/` folder (so an audit asked for in plain words is caught too). Agents count as running when spawned and done when they finish (a background agent when its own turn ends). Other mods' bands stay visible below this one. A reload mid-audit keeps the band. Spend is what the guard logged during the audit. The band yields to Claude Code's surveys, has a hide button, and clears at your next prompt after the audit ends.
-
-**Receipt.** When the audit writes `audit-data.json`, one line appears under Claude's answer:
-
-```
-seo audit example.com: score 72/100 | weakest Schema 40, Content 55 | 17 agents | 12 findings files | spend $0.42 | 6m03s | example.com-audit/FULL-AUDIT-REPORT.md
-```
-
-**Economy mode** (off by default). Runs the five agents that use Opus (content, geo, sxo, cluster, drift) on Sonnet, to cut the cost of an audit. Their analysis may be less thorough. An agent call that names its own model is left alone.
-
-**Compaction.** If the conversation is compacted mid-audit, the summary is asked to keep the output folder, which agents finished and which are running, and the findings files written.
-
-**Visual cockpit** (`/seo-cockpit`). Opens on one Overview for the site this folder is about, with no setup:
-
-```
-claude-seo.md from this folder
-1: ● Audit 85/100 · weakest Schema 76
-2: ● Vitals good · LCP 703ms · INP 48ms · CLS 0.00
-3: ○ Search no Search Console access
-4: ○ Rankings no Search Console access
-5: ○ Maps no grid yet (/seo maps grid)
-6: ● Spend today $0.00 · 30 days $0.18
-r: Refresh e: Export
-```
-
-- **The site**, most specific first: one you chose in this folder (typed in the pane, or `/seo-cockpit <site>`), the site of this folder's newest `<domain>-audit/`, your **Default site** from `/config`, then the last site you used. Set a Default site once and the cockpit opens on it from any folder; the Audit row finds that site's audit wherever it was last seen.
-- **Google access** uses claude-seo's own setup, or the two Google settings in `/config`. If Search Console says "no access" for a property you own, a service account is being used: set "Google account" to `gcloud` after `gcloud auth application-default login --scopes=https://www.googleapis.com/auth/webmasters.readonly,https://www.googleapis.com/auth/cloud-platform`. Core Web Vitals needs a Google API key ("Google API key" in `/config`).
-- **Where it sits:** in a normal terminal the pane opens above the prompt and asks for as many rows as the screen can spare (drag it to resize; your size is kept). In Claude Code's fullscreen layout, 110 columns or wider, it docks beside the conversation at full height.
-- **Everything loads on open**, from free sources only (the audit and grid files, the cost ledger, and Search Console and CrUX through claude-seo's own Google setup). The last result shows at once and is replaced when the fresh one arrives.
-- **Missing data stays visible** as a dim line saying what to do, instead of an error screen.
-- **A row opens its detail** (Enter, a click, or its number): charts and tables for that source, `b` to go back.
-- **Keys** work while the pane has focus; otherwise the footer says `ctrl+x tab`. `r` refreshes everything, `e` exports HTML. Esc or Claude Code's own close mark closes the pane, and `/seo-cockpit` again toggles it.
-- **A status line** under the prompt keeps the summary in view: `SEO · claude-seo.md · audit 85/100 · CWV good`.
-
-Charts are drawn with block characters in the terminal and as SVG on the desktop app. Every view names its source and when it was fetched.
-
-**HTML dashboard.** `e` in the pane, or `/seo-cockpit export`, writes one self-contained page (`seo-cockpit-<time>.html` in the working folder) with every view as SVG charts and tables, readable in light and dark. Where no pane can be drawn (the VS Code chat panel), `/seo-cockpit` writes this page instead and says where it is.
-
-**Commands that cost no tokens.** These answer directly without starting a turn:
-
-- `/seo-spend`: DataForSEO spend today, over 7 and 30 days, by endpoint, with a 30-day spark row.
-- `/seo-doctor`: claude-seo runtime readiness, install location, and guard state.
-- `/seo-cockpit [site | export]`: the visual cockpit (for a given site, remembered), or with `export` the HTML dashboard.
-
-## Install
-
-```bash
-/plugin marketplace add AgriciDaniel/claude-seo
-/plugin install claude-seo@agricidaniel-claude-seo
-/plugin install seo-cockpit@agricidaniel-claude-seo
-```
-
-Auto-update is off by default for third-party marketplaces. Run `claude plugin update seo-cockpit@agricidaniel-claude-seo` to update.
-
-## Settings (`/config`)
-
-| Setting | Default | Meaning |
-|---|---|---|
-| claude-seo folder | empty | Where claude-seo lives. When empty, it looks next to this plugin (a checkout) and in the plugin cache (an install) |
-| Python command | `python3` | Runs the stdlib-only ledger scripts |
-| Spend guard | on | Turn off to let paid calls through unchecked |
-| Audit band | on | The live line above the prompt during an audit |
-| Economy mode | off | Run the five Opus agents on Sonnet |
-| Default site | empty | The site the cockpit opens on when a folder shows none (`claude-seo.md`, `sc-domain:claude-seo.md` or `https://claude-seo.md/`). A site chosen in a folder, or its audit, comes first |
-| Page for Core Web Vitals | empty | For the Vitals and drift views. Empty uses the property's site |
-| Audits folder | empty | Where you keep your `<site>-audit/` folders. The cockpit finds the shown site's audit there from any folder |
-| Google account | auto | `auto`: claude-seo's own order (its sign-in, a service account, then your gcloud account). `gcloud`: always your own account from `gcloud auth application-default login`, for properties you own |
-| Google API key | empty | For Core Web Vitals (CrUX). Sensitive: kept in Claude Code's secure storage. Empty uses claude-seo's own setup |
-
-## What it can and cannot see
-
-- It reads no credentials and no environment variables. The Python scripts handle auth.
-- It runs only `dataforseo_costs.py` and `runtime.py` from your claude-seo folder; the cockpit runs `gsc_query.py`, `crux_history.py` and `drift_history.py` through `runtime.py`, so they use claude-seo's own Google setup.
-- It writes one kind of file: the HTML dashboard, in the working folder, when you ask for it.
-- Spend is checked for DataForSEO only. Other providers have no cost table, so you decide.
-- "Allow until reload" is forgotten when the plugin reloads (a restart, or a change in `/config`), after which it asks again.
-
-## Known limits
-
-- **It matches what it can see.** A paid API reached by some route it does not recognise (a new script, an unknown host, a custom MCP server name) is not held.
-- **Parallel calls can overshoot the cap a little.** Each call is checked against the ledger before the others are logged, so several approved calls made at once can together pass the daily cap.
-- **`claude -p` and headless runs:** there is no one to ask, so every call that needs approval is held. Calls the budget approves still run.
-- **CLI only:** it needs `$.process` to run the ledger script. Where that is missing, DataForSEO calls are held and the commands report an error.
-- **Ask before rules:** a call your permission rules would deny can still raise its cost question first.
-- **The band and the pane draw in the terminal and the desktop app,** not in the VS Code chat panel or `claude -p`. The receipt line is plain text and shows wherever the answer does; the cockpit falls back to the HTML dashboard.
-- **The Maps view needs a saved grid.** Grids from before this release were only drawn in the chat; run the scan again to save one.
-
-## Status
-
-Verified on Claude Code 2.1.289, 2026-10-04:
-
-- `claude plugin test`: 85 of 85 kit tests pass (spend guard, Google settings, commands, audit band and receipt, economy mode, compaction, the cockpit Overview and details, site choice, export, and the pure logic)
-- type-check (`tsc`, strict) and `claude plugin validate --strict`
-- a static security scan (reach L2, no critical or high flags)
-- live in Claude Code on a real site: the cockpit inline and docked, every Overview row with live CrUX and Search Console data, `/seo-spend` and `/seo-doctor`
-- the HTML export rendered in Chromium, light and dark
-
-Not yet observed live: the audit band during a running `/seo audit` (covered by kit tests).
-
-## Development
-
-```bash
-# Type-check against the typings Claude Code writes beside the plugin on load
-npx -p [email protected] tsc -p plugins/seo-cockpit
-claude plugin validate plugins/seo-cockpit --strict
-claude plugin test plugins/seo-cockpit
-```
-
-Layout: `hooks/register.ts` is the only file that calls `on()`. The rules live in `hooks/lib/` (pure, no `$`), and the tests are in `tests/`.
diff --git a/plugins/seo-cockpit/hooks/hooks.json b/plugins/seo-cockpit/hooks/hooks.json
deleted file mode 100644
index 9f45101..0000000
--- a/plugins/seo-cockpit/hooks/hooks.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "modules": ["./register.ts"]
-}
diff --git a/plugins/seo-cockpit/hooks/lib/audit.ts b/plugins/seo-cockpit/hooks/lib/audit.ts
deleted file mode 100644
index fd47852..0000000
--- a/plugins/seo-cockpit/hooks/lib/audit.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * Following a claude-seo audit from what the session does: the prompt that
- * starts it, the agents it spawns, the files it writes. Pure: no `$`.
- *
- * An audit writes everything under `{domain}-audit/`: per-agent
- * `findings/*.md`, then `audit-data.json` with the health score
- * (skills/seo-audit/SKILL.md, "Structured Audit Data Envelope").
- */
-
-import { usd } from './verdict'
-
-export type AgentRun = { type: string; state: 'running' | 'done' | 'failed'; startMs: number; endMs?: number; agentId?: string }
-
-export type Audit = {
- domain: string
- startMs: number
- /** By the Agent tool call's id. */
- agents: Record<string, AgentRun>
- /** Findings files written, by file name. */
- findings: string[]
- /** The `{domain}-audit` folder, once a write shows where it is. */
- dir: string | null
- /** What the spend guard logged while the audit ran. */
- spentUsd: number
- score: number | null
- categories: ReadonlyArray<{ name: string; score: number }>
- finishMs: number | null
-}
-
-/** The five claude-seo agents that run on Opus (agents/*.md frontmatter). */
-export const OPUS_AGENTS: ReadonlySet<string> = new Set(['seo-content', 'seo-geo', 'seo-sxo', 'seo-cluster', 'seo-drift'])
-
-/** An agent type without its plugin namespace (`claude-seo:seo-geo` becomes `seo-geo`). */
-export const bareType = (type: string): string => type.split(':').at(-1) ?? type
-
-export const isSeoAgent = (type: string): boolean => /^seo-[a-z-]+$/.test(bareType(type))
-
-/** The model an agent is routed to in economy mode, or null to leave it alone. */
-export const economyModel = (type: string): string | null => (OPUS_AGENTS.has(bareType(type)) ? 'sonnet' : null)
-
-/** The host of a URL or bare domain, without `www.`; null when there is none. */
-export function domainOf(target: string): string | null {
- const text = target.trim().replace(/^["'<]+|["'>]+$/g, '')
-
- try {
- const host = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`).hostname.toLowerCase()
-
- return /\./.test(host) ? host.replace(/^www\./, '') : null
- } catch {
- return null
- }
-}
-
-/** The audit a prompt starts (`/seo audit <url>`, also namespaced as `/claude-seo:seo audit`), or null. */
-export function auditFromPrompt(text: string, nowMs: number): Audit | null {
- const match = /^\s*\/(?:claude-seo:)?seo\s+audit\s+(\S+)/i.exec(text)
- const domain = match?.[1] === undefined ? null : domainOf(match[1])
-
- return domain === null ? null : newAudit(domain, nowMs)
-}
-
-export function newAudit(domain: string, nowMs: number): Audit {
- return { domain, startMs: nowMs, agents: {}, findings: [], dir: null, spentUsd: 0, score: null, categories: [], finishMs: null }
-}
-
-/** Where a written file sits in an audit folder, if it does. */
-export function auditPathOf(path: string): { dir: string; domain: string; kind: 'finding' | 'data' | 'other'; name: string } | null {
- const match = /^(.*?([^/\\]+)-audit)[/\\](.+)$/.exec(path)
-
- if (match === null || match[1] === undefined || match[2] === undefined || match[3] === undefined) {
- return null
- }
-
- const rest = match[3]
- const name = rest.split(/[/\\]/).at(-1) ?? rest
- const kind = /^findings[/\\][^/\\]+\.md$/.test(rest) ? 'finding' : rest === 'audit-data.json' ? 'data' : 'other'
-
- return { dir: match[1], domain: match[2], kind, name }
-}
-
-/** The health score and category scores from an audit-data.json text; nulls when unreadable. */
-export function scoresOf(text: string): { score: number | null; categories: Array<{ name: string; score: number }> } {
- try {
- const data = JSON.parse(text) as { summary?: { health_score?: unknown }; categories?: unknown }
- const raw = data.summary?.health_score
- const categories = Array.isArray(data.categories)
- ? data.categories.flatMap(row => {
- const { name, score } = (row ?? {}) as { name?: unknown; score?: unknown }
-
- return typeof name === 'string' && typeof score === 'number' && Number.isFinite(score) ? [{ name, score }] : []
- })
- : []
-
- return { score: typeof raw === 'number' && Number.isFinite(raw) ? raw : null, categories }
- } catch {
- return { score: null, categories: [] }
- }
-}
-
-/** Records a write; returns the audit it belongs to (started from the folder when none is running). */
-export function noteWrite(audit: Audit | null, path: string, content: string | undefined, nowMs: number): Audit | null {
- const where = auditPathOf(path)
-
- if (where === null) {
- return audit
- }
-
- const current = audit === null || audit.finishMs !== null ? newAudit(domainOf(where.domain) ?? where.domain, nowMs) : audit
- const next: Audit = { ...current, dir: where.dir }
-
- if (where.kind === 'finding' && !next.findings.includes(where.name)) {
- next.findings = [...next.findings, where.name]
- }
-
- if (where.kind === 'data' && content !== undefined) {
- const { score, categories } = scoresOf(content)
-
- next.score = score
- next.categories = categories
- }
-
- return next
-}
-
-const count = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
-
-export const elapsed = (ms: number): string => {
- const seconds = Math.max(0, Math.round(ms / 1000))
-
- return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s`
-}
-
-/** Agent counts: running, done (failed ones count as done, and are named). */
-export function tally(audit: Audit): { running: number; done: number; failed: number } {
- const runs = Object.values(audit.agents)
-
- return {
- running: runs.filter(run => run.state === 'running').length,
- done: runs.filter(run => run.state !== 'running').length,
- failed: runs.filter(run => run.state === 'failed').length,
- }
-}
-
-/** The band's one line, cut to `columns`. */
-export function bandText(audit: Audit, nowMs: number, columns: number, isEconomy: boolean): string {
- const { running, done, failed } = tally(audit)
- const parts = [
- `seo audit ${audit.domain}`,
- audit.finishMs !== null ? `done${audit.score === null ? '' : `, score ${audit.score}/100`}` : `${running} running, ${done} done${failed > 0 ? ` (${failed} failed)` : ''}`,
- `findings ${audit.findings.length}`,
- `spend ${usd(audit.spentUsd)}`,
- elapsed((audit.finishMs ?? nowMs) - audit.startMs),
- ...(isEconomy ? ['economy'] : []),
- ]
- const line = parts.join(' ')
-
- return line.length <= columns ? line : `${line.slice(0, Math.max(0, columns - 1))}…`
-}
-
-/** The line shown under the answer once the audit's data file is written. */
-export function receiptText(audit: Audit, nowMs: number): string {
- const { done, failed } = tally(audit)
- const report = audit.dir === null ? `${audit.domain}-audit/` : `${audit.dir}/FULL-AUDIT-REPORT.md`
- const weakest = [...audit.categories].sort((a, b) => a.score - b.score).slice(0, 2).map(row => `${row.name} ${row.score}`)
-
- return [
- `seo audit ${audit.domain}: ${audit.score === null ? 'no score' : `score ${audit.score}/100`}`,
- weakest.length > 0 ? `weakest ${weakest.join(', ')}` : null,
- `${count(done, 'agent')}${failed > 0 ? ` (${failed} failed)` : ''}`,
- count(audit.findings.length, 'findings file'),
- `spend ${usd(audit.spentUsd)}`,
- elapsed(nowMs - audit.startMs),
- report,
- ]
- .filter((part): part is string => part !== null)
- .join(' | ')
-}
-
-/** What compaction is asked to keep while an audit runs. */
-export function compactInstructions(audit: Audit): string {
- const done = Object.values(audit.agents).filter(run => run.state !== 'running').map(run => bareType(run.type))
- const running = Object.values(audit.agents).filter(run => run.state === 'running').map(run => bareType(run.type))
-
- return [
- `A claude-seo audit of ${audit.domain} is in progress. Keep in the summary:`,
- `- the output folder: ${audit.dir ?? `${audit.domain}-audit/`} (findings in findings/, then audit-data.json, FULL-AUDIT-REPORT.md, ACTION-PLAN.md)`,
- `- agents finished: ${done.length > 0 ? done.join(', ') : 'none yet'}; still running: ${running.length > 0 ? running.join(', ') : 'none'}`,
- `- findings files written: ${audit.findings.length > 0 ? audit.findings.join(', ') : 'none yet'}`,
- '- the business type detected, the crawl scope, and any finding not yet written to a file',
- ].join('\n')
-}
diff --git a/plugins/seo-cockpit/hooks/lib/charts.ts b/plugins/seo-cockpit/hooks/lib/charts.ts
deleted file mode 100644
index 61c0250..0000000
--- a/plugins/seo-cockpit/hooks/lib/charts.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-/**
- * Charts as data: text rows for the terminal, SVG strings for the desktop and
- * VS Code surfaces, and a self-contained HTML page for export. Pure.
- *
- * SVG text and axes use `currentColor` so a chart reads on light and dark
- * backgrounds; series and status colors are fixed mid-tones that hold on both.
- */
-
-export type Series = { name: string; values: ReadonlyArray<number | null>; color: string }
-
-export type Chart =
- | { kind: 'line'; title: string; series: readonly Series[]; xLabels: readonly [string, string]; invert?: boolean; unit?: string; bands?: { good: number; poor: number } }
- | { kind: 'bars'; title: string; rows: ReadonlyArray<{ label: string; value: number; color: string; text?: string }>; max: number }
- | { kind: 'grid'; title: string; ranks: ReadonlyArray<ReadonlyArray<number | null>> }
-
-export const COLORS = {
- blue: '#3b82f6',
- violet: '#8b5cf6',
- good: '#16a34a',
- warn: '#d97706',
- poor: '#dc2626',
- muted: '#8a8f98',
-} as const
-
-/** Green from 80, amber from 50, red below. */
-export const scoreColor = (score: number): string => (score >= 80 ? COLORS.good : score >= 50 ? COLORS.warn : COLORS.poor)
-
-/** Local-pack style: top 3 green, 4 to 10 amber, beyond red, absent grey. */
-export const rankColor = (rank: number | null): string => (rank === null ? COLORS.muted : rank <= 3 ? COLORS.good : rank <= 10 ? COLORS.warn : COLORS.poor)
-
-/** Good, needs improvement, or poor against a metric's two thresholds. */
-export const vitalColor = (value: number, good: number, poor: number): string => (value <= good ? COLORS.good : value <= poor ? COLORS.warn : COLORS.poor)
-
-const SPARK = '▁▂▃▄▅▆▇█'
-const escape = (text: string): string => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
-
-export const compact = (value: number): string =>
- Math.abs(value) >= 1_000_000 ? `${(value / 1_000_000).toFixed(1)}M` : Math.abs(value) >= 10_000 ? `${Math.round(value / 1000)}k` : Math.abs(value) >= 1000 ? `${(value / 1000).toFixed(1)}k` : `${Math.round(value * 100) / 100}`
-
-/** Squeezes a series to at most `width` points by averaging buckets. */
-export function resample(values: ReadonlyArray<number | null>, width: number): Array<number | null> {
- if (values.length <= width) {
- return [...values]
- }
-
- return Array.from({ length: width }, (_, i) => {
- const bucket = values.slice(Math.floor((i * values.length) / width), Math.floor(((i + 1) * values.length) / width)).filter((v): v is number => v !== null)
-
- return bucket.length === 0 ? null : bucket.reduce((a, b) => a + b, 0) / bucket.length
- })
-}
-
-/** One block character per value between the series' own min and max; gaps stay blank. */
-export function sparkRow(values: ReadonlyArray<number | null>, width: number, invert = false): string {
- const points = resample(values, width)
- const present = points.filter((v): v is number => v !== null)
- const low = Math.min(...present)
- const high = Math.max(...present)
-
- return points
- .map(value => {
- if (value === null) {
- return ' '
- }
-
- const share = high === low ? 0.5 : (value - low) / (high - low)
-
- return SPARK[Math.round((invert ? 1 - share : share) * (SPARK.length - 1))] ?? ' '
- })
- .join('')
-}
-
-/** A horizontal bar of `width` cells for `value` out of `max`. */
-export function barRow(value: number, max: number, width: number): string {
- const cells = max <= 0 ? 0 : Math.max(0, Math.min(width, Math.round((value / max) * width)))
-
- return '█'.repeat(cells) + '░'.repeat(width - cells)
-}
-
-/** First and last present values, for "from ... to ..." labels. */
-export function endsOf(values: ReadonlyArray<number | null>): { first: number | null; last: number | null } {
- const present = values.filter((v): v is number => v !== null)
-
- return { first: present[0] ?? null, last: present.at(-1) ?? null }
-}
-
-// ------------------------------------------------------------------- SVG
-
-const W = 560
-
-function lineSvg(chart: Extract<Chart, { kind: 'line' }>): string {
- const height = 170
- const pad = { left: 46, right: 12, top: 24, bottom: 26 }
- const plotW = W - pad.left - pad.right
- const plotH = height - pad.top - pad.bottom
- const all = chart.series.flatMap(s => s.values.filter((v): v is number => v !== null))
- const bandValues = chart.bands === undefined ? [] : [chart.bands.good, chart.bands.poor]
- let low = Math.min(...all, ...bandValues)
- let high = Math.max(...all, ...bandValues)
-
- if (!Number.isFinite(low) || !Number.isFinite(high)) {
- low = 0
- high = 1
- }
-
- if (high === low) {
- high = low + 1
- }
-
- const y = (v: number) => {
- const share = (v - low) / (high - low)
-
- return pad.top + (chart.invert === true ? share : 1 - share) * plotH
- }
-
- const longest = Math.max(1, ...chart.series.map(s => s.values.length))
- const x = (i: number) => pad.left + (longest === 1 ? plotW / 2 : (i / (longest - 1)) * plotW)
- const parts: string[] = []
-
- if (chart.bands !== undefined) {
- const { good, poor } = chart.bands
-
- parts.push(
- `<rect x="${pad.left}" y="${Math.min(y(good), y(low))}" width="${plotW}" height="${Math.abs(y(good) - y(low))}" fill="${COLORS.good}" opacity="0.10"/>`,
- `<rect x="${pad.left}" y="${Math.min(y(poor), y(good))}" width="${plotW}" height="${Math.abs(y(poor) - y(good))}" fill="${COLORS.warn}" opacity="0.10"/>`,
- `<rect x="${pad.left}" y="${Math.min(y(high), y(poor))}" width="${plotW}" height="${Math.abs(y(high) - y(poor))}" fill="${COLORS.poor}" opacity="0.10"/>`,
- // Labelled threshold lines, so the zones read without a legend.
- `<line x1="${pad.left}" y1="${y(good)}" x2="${pad.left + plotW}" y2="${y(good)}" stroke="${COLORS.good}" stroke-dasharray="4 3"/>`,
- `<text x="${pad.left + plotW - 4}" y="${y(good) - 4}" text-anchor="end" font-size="10" fill="${COLORS.good}">good ${escape(compact(good))}</text>`,
- `<line x1="${pad.left}" y1="${y(poor)}" x2="${pad.left + plotW}" y2="${y(poor)}" stroke="${COLORS.poor}" stroke-dasharray="4 3"/>`,
- `<text x="${pad.left + plotW - 4}" y="${y(poor) + 12}" text-anchor="end" font-size="10" fill="${COLORS.poor}">poor ${escape(compact(poor))}</text>`,
- )
- }
-
- parts.push(
- `<line x1="${pad.left}" y1="${pad.top + plotH}" x2="${pad.left + plotW}" y2="${pad.top + plotH}" stroke="currentColor" opacity="0.3"/>`,
- `<text x="${pad.left - 6}" y="${y(high) + 4}" text-anchor="end" font-size="10" fill="currentColor" opacity="0.7">${escape(compact(high))}</text>`,
- `<text x="${pad.left - 6}" y="${y(low) + 4}" text-anchor="end" font-size="10" fill="currentColor" opacity="0.7">${escape(compact(low))}</text>`,
- `<text x="${pad.left}" y="${height - 8}" font-size="10" fill="currentColor" opacity="0.7">${escape(chart.xLabels[0])}</text>`,
- `<text x="${pad.left + plotW}" y="${height - 8}" text-anchor="end" font-size="10" fill="currentColor" opacity="0.7">${escape(chart.xLabels[1])}</text>`,
- )
-
- chart.series.forEach((series, index) => {
- const segments: string[] = []
- let open = false
-
- series.values.forEach((value, i) => {
- if (value === null) {
- open = false
-
- return
- }
-
- segments.push(`${open ? 'L' : 'M'}${x(i).toFixed(1)},${y(value).toFixed(1)}`)
- open = true
- })
- parts.push(`<path d="${segments.join(' ')}" fill="none" stroke="${series.color}" stroke-width="2" stroke-linejoin="round"/>`)
- parts.push(`<text x="${pad.left + index * 150}" y="14" font-size="11" fill="${series.color}">● ${escape(series.name)}</text>`)
- })
-
- return svgDoc(height, chart.title, parts)
-}
-
-function barsSvg(chart: Extract<Chart, { kind: 'bars' }>): string {
- const rowH = 22
- const labelW = 170
- const height = 12 + chart.rows.length * rowH
- const plotW = W - labelW - 70
- const parts = chart.rows.flatMap((row, i) => {
- const y = 8 + i * rowH
- const width = chart.max <= 0 ? 0 : Math.max(0, Math.min(plotW, (row.value / chart.max) * plotW))
-
- return [
- `<text x="${labelW - 8}" y="${y + 14}" text-anchor="end" font-size="11" fill="currentColor">${escape(row.label.length > 26 ? `${row.label.slice(0, 25)}…` : row.label)}</text>`,
- `<rect x="${labelW}" y="${y + 3}" width="${plotW}" height="14" rx="3" fill="currentColor" opacity="0.08"/>`,
- `<rect x="${labelW}" y="${y + 3}" width="${width.toFixed(1)}" height="14" rx="3" fill="${row.color}"/>`,
- `<text x="${labelW + plotW + 8}" y="${y + 14}" font-size="11" fill="currentColor">${escape(row.text ?? compact(row.value))}</text>`,
- ]
- })
-
- return svgDoc(height, chart.title, parts)
-}
-
-function gridSvg(chart: Extract<Chart, { kind: 'grid' }>): string {
- const size = Math.max(1, chart.ranks.length)
- const cell = Math.min(40, Math.floor(300 / size))
- const height = size * cell + 40
- const parts = chart.ranks.flatMap((row, r) =>
- row.flatMap((rank, c) => [
- `<rect x="${20 + c * cell}" y="${10 + r * cell}" width="${cell - 3}" height="${cell - 3}" rx="4" fill="${rankColor(rank)}"/>`,
- `<text x="${20 + c * cell + (cell - 3) / 2}" y="${10 + r * cell + (cell - 3) / 2 + 4}" text-anchor="middle" font-size="11" fill="#ffffff">${rank === null ? '-' : rank > 20 ? '20+' : rank}</text>`,
- ]),
- )
- const legendY = 10 + size * cell + 18
-
- parts.push(
- ...[
- ['1-3', COLORS.good],
- ['4-10', COLORS.warn],
- ['11+', COLORS.poor],
- ['not found', COLORS.muted],
- ].map(([label, color], i) => `<rect x="${20 + i * 90}" y="${legendY - 9}" width="10" height="10" rx="2" fill="${color}"/><text x="${34 + i * 90}" y="${legendY}" font-size="11" fill="currentColor">${label}</text>`),
- )
-
- return svgDoc(height, chart.title, parts)
-}
-
-function svgDoc(height: number, title: string, parts: readonly string[]): string {
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${height}" width="${W}" height="${height}" font-family="system-ui, sans-serif" role="img"><title>${escape(title)}</title>${parts.join('')}</svg>`
-}
-
-/** The chart as an SVG string (well under the 131,072-character limit for these sizes). */
-export function svgOf(chart: Chart): { source: string; height: number } {
- const source = chart.kind === 'line' ? lineSvg(chart) : chart.kind === 'bars' ? barsSvg(chart) : gridSvg(chart)
- const height = Number(/height="(\d+)"/.exec(source)?.[1] ?? 200)
-
- return { source, height }
-}
-
-// ------------------------------------------------------------------- HTML
-
-export type Section = {
- heading: string
- source: string
- kpis: ReadonlyArray<{ label: string; value: string }>
- charts: readonly Chart[]
- tables: ReadonlyArray<{ head: readonly string[]; rows: ReadonlyArray<readonly string[]> }>
- notes: readonly string[]
-}
-
-/** A self-contained page (inline CSS and SVG, no scripts), readable in light and dark. */
-export function htmlPage(title: string, generated: string, sections: readonly Section[]): string {
- const body = sections
- .map(
- section => `<section><h2>${escape(section.heading)}</h2><p class="src">${escape(section.source)}</p>
-${section.kpis.length > 0 ? `<div class="kpis">${section.kpis.map(k => `<div class="kpi"><span>${escape(k.label)}</span><b>${escape(k.value)}</b></div>`).join('')}</div>` : ''}
-${section.charts.map(chart => `<figure>${svgOf(chart).source}</figure>`).join('\n')}
-${section.tables.map(t => `<table><thead><tr>${t.head.map(h => `<th>${escape(h)}</th>`).join('')}</tr></thead><tbody>${t.rows.map(r => `<tr>${r.map(c => `<td>${escape(c)}</td>`).join('')}</tr>`).join('')}</tbody></table>`).join('\n')}
-${section.notes.map(n => `<p class="note">${escape(n)}</p>`).join('')}</section>`,
- )
- .join('\n')
-
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)}</title>
-<style>
-:root{--bg:#f7f7f5;--fg:#1d1f23;--card:#ffffff;--line:#e3e3df;--muted:#6b7079}
-@media (prefers-color-scheme:dark){:root{--bg:#16181c;--fg:#e8e8e6;--card:#1f2228;--line:#30343b;--muted:#9aa0a8}}
-*{box-sizing:border-box}body{margin:0;padding:24px 16px;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
-main{max-width:760px;margin:0 auto}h1{font-size:24px;margin:0 0 4px}.gen{color:var(--muted);margin:0 0 24px}
-section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin:0 0 16px}
-h2{font-size:18px;margin:0}.src{color:var(--muted);font-size:13px;margin:2px 0 12px}
-.kpis{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 12px}.kpi{border:1px solid var(--line);border-radius:8px;padding:6px 10px}.kpi span{display:block;color:var(--muted);font-size:12px}.kpi b{font-size:17px}
-figure{margin:0 0 12px;color:var(--fg)}figure svg{max-width:100%;height:auto}
-table{width:100%;border-collapse:collapse;font-size:13px;margin:0 0 12px}th,td{text-align:left;padding:5px 6px;border-bottom:1px solid var(--line)}th{color:var(--muted);font-weight:600}
-.note{color:var(--muted);font-size:13px;margin:4px 0}
-</style></head><body><main><h1>${escape(title)}</h1><p class="gen">${escape(generated)}</p>
-${body}
-</main></body></html>`
-}
diff --git a/plugins/seo-cockpit/hooks/lib/format.ts b/plugins/seo-cockpit/hooks/lib/format.ts
deleted file mode 100644
index 7dee5a8..0000000
--- a/plugins/seo-cockpit/hooks/lib/format.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Plain-text answers for the zero-token commands. Pure.
- */
-
-import { usd } from './verdict'
-
-const SPARK = '▁▂▃▄▅▆▇█'
-
-/** One block character per value, scaled to the largest. */
-export function spark(values: readonly number[]): string {
- const top = Math.max(0, ...values)
-
- return values
- .map(value => (top <= 0 || value <= 0 ? ' ' : SPARK[Math.min(SPARK.length - 1, Math.floor((value / top) * (SPARK.length - 1)))]))
- .join('')
-}
-
-type Today = { date?: unknown; total_usd?: unknown; daily_limit_usd?: unknown; remaining_usd?: unknown; calls?: unknown; by_endpoint?: unknown }
-type Summary = { daily_totals?: unknown; grand_total_usd?: unknown; total_calls?: unknown; period_days?: unknown }
-
-const n = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
-
-/** The last `days` calendar days ending at `today` (YYYY-MM-DD), oldest first. */
-export function lastDays(today: string, days: number): string[] {
- const end = new Date(`${today}T00:00:00Z`)
-
- if (Number.isNaN(end.getTime())) {
- return []
- }
-
- return Array.from({ length: days }, (_, i) => {
- const day = new Date(end.getTime() - (days - 1 - i) * 86_400_000)
-
- return day.toISOString().slice(0, 10)
- })
-}
-
-/**
- * The /seo-spend answer from `dataforseo_costs.py today` and `summary --days 30`.
- */
-export function spendText(today: Today, summary: Summary): string {
- const date = typeof today.date === 'string' ? today.date : ''
- const totals = typeof summary.daily_totals === 'object' && summary.daily_totals !== null ? (summary.daily_totals as Record<string, { total_usd?: unknown; calls?: unknown }>) : {}
- const days = lastDays(date, 30)
- const series = days.map(day => n(totals[day]?.total_usd))
- const sum = (values: readonly number[]) => values.reduce((a, b) => a + b, 0)
- // The same 30 calendar days for the total, the call count and the spark row
- // (the script's own window is "now minus 30 days", which reaches into day 31).
- const monthCalls = sum(days.map(day => n(totals[day]?.calls)))
- const allRows = typeof today.by_endpoint === 'object' && today.by_endpoint !== null ? Object.entries(today.by_endpoint as Record<string, { cost_usd?: unknown; calls?: unknown }>) : []
- // A ledger reset leaves a $0 audit row; it is not a call.
- const resets = n(allRows.find(([endpoint]) => endpoint === '_audit_reset')?.[1].calls)
- const byEndpoint = allRows.filter(([endpoint]) => endpoint !== '_audit_reset')
- const lines = [
- `DataForSEO spend (claude-seo ledger)`,
- ` today ${usd(n(today.total_usd))} of ${usd(n(today.daily_limit_usd))} cap, ${n(today.calls) - resets} calls, ${usd(n(today.remaining_usd))} left`,
- ` 7 days ${usd(sum(series.slice(-7)))}`,
- ` 30 days ${usd(days.length > 0 ? sum(series) : n(summary.grand_total_usd))}, ${days.length > 0 ? monthCalls : n(summary.total_calls)} calls`,
- ]
-
- if (days.length > 0) {
- lines.push(` last 30 days |${spark(series)}| ${days[0]} to ${days.at(-1)}`)
- }
-
- if (byEndpoint.length > 0) {
- lines.push(' today by endpoint:')
-
- for (const [endpoint, row] of byEndpoint.sort((a, b) => n(b[1].cost_usd) - n(a[1].cost_usd)).slice(0, 8)) {
- lines.push(` ${usd(n(row.cost_usd)).padStart(8)} ${n(row.calls)}x ${endpoint}`)
- }
- }
-
- return lines.join('\n')
-}
-
-type Doctor = { ready?: unknown; mode?: unknown; plugin_version?: unknown; python_version?: unknown; browser_ready?: unknown; reasons?: unknown }
-
-/** The /seo-doctor answer from `claude-seo doctor --json`. */
-export function doctorText(doctor: Doctor, root: string): string {
- const reasons = Array.isArray(doctor.reasons) ? doctor.reasons.filter((reason): reason is string => typeof reason === 'string') : []
- const lines = [
- `claude-seo ${typeof doctor.plugin_version === 'string' ? doctor.plugin_version : '?'} at ${root}`,
- ` runtime ${doctor.ready === true ? 'ready' : 'setup required'} (${typeof doctor.mode === 'string' ? doctor.mode : '?'} mode, Python ${typeof doctor.python_version === 'string' ? doctor.python_version : '?'})`,
- ` Chromium ${doctor.browser_ready === true ? 'ready' : 'not installed'}`,
- ...reasons.map(reason => ` reason ${reason}`),
- ]
-
- if (doctor.ready !== true) {
- lines.push(` fix run: "${root}/scripts/claude-seo" setup`)
- }
-
- return lines.join('\n')
-}
diff --git a/plugins/seo-cockpit/hooks/lib/overview.ts b/plugins/seo-cockpit/hooks/lib/overview.ts
deleted file mode 100644
index e693a8a..0000000
--- a/plugins/seo-cockpit/hooks/lib/overview.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * The cockpit's Overview: which site it is about, and one line per source.
- * Pure. Built from the tab models, so the Overview and the detail views never
- * disagree.
- */
-
-import type { TabId, TabModel } from './tabs'
-
-/** The Overview's rows, in order of what a person checks first. */
-export const ROWS: ReadonlyArray<{ id: TabId; label: string; key: string }> = [
- { id: 'audit', label: 'Audit', key: '1' },
- { id: 'vitals', label: 'Vitals', key: '2' },
- { id: 'gsc', label: 'Search', key: '3' },
- { id: 'rankings', label: 'Rankings', key: '4' },
- { id: 'maps', label: 'Maps', key: '5' },
- { id: 'spend', label: 'Spend', key: '6' },
-]
-
-export type RowState = 'loading' | 'ok' | 'missing' | 'error'
-
-export type Row = { id: TabId; label: string; key: string; state: RowState; line: string }
-
-/** The host of a URL, `sc-domain:` property or bare domain; null when there is none. */
-export function hostOf(value: string): string | null {
- const text = value.trim().replace(/^sc-domain:/i, '')
-
- if (text === '') {
- return null
- }
-
- try {
- const host = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`).hostname.toLowerCase()
-
- return host.includes('.') ? host.replace(/^www\./, '') : null
- } catch {
- return null
- }
-}
-
-/** The site an audit folder is about: `meta.site` in its audit-data.json, else the folder name. */
-export function siteOfAudit(folder: string, data: unknown): string | null {
- const meta = (data as { meta?: { site?: unknown } } | null)?.meta
- const fromData = typeof meta?.site === 'string' ? hostOf(meta.site) : null
-
- return fromData ?? hostOf(folder.replace(/-audit$/, ''))
-}
-
-/**
- * The target, most specific first: what the person chose for this folder
- * (typed in the pane, or `/seo-cockpit <site>`), the site this folder's audit
- * is about, then the default from /config. The caller falls back to the last
- * site used when all three are empty.
- */
-export function chooseTarget(setting: string, typed: string | null, inferred: string | null): { host: string | null; source: 'typed' | 'folder' | 'setting' | null } {
- const chosen = typed === null ? null : hostOf(typed)
-
- if (chosen !== null) {
- return { host: chosen, source: 'typed' }
- }
-
- if (inferred !== null) {
- return { host: inferred, source: 'folder' }
- }
-
- const fallback = hostOf(setting)
-
- return fallback === null ? { host: null, source: null } : { host: fallback, source: 'setting' }
-}
-
-const kpi = (model: TabModel, label: string): string | undefined => model.kpis.find(k => k.label === label)?.value
-
-const short = (text: string, max = 60): string => (text.length <= max ? text : `${text.slice(0, max - 1)}…`)
-
-/** Turns a script's error into a short reason a person can act on. */
-function reasonOf(id: TabId, error: string): string {
- if (/permission denied/i.test(error)) {
- return 'no Search Console access'
- }
-
- if (/not set up|runtime is not ready/i.test(error)) {
- return 'claude-seo runtime not set up: run /seo setup'
- }
-
- if (/credential|api key|google access|oauth/i.test(error)) {
- return 'Google not connected: run /seo google setup'
- }
-
- if (/no saved geo-grid/i.test(error)) {
- return 'no grid yet (/seo maps grid)'
- }
-
- if (/no audit found/i.test(error)) {
- return 'no audit yet (/seo audit)'
- }
-
- if (/no url to measure/i.test(error)) {
- return 'needs a site: type it above'
- }
-
- return short(error)
-}
-
-/** One Overview line for a source. */
-export function rowOf(id: TabId, model: TabModel | undefined, isLoading: boolean): Row {
- const base = ROWS.find(row => row.id === id) ?? { id, label: id, key: '' }
-
- if (model === undefined) {
- return { ...base, state: isLoading ? 'loading' : 'missing', line: isLoading ? 'checking…' : 'not loaded' }
- }
-
- if (model.error !== null) {
- const isMissing = /no audit found|no saved geo-grid|no url to measure|not connected|permission denied|not set up/i.test(model.error)
-
- return { ...base, state: isMissing ? 'missing' : 'error', line: reasonOf(id, model.error) }
- }
-
- const parts: Array<string | undefined> = (() => {
- switch (id) {
- case 'audit': {
- const bars = model.charts[0]
- const weakest = bars?.kind === 'bars' ? bars.rows[0] : undefined
-
- // "Schema / Structured Data" reads as "Schema" on one line.
- const name = weakest?.label.split(/\s[/(]/)[0]
-
- return [kpi(model, 'Health score'), weakest === undefined ? undefined : `weakest ${name} ${weakest.value}`]
- }
- case 'vitals': {
- // The verdict first, so a narrow pane keeps it: "good · LCP 703ms · INP 48ms · CLS 0.00".
- const values = model.kpis.map(k => `${k.label.replace(' p75', '')} ${k.value.replace(/ (good|needs work|poor)$/, '').replace(' ms', 'ms')}`)
- const verdict = model.kpis.some(k => / poor$/.test(k.value)) ? 'poor' : model.kpis.some(k => / needs work$/.test(k.value)) ? 'needs work' : 'good'
-
- return [verdict, ...values]
- }
- case 'gsc':
- return [`clicks ${kpi(model, 'Clicks, 28 days') ?? '?'}`, `impr. ${kpi(model, 'Impressions, 28 days') ?? '?'}`]
- case 'rankings':
- return [`avg pos ${kpi(model, 'Avg position, now') ?? '?'}`, `was ${kpi(model, '90 days ago') ?? '?'}`, `top 3: ${kpi(model, 'Queries in top 3') ?? '0'}`]
- case 'maps':
- return [`SoLV ${kpi(model, 'Share of local voice') ?? '?'}`, `${kpi(model, 'Points in top 3') ?? '?'} in top 3`]
- case 'spend':
- return [`today ${(kpi(model, 'Today') ?? '?').split(' of ')[0]}`, `30 days ${kpi(model, '30 days') ?? '?'}`]
- }
- })()
-
- return { ...base, state: 'ok', line: parts.filter((p): p is string => p !== undefined).join(' · ') }
-}
-
-/** The one-line status under the prompt, from what loaded; undefined when nothing did. */
-export function statusLine(host: string | null, rows: readonly Row[]): string | undefined {
- const audit = rows.find(r => r.id === 'audit' && r.state === 'ok')
- const vitals = rows.find(r => r.id === 'vitals' && r.state === 'ok')
-
- if (host === null || (audit === undefined && vitals === undefined)) {
- return undefined
- }
-
- const score = audit?.line.split(' · ')[0]
- const cwv = vitals === undefined ? undefined : /^(poor|needs work)/.test(vitals.line) ? 'CWV needs work' : 'CWV good'
-
- // The engine prefixes the plugin's name; the line itself starts with the site.
- return [host, score === undefined ? undefined : `audit ${score}`, cwv].filter(Boolean).join(' · ')
-}
diff --git a/plugins/seo-cockpit/hooks/lib/paid.ts b/plugins/seo-cockpit/hooks/lib/paid.ts
deleted file mode 100644
index 58a5f2e..0000000
--- a/plugins/seo-cockpit/hooks/lib/paid.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/**
- * Which tool calls spend money, and how each one is priced.
- *
- * Pure: no `$`. register.ts asks `classify` about every tool call it sees and
- * only holds the ones it returns a PaidCall for.
- */
-
-export type PaidCall =
- /**
- * Priced by claude-seo's DataForSEO cost table: an MCP tool, or a script
- * that bills one or more endpoints (`compare` bills two).
- */
- | { kind: 'dataforseo'; endpoints: readonly string[]; label: string }
- /** Anything else that bills: no cost table, so the person decides. */
- | { kind: 'ask'; label: string; allowKey: string }
-
-/** MCP servers whose calls bill a paid account. Matched on the server segment of `mcp__<server>__<tool>`. */
-const PAID_MCP_SERVERS: ReadonlyArray<{ pattern: RegExp; label: string }> = [
- { pattern: /ahrefs/i, label: 'Ahrefs' },
- { pattern: /se-?ranking/i, label: 'SE Ranking' },
- { pattern: /firecrawl/i, label: 'Firecrawl' },
- { pattern: /profound/i, label: 'Profound' },
- { pattern: /banana/i, label: 'Gemini image generation' },
-]
-
-/**
- * DataForSEO lookups that list reference data and cost nothing: locations,
- * languages, filters, categories, model lists.
- */
-const FREE_DATAFORSEO = /(?:_locations|_languages|_filters|_loc_and_lang|_categories|llm_models)$/
-
-/** claude-seo scripts that bill, but have no cost-table row: the person decides. */
-const PAID_SCRIPTS: ReadonlyArray<{ pattern: RegExp; label: string }> = [
- { pattern: /\bmoz_api\.py\b/, label: 'Moz API' },
- { pattern: /\bkeywordseverywhere_api\.py\b/, label: 'Keywords Everywhere' },
- { pattern: /\bnlp_analyze\.py\b/, label: 'Google Cloud Natural Language (billed past the free tier)' },
- { pattern: /\bindexing_notify\.py\b/, label: 'Google Indexing API (uses daily quota)' },
- // Either the launcher form (`run --extension banana generate.py`) or a direct path, either slash.
- { pattern: /--extension\s+banana\s+(?:generate|batch|edit)\.py\b|\bbanana[\\/]scripts[\\/](?:generate|batch|edit)\.py\b/, label: 'Gemini image generation' },
-]
-
-/** Paid APIs Claude reaches with curl or WebFetch, keyed by host (SE Ranking and Profound ship no MCP server). */
-const PAID_HOSTS: ReadonlyArray<{ pattern: RegExp; label: string }> = [
- { pattern: /\bapi\d?\.seranking\.com\b/i, label: 'SE Ranking API' },
- { pattern: /\bapi\.tryprofound\.com\b/i, label: 'Profound API' },
- { pattern: /\bapi\.dataforseo\.com\b/i, label: 'DataForSEO API (direct, not priced)' },
-]
-
-/** Splits `mcp__<server>__<tool>`; null for a tool that is not an MCP tool. */
-export function mcpParts(tool: string): { server: string; name: string } | null {
- const match = /^mcp__(.+?)__(.+)$/.exec(tool)
-
- if (match === null || match[1] === undefined || match[2] === undefined) {
- return null
- }
-
- return { server: match[1], name: match[2] }
-}
-
-/** The single commands of a shell line: split on `&&`, `||`, `;`, `|` and newlines. */
-export function segmentsOf(command: string): string[] {
- return command.split(/&&|\|\||[;|\n]/).map(part => part.trim()).filter(part => part !== '')
-}
-
-/**
- * The DataForSEO endpoints a `dataforseo_merchant.py` run bills, from its
- * subcommand and `--marketplace`: `search` bills one (Google unless
- * `--marketplace amazon`), `sellers` one, `compare` Google then Amazon.
- */
-export function merchantEndpoints(segment: string): string[] {
- const sub = /dataforseo_merchant\.py\s+(\w+)/.exec(segment)?.[1]
-
- if (sub === 'sellers') {
- return ['merchant_google_sellers_search']
- }
-
- if (sub === 'compare') {
- return ['merchant_google_products_search', 'merchant_amazon_products_search']
- }
-
- return /--marketplace[=\s]+["']?amazon\b/i.test(segment) ? ['merchant_amazon_products_search'] : ['merchant_google_products_search']
-}
-
-function classifySegment(segment: string): PaidCall | null {
- if (/\bdataforseo_merchant\.py\b/.test(segment)) {
- const endpoints = merchantEndpoints(segment)
-
- return { kind: 'dataforseo', endpoints, label: `DataForSEO Merchant (${endpoints.join(' + ')})` }
- }
-
- const script = PAID_SCRIPTS.find(entry => entry.pattern.test(segment))
-
- if (script !== undefined) {
- return { kind: 'ask', label: script.label, allowKey: `script:${script.label}` }
- }
-
- const host = PAID_HOSTS.find(entry => entry.pattern.test(segment))
-
- return host === undefined ? null : { kind: 'ask', label: host.label, allowKey: `host:${host.label}` }
-}
-
-/** Merges the paid parts of one shell line: every DataForSEO endpoint, else the first ask. */
-function merge(calls: readonly PaidCall[]): PaidCall | null {
- const priced = calls.flatMap(call => (call.kind === 'dataforseo' ? call.endpoints : []))
- const ask = calls.find(call => call.kind === 'ask')
-
- // A line that mixes a priced endpoint and an unpriced paid script asks: the person sees the whole line.
- if (ask !== undefined) {
- return priced.length === 0 ? ask : { kind: 'ask', label: `${ask.label} and DataForSEO`, allowKey: `line:${ask.label}+dataforseo` }
- }
-
- return priced.length === 0 ? null : { kind: 'dataforseo', endpoints: priced, label: calls.map(call => call.label).join(', ') }
-}
-
-/**
- * The paid call a tool call is, or null when it costs nothing.
- *
- * A shell line is classified one command at a time, so a cost check chained
- * in front of a paid script (`check x && run merchant.py`) never hides it.
- *
- * @param tool the tool's name as `tool.call` reports it
- * @param command the shell command, for Bash and PowerShell
- * @param url the URL, for WebFetch
- */
-export function classify(tool: string, command: string | undefined, url?: string): PaidCall | null {
- const mcp = mcpParts(tool)
-
- if (mcp !== null) {
- if (/dataforseo/i.test(mcp.server)) {
- return FREE_DATAFORSEO.test(mcp.name) ? null : { kind: 'dataforseo', endpoints: [mcp.name], label: `DataForSEO ${mcp.name}` }
- }
-
- const paid = PAID_MCP_SERVERS.find(entry => entry.pattern.test(mcp.server))
-
- return paid === undefined ? null : { kind: 'ask', label: `${paid.label} (${mcp.name})`, allowKey: `mcp:${mcp.server}` }
- }
-
- if (tool === 'WebFetch' && url !== undefined) {
- const host = PAID_HOSTS.find(entry => entry.pattern.test(url))
-
- return host === undefined ? null : { kind: 'ask', label: host.label, allowKey: `host:${host.label}` }
- }
-
- if ((tool !== 'Bash' && tool !== 'PowerShell') || command === undefined) {
- return null
- }
-
- return merge(segmentsOf(command).map(classifySegment).filter((call): call is PaidCall => call !== null))
-}
diff --git a/plugins/seo-cockpit/hooks/lib/root.ts b/plugins/seo-cockpit/hooks/lib/root.ts
deleted file mode 100644
index 19c9526..0000000
--- a/plugins/seo-cockpit/hooks/lib/root.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Finding claude-seo from seo-cockpit's own folder. Pure string work; the
- * caller checks each candidate on disk.
- *
- * Three layouts:
- * - a setting the person gave (`claudeSeoRoot`);
- * - a checkout: seo-cockpit is `<claude-seo>/plugins/seo-cockpit`;
- * - an install: both live in the plugin cache as
- * `<cache>/<marketplace>/seo-cockpit/<version>` and
- * `<cache>/<marketplace>/claude-seo/<version>`.
- */
-
-const trimSlash = (path: string): string => path.replace(/[\\/]+$/, '')
-
-/** The parent folder, or the path itself at a root. */
-export function parentOf(path: string): string {
- const clean = trimSlash(path)
- const cut = Math.max(clean.lastIndexOf('/'), clean.lastIndexOf('\\'))
-
- return cut <= 0 ? clean : clean.slice(0, cut)
-}
-
-export const joinPath = (...parts: string[]): string => parts.map((part, i) => (i === 0 ? trimSlash(part) : part.replace(/^[\\/]+|[\\/]+$/g, ''))).join('/')
-
-/** The file whose presence marks a claude-seo folder. */
-export const MARKER = 'scripts/dataforseo_costs.py'
-
-/**
- * Folders that may hold claude-seo, most specific first. The cache folders
- * are returned for the caller to list: `cacheDir` is claude-seo under this
- * plugin's own marketplace, `cacheRoot` holds every marketplace (claude-seo
- * may come from another one, such as a community mirror).
- */
-export function candidatesOf(pluginRoot: string, setting: string): { fixed: string[]; cacheDir: string; cacheRoot: string } {
- const fixed: string[] = []
-
- if (setting.trim() !== '') {
- fixed.push(trimSlash(setting.trim()))
- }
-
- // Checkout: <claude-seo>/plugins/seo-cockpit
- const grandparent = parentOf(parentOf(pluginRoot))
-
- fixed.push(grandparent)
-
- // Install: <cache>/<marketplace>/seo-cockpit/<version> -> <cache>/<marketplace>/claude-seo
- return { fixed, cacheDir: joinPath(grandparent, 'claude-seo'), cacheRoot: parentOf(grandparent) }
-}
-
-/** `[major, minor, patch, ...]` and whether a pre-release tag follows (`2.5.0-rc1`). */
-function partsOf(version: string): { numbers: number[]; isPrerelease: boolean } {
- const [core = '', ...rest] = version.split(/[-+]/)
-
- return { numbers: core.split('.').map(part => Number.parseInt(part, 10) || 0), isPrerelease: rest.length > 0 && version.includes('-') }
-}
-
-/** Compares dotted versions numerically (`2.10.0` after `2.9.1`); a release ranks above its pre-releases. */
-function compareVersions(a: string, b: string): number {
- const pa = partsOf(a)
- const pb = partsOf(b)
-
- for (let i = 0; i < Math.max(pa.numbers.length, pb.numbers.length); i++) {
- const diff = (pa.numbers[i] ?? 0) - (pb.numbers[i] ?? 0)
-
- if (diff !== 0) {
- return diff
- }
- }
-
- return pa.isPrerelease === pb.isPrerelease ? a.localeCompare(b) : pa.isPrerelease ? -1 : 1
-}
-
-/** The highest version folder name, or null when none looks like a version. */
-export function latestVersion(names: readonly string[]): string | null {
- const versions = names.filter(name => /^\d+(?:\.\d+)*(?:[-+].*)?$/.test(name))
-
- return versions.length === 0 ? null : [...versions].sort(compareVersions).at(-1) ?? null
-}
-
-/**
- * The environment claude-seo's runtime.py must see, so it finds the Python
- * environment claude-seo set up, not one keyed to whichever plugin is calling.
- *
- * runtime.py picks its folder from CLAUDE_PLUGIN_DATA, which Claude Code sets
- * per plugin; inherited from this mod's process it names the wrong plugin.
- * - An install (`<home>/.claude/plugins/cache/<mkt>/claude-seo/<ver>`): point
- * it at claude-seo's own data folder, `<home>/.claude/plugins/data/claude-seo-<mkt>`,
- * where `/seo setup` puts the environment.
- * - A checkout or a custom folder: clear both variables, so runtime.py uses
- * its own standalone rule (the checkout's `.venv`).
- */
-export function runtimeEnvOf(seoRoot: string): Record<string, string> {
- const match = /^(.*)[\\/]plugins[\\/]cache[\\/]([^\\/]+)[\\/]claude-seo[\\/][^\\/]+[\\/]?$/.exec(seoRoot)
-
- return match === null || match[1] === undefined || match[2] === undefined
- ? { CLAUDE_PLUGIN_DATA: '', CLAUDE_PLUGIN_ROOT: '' }
- : { CLAUDE_PLUGIN_DATA: `${match[1]}/plugins/data/claude-seo-${match[2]}`, CLAUDE_PLUGIN_ROOT: seoRoot }
-}
diff --git a/plugins/seo-cockpit/hooks/lib/tabs.ts b/plugins/seo-cockpit/hooks/lib/tabs.ts
deleted file mode 100644
index ecc44f3..0000000
--- a/plugins/seo-cockpit/hooks/lib/tabs.ts
+++ /dev/null
@@ -1,333 +0,0 @@
-/**
- * The cockpit's tabs as data: each builder turns one claude-seo script's JSON
- * into KPIs, charts and tables. Pure. Every model names its source and when
- * it was fetched, so no number on screen is unlabeled.
- */
-
-import { COLORS, compact, endsOf, scoreColor, vitalColor, type Chart, type Section } from './charts'
-import { lastDays } from './format'
-import { usd } from './verdict'
-
-export type TabId = 'gsc' | 'rankings' | 'vitals' | 'audit' | 'maps' | 'spend'
-
-export const TABS: ReadonlyArray<{ id: TabId; key: string; label: string }> = [
- { id: 'gsc', key: '1', label: 'Search Console' },
- { id: 'rankings', key: '2', label: 'Rankings' },
- { id: 'vitals', key: '3', label: 'Vitals' },
- { id: 'audit', key: '4', label: 'Audit' },
- { id: 'maps', key: '5', label: 'Maps' },
- { id: 'spend', key: '6', label: 'Spend' },
-]
-
-export type TabModel = Section & { error: string | null; fetchedAt: string }
-
-type Json = Record<string, unknown>
-
-const obj = (value: unknown): Json => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Json) : {})
-const arr = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
-const num = (value: unknown): number | null => (typeof value === 'number' && Number.isFinite(value) ? value : null)
-const str = (value: unknown): string => (typeof value === 'string' ? value : '')
-const sum = (values: ReadonlyArray<number | null>) => values.reduce<number>((a, b) => a + (b ?? 0), 0)
-const mean = (values: ReadonlyArray<number | null>) => {
- const present = values.filter((v): v is number => v !== null)
-
- return present.length === 0 ? null : present.reduce((a, b) => a + b, 0) / present.length
-}
-
-const pct = (now: number, before: number): string => (before === 0 ? '' : ` (${now >= before ? '+' : ''}${Math.round(((now - before) / before) * 100)}%)`)
-
-/** A model that says what is missing and how to get it. */
-export function emptyModel(heading: string, source: string, fetchedAt: string, error: string, notes: readonly string[] = []): TabModel {
- return { heading, source, fetchedAt, error, kpis: [], charts: [], tables: [], notes }
-}
-
-type GscRow = { date: string; query: string; clicks: number; impressions: number; ctr: number; position: number }
-
-function gscRows(raw: unknown): GscRow[] {
- return arr(obj(raw).rows).map(row => {
- const r = obj(row)
- const keys = arr(r.keys).map(str)
-
- return {
- date: str(r.date) || (keys[0] ?? ''),
- query: str(r.query) || (keys[0] ?? ''),
- clicks: num(r.clicks) ?? 0,
- impressions: num(r.impressions) ?? 0,
- ctr: num(r.ctr) ?? 0,
- position: num(r.position) ?? 0,
- }
- })
-}
-
-/** The error a gsc_query.py result carries, or null. */
-export const gscError = (raw: unknown): string | null => (str(obj(raw).error) || null)
-
-/**
- * Search Console: 90 days by date, plus the top queries of the last 28 days.
- * Deltas compare the last 28 days with the 28 before them.
- */
-export function gscModel(byDate: unknown, byQuery: unknown, property: string, fetchedAt: string): TabModel {
- const heading = 'Search Console'
- const error = gscError(byDate)
-
- if (error !== null) {
- return emptyModel(heading, `gsc_query.py, ${property || 'default property'}`, fetchedAt, error, ['Set up Google access with /seo google setup, then set "Search Console property" in /config.'])
- }
-
- const days = gscRows(byDate).filter(row => /^\d{4}-\d{2}-\d{2}$/.test(row.date)).sort((a, b) => a.date.localeCompare(b.date))
-
- if (days.length === 0) {
- return emptyModel(heading, `gsc_query.py, ${property || 'default property'}`, fetchedAt, 'Search Console returned no rows for the last 90 days.')
- }
-
- const last28 = days.slice(-28)
- const prev28 = days.slice(-56, -28)
- const clicks = sum(last28.map(d => d.clicks))
- const impressions = sum(last28.map(d => d.impressions))
- const range = obj(obj(byDate).date_range)
- const queries = gscRows(byQuery).slice(0, 10)
-
- return {
- heading,
- source: `Google Search Console, ${str(obj(byDate).property) || property}, ${str(range.start) || days[0]?.date} to ${str(range.end) || days.at(-1)?.date} (data lags about 2 days)`,
- fetchedAt,
- error: null,
- kpis: [
- { label: 'Clicks, 28 days', value: `${compact(clicks)}${pct(clicks, sum(prev28.map(d => d.clicks)))}` },
- { label: 'Impressions, 28 days', value: `${compact(impressions)}${pct(impressions, sum(prev28.map(d => d.impressions)))}` },
- { label: 'CTR, 28 days', value: impressions === 0 ? 'n/a' : `${((clicks / impressions) * 100).toFixed(1)}%` },
- { label: 'Avg position, 28 days', value: (mean(last28.map(d => d.position)) ?? 0).toFixed(1) },
- ],
- charts: [
- { kind: 'line', title: 'Clicks per day', series: [{ name: 'Clicks', values: days.map(d => d.clicks), color: COLORS.blue }], xLabels: [days[0]?.date ?? '', days.at(-1)?.date ?? ''] },
- { kind: 'line', title: 'Impressions per day', series: [{ name: 'Impressions', values: days.map(d => d.impressions), color: COLORS.violet }], xLabels: [days[0]?.date ?? '', days.at(-1)?.date ?? ''] },
- ],
- tables:
- queries.length === 0
- ? []
- : [{ head: ['Top query, 28 days', 'Clicks', 'Impr.', 'CTR', 'Pos.'], rows: queries.map(q => [q.query, compact(q.clicks), compact(q.impressions), `${q.ctr}%`, q.position.toFixed(1)]) }],
- notes: [],
- }
-}
-
-/** Rankings: average position over time (lower is better), where the top queries rank, and drift checks. */
-export function rankingsModel(byDate: unknown, byQuery: unknown, drift: unknown, property: string, fetchedAt: string): TabModel {
- const heading = 'Rankings'
- const error = gscError(byDate)
-
- if (error !== null) {
- return emptyModel(heading, `gsc_query.py, ${property || 'default property'}`, fetchedAt, error, ['Rankings come from Search Console average position, so they need Google access too.'])
- }
-
- const days = gscRows(byDate).filter(row => /^\d{4}-\d{2}-\d{2}$/.test(row.date)).sort((a, b) => a.date.localeCompare(b.date))
- const queries = gscRows(byQuery)
- const buckets = [
- { label: 'Top 3', test: (p: number) => p <= 3, color: COLORS.good },
- { label: '4 to 10', test: (p: number) => p > 3 && p <= 10, color: COLORS.warn },
- { label: '11 to 20', test: (p: number) => p > 10 && p <= 20, color: COLORS.poor },
- { label: '21+', test: (p: number) => p > 20, color: COLORS.muted },
- ].map(b => ({ label: b.label, value: queries.filter(q => b.test(q.position)).length, color: b.color }))
- const comparisons = arr(obj(drift).comparisons).map(obj).reverse()
- const charts: Chart[] = []
-
- if (days.length > 0) {
- charts.push({ kind: 'line', title: 'Average position (lower is better)', series: [{ name: 'Avg position', values: days.map(d => d.position), color: COLORS.blue }], xLabels: [days[0]?.date ?? '', days.at(-1)?.date ?? ''], invert: true })
- }
-
- if (queries.length > 0) {
- charts.push({ kind: 'bars', title: 'Top queries by position band', rows: buckets, max: Math.max(1, ...buckets.map(b => b.value)) })
- }
-
- if (comparisons.length > 1) {
- charts.push({
- kind: 'line',
- title: 'Drift checks: issues found per comparison',
- series: [
- { name: 'Critical', values: comparisons.map(c => num(c.critical)), color: COLORS.poor },
- { name: 'Warning', values: comparisons.map(c => num(c.warning)), color: COLORS.warn },
- ],
- xLabels: [str(comparisons[0]?.timestamp).slice(0, 10), str(comparisons.at(-1)?.timestamp).slice(0, 10)],
- })
- }
-
- const striking = queries.filter(q => q.position > 3 && q.position <= 15 && q.impressions > 0).sort((a, b) => b.impressions - a.impressions).slice(0, 8)
- const { first, last } = endsOf(days.map(d => d.position))
-
- return {
- heading,
- source: `Google Search Console average position, ${property || str(obj(byDate).property) || 'default property'}; drift: claude-seo baselines`,
- fetchedAt,
- error: days.length === 0 && queries.length === 0 ? 'Search Console returned no rows.' : null,
- kpis: [
- { label: 'Avg position, now', value: last === null ? 'n/a' : last.toFixed(1) },
- { label: '90 days ago', value: first === null ? 'n/a' : first.toFixed(1) },
- { label: 'Queries in top 3', value: String(buckets[0]?.value ?? 0) },
- { label: 'Queries tracked', value: String(queries.length) },
- ],
- charts,
- tables: striking.length === 0 ? [] : [{ head: ['Striking distance (pos. 4 to 15)', 'Pos.', 'Impr.', 'Clicks'], rows: striking.map(q => [q.query, q.position.toFixed(1), compact(q.impressions), compact(q.clicks)]) }],
- notes: comparisons.length > 1 ? [] : ['No drift history for this URL yet. Run /seo drift baseline <url> to start tracking on-page changes.'],
- }
-}
-
-const VITALS: ReadonlyArray<{ key: string; label: string; unit: string; color: string }> = [
- { key: 'largest_contentful_paint', label: 'LCP', unit: 'ms', color: COLORS.blue },
- { key: 'interaction_to_next_paint', label: 'INP', unit: 'ms', color: COLORS.violet },
- { key: 'cumulative_layout_shift', label: 'CLS', unit: '', color: COLORS.blue },
-]
-
-/** Core Web Vitals: CrUX p75 per collection period, against Google's good and poor thresholds. */
-export function vitalsModel(raw: unknown, target: string, fetchedAt: string): TabModel {
- const heading = 'Core Web Vitals'
- const data = obj(raw)
- const error = str(data.error)
-
- if (error !== '') {
- return emptyModel(heading, `crux_history.py, ${target}`, fetchedAt, error, ['CrUX needs a Google API key and enough real-user traffic for the URL or origin.'])
- }
-
- const periods = arr(data.collection_periods).map(obj)
- const metrics = obj(data.metrics)
- const xLabels: [string, string] = [str(periods[0]?.last), str(periods.at(-1)?.last)]
- const charts: Chart[] = []
- const kpis: Array<{ label: string; value: string }> = []
-
- for (const vital of VITALS) {
- const metric = obj(metrics[vital.key])
- const values = arr(metric.p75_values).map(num)
- const good = num(metric.good_threshold)
- const poor = num(metric.poor_threshold)
- const { last } = endsOf(values)
-
- if (values.length === 0 || good === null || poor === null) {
- continue
- }
-
- const shown = (v: number) => (vital.unit === 'ms' ? `${Math.round(v)} ms` : v.toFixed(2))
- const verdict = last === null ? '' : last <= good ? ' good' : last <= poor ? ' needs work' : ' poor'
-
- kpis.push({ label: `${vital.label} p75`, value: last === null ? 'n/a' : `${shown(last)}${verdict}` })
- charts.push({ kind: 'line', title: `${vital.label} p75 (good ≤ ${shown(good)}, poor > ${shown(poor)})`, series: [{ name: vital.label, values, color: last === null ? vital.color : vitalColor(last, good, poor) }], xLabels, bands: { good, poor }, unit: vital.unit })
- }
-
- return {
- heading,
- source: `Chrome UX Report history, ${str(data.target) || target}, ${str(data.form_factor) || 'ALL'} devices, ${periods.length} weekly periods`,
- fetchedAt,
- error: charts.length === 0 ? 'CrUX has no Core Web Vitals history for this target.' : null,
- kpis,
- charts,
- tables: [],
- notes: ['p75 is the value 75% of real visits beat. Thresholds: LCP 2.5 s, INP 200 ms, CLS 0.1.'],
- }
-}
-
-/** The audit scorecard from audit-data.json. */
-export function auditModel(raw: unknown, path: string, fetchedAt: string): TabModel {
- const heading = 'Audit scorecard'
- const data = obj(raw)
- const summary = obj(data.summary)
- const score = num(summary.health_score)
- const categories = arr(data.categories)
- .map(obj)
- .flatMap(c => {
- const value = num(c.score)
-
- return value === null ? [] : [{ label: str(c.name), value, color: scoreColor(value), text: `${value}/100` }]
- })
-
- if (score === null && categories.length === 0) {
- return emptyModel(heading, path || 'audit-data.json', fetchedAt, 'No audit found in this folder.', ['Run /seo audit <url>; its audit-data.json appears here.'])
- }
-
- const severity = (finding: Json) => str(finding.severity)
- const findings = arr(data.categories)
- .map(obj)
- .flatMap(c => arr(c.findings).map(obj).map(f => ({ category: str(c.name), title: str(f.title), severity: severity(f) })))
- .filter(f => f.severity === 'Critical' || f.severity === 'High')
- .slice(0, 8)
- const wins = arr(summary.quick_wins).map(w => (typeof w === 'string' ? w : str(obj(w).title))).filter(Boolean).slice(0, 5)
-
- return {
- heading,
- source: `${path}${str(summary.business_type) ? `, business type: ${str(summary.business_type)}` : ''}`,
- fetchedAt,
- error: null,
- kpis: [
- { label: 'Health score', value: score === null ? 'n/a' : `${score}/100` },
- { label: 'Categories', value: String(categories.length) },
- { label: 'Critical and high findings', value: String(findings.length) },
- ],
- charts: categories.length === 0 ? [] : [{ kind: 'bars', title: 'Score by category', rows: [...categories].sort((a, b) => a.value - b.value), max: 100 }],
- tables: findings.length === 0 ? [] : [{ head: ['Severity', 'Category', 'Finding'], rows: findings.map(f => [f.severity, f.category, f.title]) }],
- notes: wins.map(w => `Quick win: ${w}`),
- }
-}
-
-/** The Maps geo-grid from a saved geo-grid-*.json (skills/seo-maps, step 8). */
-export function mapsModel(raw: unknown, path: string, fetchedAt: string): TabModel {
- const heading = 'Maps geo-grid'
- const data = obj(raw)
- const ranks = arr(data.ranks).map(row => arr(row).map(cell => (typeof cell === 'number' && Number.isFinite(cell) ? cell : null)))
-
- if (ranks.length === 0) {
- return emptyModel(heading, path || 'geo-grid-*.json', fetchedAt, 'No saved geo-grid in this folder.', ['Run /seo maps grid <keyword> <location> (uses DataForSEO credits); the grid is saved as <business>-maps/geo-grid-<keyword>-<date>.json.'])
- }
-
- const cells = ranks.flat()
- const found = cells.filter((c): c is number => c !== null)
- const top3 = found.filter(c => c <= 3).length
- const solv = num(data.solv) ?? (cells.length === 0 ? 0 : Math.round((top3 / cells.length) * 100))
-
- return {
- heading,
- source: `${path}: "${str(data.keyword)}" near ${str(data.location) || 'the business'}, ${str(data.date)}, ${ranks.length}x${ranks[0]?.length ?? 0} grid${num(data.radius_km) === null ? '' : `, ${num(data.radius_km)} km radius`}`,
- fetchedAt,
- error: null,
- kpis: [
- { label: 'Share of local voice', value: `${solv}%` },
- { label: 'Points in top 3', value: `${top3} of ${cells.length}` },
- { label: 'Average rank where found', value: found.length === 0 ? 'n/a' : (found.reduce((a, b) => a + b, 0) / found.length).toFixed(1) },
- { label: 'Not found', value: String(cells.length - found.length) },
- ],
- charts: [{ kind: 'grid', title: `Rank by grid point: ${str(data.keyword)}`, ranks }],
- tables: [],
- notes: [`${str(data.business) || 'The business'}; north is up.`],
- }
-}
-
-/** Spend: DataForSEO per day for 30 days, and today by endpoint, from the claude-seo ledger. */
-export function spendModel(today: unknown, summary: unknown, fetchedAt: string): TabModel {
- const t = obj(today)
- const totals = obj(obj(summary).daily_totals)
- const days = lastDays(str(t.date), 30)
- const series = days.map(day => num(obj(totals[day]).total_usd) ?? 0)
- const byEndpoint = Object.entries(obj(t.by_endpoint))
- .filter(([endpoint]) => endpoint !== '_audit_reset')
- .map(([endpoint, row]) => ({ label: endpoint, value: num(obj(row).cost_usd) ?? 0 }))
- .sort((a, b) => b.value - a.value)
- .slice(0, 8)
- const limit = num(t.daily_limit_usd) ?? 0
- const spent = num(t.total_usd) ?? 0
-
- return {
- heading: 'Spend',
- source: `claude-seo DataForSEO ledger, ${days[0] ?? ''} to ${days.at(-1) ?? ''}`,
- fetchedAt,
- error: null,
- kpis: [
- { label: 'Today', value: `${usd(spent)} of ${usd(limit)}` },
- { label: '7 days', value: usd(series.slice(-7).reduce((a, b) => a + b, 0)) },
- { label: '30 days', value: usd(series.reduce((a, b) => a + b, 0)) },
- ],
- charts: [
- { kind: 'line', title: 'DataForSEO spend per day (USD)', series: [{ name: 'Spend', values: series, color: COLORS.blue }], xLabels: [days[0] ?? '', days.at(-1) ?? ''] },
- ...(byEndpoint.length === 0
- ? []
- : [{ kind: 'bars' as const, title: 'Today by endpoint', rows: byEndpoint.map(row => ({ ...row, color: limit > 0 && spent / limit > 0.8 ? COLORS.warn : COLORS.blue, text: usd(row.value) })), max: Math.max(...byEndpoint.map(row => row.value)) }]),
- ],
- tables: [],
- notes: ['Image generation and other providers keep their own ledgers and are not shown here.'],
- }
-}
-
diff --git a/plugins/seo-cockpit/hooks/lib/verdict.ts b/plugins/seo-cockpit/hooks/lib/verdict.ts
deleted file mode 100644
index c6d9658..0000000
--- a/plugins/seo-cockpit/hooks/lib/verdict.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * Reading `dataforseo_costs.py check` output into a decision the guard acts on.
- *
- * Pure. Anything that does not parse as a known verdict becomes `error`, and
- * the guard holds the call: a ledger that cannot be read never waves spend through.
- */
-
-export type Verdict =
- | { decision: 'approved'; costUsd: number; todayUsd: number; remainingUsd: number }
- | { decision: 'needs_approval'; costUsd: number; todayUsd: number; remainingUsd: number | null; reason: string; message: string }
- | { decision: 'blocked'; message: string }
- | { decision: 'error'; message: string }
-
-const num = (value: unknown, fallback: number): number =>
- typeof value === 'number' && Number.isFinite(value) ? value : fallback
-
-/**
- * @param exitCode the script's exit status
- * @param stdout what it printed
- */
-export function parseCheck(exitCode: number, stdout: string): Verdict {
- if (exitCode !== 0) {
- // A ledger error exits 1 with its reason as JSON on stdout.
- const reason = /"message"\s*:\s*"([^"]*)"/.exec(stdout)?.[1]
-
- return { decision: 'error', message: `cost check exited ${exitCode}${reason ? ` (${reason})` : ''}` }
- }
-
- let data: Record<string, unknown>
-
- try {
- const parsed: unknown = JSON.parse(stdout)
-
- if (typeof parsed !== 'object' || parsed === null) {
- return { decision: 'error', message: 'cost check printed no JSON object' }
- }
-
- data = parsed as Record<string, unknown>
- } catch {
- return { decision: 'error', message: 'cost check printed no JSON' }
- }
-
- const message = typeof data.message === 'string' ? data.message : ''
-
- switch (data.status) {
- case 'approved':
- return {
- decision: 'approved',
- costUsd: num(data.total_cost_usd, 0),
- todayUsd: num(data.today_spend_usd, 0),
- remainingUsd: num(data.daily_remaining_usd, 0),
- }
- case 'needs_approval':
- return {
- decision: 'needs_approval',
- // An unknown endpoint reports only an estimate.
- costUsd: num(data.total_cost_usd, num(data.estimated_cost_usd, 0)),
- todayUsd: num(data.today_spend_usd, 0),
- remainingUsd: typeof data.daily_remaining_usd === 'number' ? data.daily_remaining_usd : null,
- reason: typeof data.approval_reason === 'string' ? data.approval_reason : 'needs_approval',
- message,
- }
- case 'blocked':
- return { decision: 'blocked', message: message || 'daily DataForSEO limit reached' }
- default:
- return { decision: 'error', message: `cost check returned an unknown status` }
- }
-}
-
-export const usd = (value: number): string => `$${value.toFixed(value !== 0 && value < 0.1 ? 3 : 2)}`
-
-/** One decision for a call that bills several endpoints: the strictest verdict wins, costs add up. */
-export function combine(verdicts: readonly Verdict[]): Verdict {
- const first = verdicts.find(v => v.decision === 'error') ?? verdicts.find(v => v.decision === 'blocked')
-
- if (first !== undefined || verdicts.length === 0) {
- return first ?? { decision: 'error', message: 'no cost check ran' }
- }
-
- const priced = verdicts as ReadonlyArray<Extract<Verdict, { costUsd: number }>>
- const costUsd = priced.reduce((sum, v) => sum + v.costUsd, 0)
- const todayUsd = Math.max(...priced.map(v => v.todayUsd))
- const asks = priced.filter((v): v is Extract<Verdict, { decision: 'needs_approval' }> => v.decision === 'needs_approval')
-
- if (asks.length === 0) {
- return { decision: 'approved', costUsd, todayUsd, remainingUsd: Math.min(...priced.map(v => (v.decision === 'approved' ? v.remainingUsd : Infinity))) }
- }
-
- const remaining = priced.map(v => v.remainingUsd).filter((r): r is number => r !== null)
-
- return {
- decision: 'needs_approval',
- costUsd,
- todayUsd,
- remainingUsd: remaining.length === 0 ? null : Math.min(...remaining),
- reason: [...new Set(asks.map(v => v.reason))].join(', '),
- message: asks.map(v => v.message).join(' '),
- }
-}
-
-/** True when the cost table had no price for the endpoint, so the figure is a guess and is not logged. */
-export const isUnpriced = (verdict: Verdict): boolean => verdict.decision === 'needs_approval' && verdict.reason.split(', ').includes('unknown_endpoint')
diff --git a/plugins/seo-cockpit/hooks/register.ts b/plugins/seo-cockpit/hooks/register.ts
deleted file mode 100644
index 22d2809..0000000
--- a/plugins/seo-cockpit/hooks/register.ts
+++ /dev/null
@@ -1,999 +0,0 @@
-import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code'
-
-import { auditFromPrompt, bandText, compactInstructions, economyModel, isSeoAgent, noteWrite, receiptText, type Audit } from './lib/audit'
-import { COLORS, htmlPage } from './lib/charts'
-import { doctorText, spendText } from './lib/format'
-import { classify, type PaidCall } from './lib/paid'
-import { candidatesOf, joinPath, latestVersion, MARKER, runtimeEnvOf } from './lib/root'
-import { chooseTarget, hostOf, rowOf, ROWS, siteOfAudit, statusLine } from './lib/overview'
-import { auditModel, emptyModel, gscModel, mapsModel, rankingsModel, spendModel, TABS, vitalsModel, type TabId, type TabModel } from './lib/tabs'
-import { combine, isUnpriced, parseCheck, usd, type Verdict } from './lib/verdict'
-import { paneView, type Kit, type PaneState } from './views/pane'
-
-type ToolResult = ResultOf['tool.call']
-
-/** What one activation knows: its settings, and what it has learned since it loaded. */
-type Ctx = {
- setting: string
- python: string
- isGuardOn: boolean
- /** Paid tools the person allowed until the plugin reloads. */
- allowed: Set<string>
- root: string | null
- isEconomy: boolean
- isBandOn: boolean
- /** The audit being followed, kept after it finishes until the next prompt. */
- audit: Audit | null
- isBandHidden: boolean
- isReceiptShown: boolean
- /** Stops the once-a-second redraw of the band's clock. */
- stopTicker: (() => void) | null
- /** Search Console property and the URL for Core Web Vitals, from /config. */
- site: string
- pageUrl: string
- pane: PaneState & { isOpen: boolean }
- /** Google settings from /config, handed to claude-seo's scripts only. */
- googleAccount: string
- googleApiKey: string
- /** Where the person keeps their audits (`<site>-audit/` folders), found from any working folder. */
- auditsFolder: string
- /** What the person typed in the pane as the site, per working folder. */
- typed: string | null
-}
-
-const PANE_ID = 'seo-cockpit'
-
-
-const stamp = (): string => new Date().toISOString().slice(0, 16).replace('T', ' ')
-
-const HELD = 'seo-cockpit held this paid call'
-const ALLOW = 'Allow until reload'
-
-/** The tools the guard looks at; `classify` decides which of their calls are paid. */
-const GUARDED_TOOLS = ['Bash', 'WebFetch', /^PowerShell$/, /^mcp__/] as const
-
-/** A string field of a tool call's arguments, whatever the tool. */
-function fieldOf(e: object, key: string): string | undefined {
- const value = (e as Readonly<Record<string, unknown>>)[key]
-
- return typeof value === 'string' ? value : undefined
-}
-
-// Every function that takes `$` is declared here at the top of the file and
-// spells each call `$.noun.method(...)`, so `claude plugin validate` can read
-// what the module calls off its source.
-
-async function findRoot($: EngineInterface, ctx: Ctx): Promise<string | null> {
- if (ctx.root !== null) {
- return ctx.root
- }
-
- const { fixed, cacheDir, cacheRoot } = candidatesOf($.plugin.root, ctx.setting)
-
- for (const candidate of fixed) {
- if (await $.fs.exists(joinPath(candidate, MARKER))) {
- ctx.root = candidate
-
- return ctx.root
- }
- }
-
- // This plugin's own marketplace first, then any other that carries claude-seo.
- const cacheDirs = [cacheDir]
-
- try {
- for (const entry of await $.fs.list(cacheRoot)) {
- const dir = joinPath(cacheRoot, entry.name, 'claude-seo')
-
- if (entry.kind === 'dir' && dir !== cacheDir) {
- cacheDirs.push(dir)
- }
- }
- } catch {
- // No plugin cache: not installed from a marketplace.
- }
-
- for (const dir of cacheDirs) {
- try {
- const version = latestVersion((await $.fs.list(dir)).filter(entry => entry.kind === 'dir').map(entry => entry.name))
- const candidate = version === null ? null : joinPath(dir, version)
-
- if (candidate !== null && (await $.fs.exists(joinPath(candidate, MARKER)))) {
- ctx.root = candidate
-
- return ctx.root
- }
- } catch {
- // That marketplace has no claude-seo.
- }
- }
-
- return null
-}
-
-/** The environment claude-seo's scripts run with: its own runtime folder, plus the Google settings from /config. */
-function scriptEnv(ctx: Ctx, seoRoot: string): Record<string, string> {
- return {
- ...runtimeEnvOf(seoRoot),
- ...(ctx.googleAccount === 'gcloud' && { CLAUDE_SEO_GOOGLE_AUTH: 'adc' }),
- ...(ctx.googleApiKey !== '' && { GOOGLE_API_KEY: ctx.googleApiKey }),
- }
-}
-
-/** Runs one of claude-seo's stdlib-only scripts with the configured Python. */
-async function runScript($: EngineInterface, ctx: Ctx, seoRoot: string, script: string, args: readonly string[]) {
- return $.process.run([ctx.python, joinPath(seoRoot, 'scripts', script), ...args], { timeoutMs: 20_000, env: scriptEnv(ctx, seoRoot) })
-}
-
-/** Writes a guarded call's cost to the ledger. Never throws: the call already ran. */
-async function logCost($: EngineInterface, ctx: Ctx, seoRoot: string, endpoint: string, cost: number): Promise<boolean> {
- try {
- const { exitCode } = await runScript($, ctx, seoRoot, 'dataforseo_costs.py', ['log', endpoint, String(cost), '--note', 'seo-cockpit estimate'])
-
- return exitCode === 0
- } catch {
- return false
- }
-}
-
-/** Runs the call, then logs each endpoint it billed at its table price. A denied, failed or unpriced call is not logged. */
-async function runAndLog($: EngineInterface, ctx: Ctx, seoRoot: string, checks: ReadonlyArray<{ endpoint: string; verdict: Verdict }>, run: () => Promise<ToolResult>): Promise<ToolResult> {
- const result = await run()
-
- if (result.deny !== undefined) {
- return result
- }
-
- const names = checks.map(check => check.endpoint).join(', ')
-
- if (result.isError === true) {
- return { ...result, context: [...(result.context ?? []), `seo-cockpit did not log ${names}: the call failed, and DataForSEO does not bill failed tasks.`] }
- }
-
- if (checks.some(check => isUnpriced(check.verdict))) {
- return { ...result, context: [...(result.context ?? []), `seo-cockpit did not log ${names}: it has no price in the cost table. Log the actual cost from the response with dataforseo_costs.py log <endpoint> <cost>.`] }
- }
-
- const logged = await Promise.all(checks.map(check => logCost($, ctx, seoRoot, check.endpoint, 'costUsd' in check.verdict ? check.verdict.costUsd : 0)))
- const total = checks.reduce((sum, check) => sum + ('costUsd' in check.verdict ? check.verdict.costUsd : 0), 0)
-
- if (ctx.audit !== null && ctx.audit.finishMs === null) {
- ctx.audit = { ...ctx.audit, spentUsd: ctx.audit.spentUsd + total }
- }
- // The skills tell Claude to log each call itself; say it is done so it is not counted twice.
- const note = logged.every(Boolean)
- ? `seo-cockpit logged this call to the claude-seo DataForSEO ledger (${names}, about ${usd(total)}). Do not run dataforseo_costs.py log for it.`
- : `seo-cockpit could not log this call's cost. Log it with dataforseo_costs.py log <endpoint> <actual cost> for: ${names}.`
-
- return { ...result, context: [...(result.context ?? []), note] }
-}
-
-/** Asks the person; a dismissed dialog, or a run with no one to ask, is a no. The safe answer is listed first. */
-async function askOrNull($: EngineInterface, question: string, choices: readonly string[]): Promise<string | null> {
- try {
- return await $.ui.ask(question, choices)
- } catch {
- return null
- }
-}
-
-async function guard($: EngineInterface, ctx: Ctx, paid: PaidCall, run: () => Promise<ToolResult>): Promise<ToolResult> {
- if (paid.kind === 'ask') {
- if (ctx.allowed.has(paid.allowKey)) {
- return run()
- }
-
- const answer = await askOrNull($, `${paid.label} bills a paid account. Run this call?`, ['Hold it', 'Run it', ALLOW])
-
- if (answer === ALLOW) {
- ctx.allowed.add(paid.allowKey)
- }
-
- return answer === 'Run it' || answer === ALLOW ? run() : { deny: `${HELD}: the person did not approve ${paid.label}.` }
- }
-
- const seoRoot = await findRoot($, ctx)
-
- if (seoRoot === null) {
- return { deny: `${HELD}: claude-seo was not found, so the DataForSEO budget could not be checked. Set "claude-seo folder" in /config, or turn the spend guard off there.` }
- }
-
- const checks = await Promise.all(
- paid.endpoints.map(async endpoint => {
- const { exitCode, stdout } = await runScript($, ctx, seoRoot, 'dataforseo_costs.py', ['check', endpoint])
-
- return { endpoint, verdict: parseCheck(exitCode, stdout) }
- }),
- )
- const verdict = combine(checks.map(check => check.verdict))
-
- switch (verdict.decision) {
- case 'approved':
- return runAndLog($, ctx, seoRoot, checks, run)
- case 'blocked':
- return { deny: `${HELD}: ${verdict.message}` }
- case 'error':
- // Look for claude-seo again next time: an update may have moved it.
- ctx.root = null
-
- return { deny: `${HELD}: ${verdict.message}. Run /seo-doctor.` }
- case 'needs_approval': {
- const left = verdict.remainingUsd === null ? '' : `, ${usd(verdict.remainingUsd)} left today`
- const price = isUnpriced(verdict) ? 'has no listed price' : `costs about ${usd(verdict.costUsd)}`
- const answer = await askOrNull(
- $,
- `${paid.label} ${price} (${verdict.reason.replace(/_/g, ' ')}; ${usd(verdict.todayUsd)} spent today${left}). Run it?`,
- ['Hold it', 'Approve'],
- )
-
- return answer === 'Approve' ? runAndLog($, ctx, seoRoot, checks, run) : { deny: `${HELD}: the person did not approve ${paid.label}.` }
- }
- }
-}
-
-/** Redraws the band once a second while an audit runs, so its clock moves. */
-function startTicker($: EngineInterface, ctx: Ctx): void {
- if (ctx.stopTicker === null) {
- const timer = $.clock.every(1000, () => $.ui.invalidate('ui.render'))
-
- ctx.stopTicker = () => timer.cancel()
- }
-}
-
-function stopTicker(ctx: Ctx): void {
- ctx.stopTicker?.()
- ctx.stopTicker = null
-}
-
-/** The band's clock needs redrawing only while the band shows a running audit. */
-function syncTicker($: EngineInterface, ctx: Ctx): void {
- const audit = ctx.audit
-
- if (ctx.isBandOn && !ctx.isBandHidden && audit !== null && audit.finishMs === null) {
- startTicker($, ctx)
- } else {
- stopTicker(ctx)
- }
-}
-
-/** Sets the audit, redraws, and keeps a copy in the store so a reload mid-audit does not lose it. */
-function setAudit($: EngineInterface, ctx: Ctx, audit: Audit | null): void {
- ctx.audit = audit
- syncTicker($, ctx)
- $.ui.invalidate('ui.render')
- void $.store.set('audit', audit).catch(() => undefined)
-}
-
-/** Starts following a new audit and shows the band again. */
-function follow($: EngineInterface, ctx: Ctx, audit: Audit): void {
- ctx.isBandHidden = false
- ctx.isReceiptShown = false
- setAudit($, ctx, audit)
-}
-
-/** An audit older than this with no result is treated as abandoned. */
-const STALE_MS = 3 * 60 * 60 * 1000
-
-/** After a reload, picks up an audit that was still running. */
-async function restoreAudit($: EngineInterface, ctx: Ctx): Promise<void> {
- if (ctx.audit !== null) {
- return
- }
-
- const saved = (await $.store.get('audit').catch(() => null)) as Audit | null
-
- if (saved !== null && typeof saved === 'object' && typeof saved.domain === 'string' && saved.finishMs === null && Date.now() - saved.startMs < STALE_MS) {
- ctx.audit = saved
- syncTicker($, ctx)
- $.ui.invalidate('ui.render')
- }
-}
-
-/** Runs a claude-seo script through its managed runtime (for scripts that need its packages) and parses the JSON it prints. */
-async function runtimeJson($: EngineInterface, ctx: Ctx, seoRoot: string, script: string, args: readonly string[]): Promise<{ data: unknown; error: string | null }> {
- try {
- const { exitCode, stdout, stderr } = await $.process.run([ctx.python, joinPath(seoRoot, 'scripts', 'runtime.py'), 'run', script, ...args], { timeoutMs: 90_000, env: scriptEnv(ctx, seoRoot) })
-
- try {
- return { data: JSON.parse(stdout), error: null }
- } catch {
- const reason = stderr.trim().split('\n').at(-1) ?? ''
-
- return { data: null, error: exitCode === 3 ? 'claude-seo runtime is not set up: run /seo setup' : reason || `${script} printed no JSON (exit ${exitCode})` }
- }
- } catch (error) {
- return { data: null, error: error instanceof Error ? error.message : String(error) }
- }
-}
-
-/** The newest file under the working folder's `*<suffix>` folders whose name passes `test`. */
-async function newestFile($: EngineInterface, suffix: string, test: (name: string) => boolean): Promise<string | null> {
- let best: { path: string; mtime: number } | null = null
-
- try {
- const cwd = await $.session.cwd()
-
- for (const dir of (await $.fs.list(cwd)).filter(entry => entry.kind === 'dir' && entry.name.endsWith(suffix))) {
- for (const file of (await $.fs.list(joinPath(cwd, dir.name))).filter(entry => entry.kind === 'file' && test(entry.name))) {
- const path = joinPath(cwd, dir.name, file.name)
- const { mtimeMs } = await $.fs.stat(path)
-
- if (best === null || mtimeMs > best.mtime) {
- best = { path, mtime: mtimeMs }
- }
- }
- }
- } catch {
- // An unreadable folder has nothing to show; the tab says how to make some.
- }
-
- return best?.path ?? null
-}
-
-/** A path as shown on screen: relative to the working folder when it is inside it. */
-async function shown($: EngineInterface, path: string | null): Promise<string> {
- if (path === null) {
- return ''
- }
-
- const cwd = await $.session.cwd()
-
- return path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path
-}
-
-/** The store key for a tab's last result: per working folder and property, so one project's data never shows in another. */
-async function cacheKey($: EngineInterface, ctx: Ctx, tab: TabId): Promise<string> {
- return `tab:${tab}:${await $.session.cwd()}:${ctx.site}`
-}
-
-const isModel = (value: unknown): value is TabModel => {
- const m = value as Partial<TabModel> | null
-
- return typeof m === 'object' && m !== null && typeof m.heading === 'string' && Array.isArray(m.kpis) && Array.isArray(m.charts) && Array.isArray(m.tables) && Array.isArray(m.notes)
-}
-
-/** The audit for a site: a live one, this folder's if it is about that site, else the one remembered for it. */
-async function auditFor($: EngineInterface, ctx: Ctx, host: string | null): Promise<[unknown, string]> {
- if (ctx.audit?.dir != null && (host === null || ctx.audit.domain === host)) {
- const path = joinPath(ctx.audit.dir, 'audit-data.json')
-
- return [await readJson($, path), await shown($, path)]
- }
-
- const here = await newestFile($, '-audit', name => name === 'audit-data.json')
-
- if (here !== null) {
- const data = await readJson($, here)
-
- if (host === null || siteOfAudit(here.split(/[/\\]/).at(-2) ?? '', data) === host) {
- return [data, await shown($, here)]
- }
- }
-
- const remembered = host === null ? undefined : await $.store.get(`audit:${host}`).catch(() => undefined)
-
- if (typeof remembered === 'string') {
- const data = await readJson($, remembered)
-
- if (data !== null) {
- return [data, remembered]
- }
- }
-
- // The audits folder from /config: `<site>-audit/audit-data.json`, with or without www.
- if (host !== null && ctx.auditsFolder !== '') {
- for (const name of [`${host}-audit`, `www.${host}-audit`]) {
- const path = joinPath(ctx.auditsFolder, name, 'audit-data.json')
- const data = await readJson($, path)
-
- if (data !== null) {
- void $.store.set(`audit:${host}`, path).catch(() => undefined)
-
- return [data, path]
- }
- }
- }
-
- return [null, '']
-}
-
-async function readJson($: EngineInterface, path: string): Promise<unknown> {
- try {
- return JSON.parse(await $.fs.read(path))
- } catch {
- return null
- }
-}
-
-/** The site the cockpit is about: this folder's choice, its audit, the /config default, then the last site used. */
-async function resolveHost($: EngineInterface, ctx: Ctx): Promise<void> {
- const cwd = await $.session.cwd().catch(() => '')
-
- if (ctx.typed === null) {
- const saved = await $.store.get(`target:${cwd}`).catch(() => undefined)
-
- ctx.typed = typeof saved === 'string' ? saved : null
- }
-
- let inferred: string | null = ctx.audit?.domain ?? null
-
- if (inferred === null) {
- const path = await newestFile($, '-audit', name => name === 'audit-data.json')
-
- if (path !== null) {
- const folder = path.split(/[/\\]/).at(-2) ?? ''
-
- inferred = siteOfAudit(folder, await readJson($, path))
-
- // Remember where this site's audit lives, so the Audit row works from any folder.
- if (inferred !== null) {
- void $.store.set(`audit:${inferred}`, path).catch(() => undefined)
- }
- }
- }
-
- const setting = ctx.site || ctx.pageUrl
- const chosen = chooseTarget(setting, ctx.typed, inferred)
- let host = chosen.host
- let source: PaneState['hostSource'] = chosen.source
-
- // Nothing here says which site: use the last one seen anywhere, and say so.
- if (host === null) {
- const last = await $.store.get('target:last').catch(() => undefined)
-
- host = typeof last === 'string' ? hostOf(last) : null
- source = host === null ? null : 'last'
- } else {
- void $.store.set('target:last', host).catch(() => undefined)
- }
-
- ctx.pane.host = host
- ctx.pane.hostSource = source
-}
-
-/**
- * The Search Console property for a site. A /config value counts only when it
- * is a real property (`sc-domain:` or a URL prefix) for that site; a bare name
- * such as `claude-seo.md` is not a property and becomes `sc-domain:claude-seo.md`.
- */
-function propertyFor(setting: string, host: string): string {
- const value = setting.trim()
-
- return hostOf(value) === host && /^(sc-domain:|https?:\/\/)/i.test(value) ? value : `sc-domain:${host}`
-}
-
-/** Builds one source's model from claude-seo's own scripts and files. Free: no paid API is called. */
-async function buildTab($: EngineInterface, ctx: Ctx, tab: TabId): Promise<TabModel> {
- const at = stamp()
- const label = TABS.find(t => t.id === tab)?.label ?? tab
- const seoRoot = await findRoot($, ctx)
-
- if (seoRoot === null) {
- return emptyModel(label, 'claude-seo', at, 'claude-seo was not found. Set "claude-seo folder" in /config.')
- }
-
- const host = ctx.pane.host
- // The /config property and page apply only to the site they name; any other site uses its domain property and home page.
- const property = host === null ? '' : propertyFor(ctx.site, host)
- const propertyArgs = property === '' ? [] : ['--property', property]
- const url = host === null ? '' : hostOf(ctx.pageUrl) === host ? ctx.pageUrl : `https://${host}`
-
- if (tab === 'gsc' || tab === 'rankings') {
- // With no site, claude-seo would fall back to its own default property, which may be another site.
- if (property === '') {
- return emptyModel(label, 'gsc_query.py', at, 'No URL to measure.')
- }
-
- const [byDate, byQuery] = await Promise.all([
- runtimeJson($, ctx, seoRoot, 'gsc_query.py', ['query', '--dimensions', 'date', '--days', '90', '--limit', '1000', '--json', ...propertyArgs]),
- runtimeJson($, ctx, seoRoot, 'gsc_query.py', ['query', '--dimensions', 'query', '--days', '28', '--limit', tab === 'gsc' ? '10' : '200', '--json', ...propertyArgs]),
- ])
-
- if (byDate.error !== null) {
- return emptyModel(label, 'gsc_query.py', at, byDate.error)
- }
-
- if (tab === 'gsc') {
- return gscModel(byDate.data, byQuery.data, property, at)
- }
-
- const drift = url === '' ? { data: null } : await runtimeJson($, ctx, seoRoot, 'drift_history.py', [url, '--limit', '20'])
-
- return rankingsModel(byDate.data, byQuery.data, drift.data, property, at)
- }
-
- if (tab === 'vitals') {
- if (url === '') {
- return emptyModel(label, 'crux_history.py', at, 'No URL to measure.')
- }
-
- const crux = await runtimeJson($, ctx, seoRoot, 'crux_history.py', [url, '--json'])
-
- return crux.error !== null ? emptyModel(label, 'crux_history.py', at, crux.error) : vitalsModel(crux.data, url, at)
- }
-
- if (tab === 'audit') {
- return auditModel(...(await auditFor($, ctx, host)), at)
- }
-
- if (tab === 'maps') {
- const path = await newestFile($, '-maps', name => /^geo-grid-.*\.json$/.test(name))
-
- return mapsModel(path === null ? null : await readJson($, path), await shown($, path), at)
- }
-
- const [today, summary] = await Promise.all([runScript($, ctx, seoRoot, 'dataforseo_costs.py', ['today']), runScript($, ctx, seoRoot, 'dataforseo_costs.py', ['summary', '--days', '30'])])
-
- try {
- return spendModel(JSON.parse(today.stdout), JSON.parse(summary.stdout), at)
- } catch {
- return emptyModel(label, 'dataforseo_costs.py', at, 'The spend ledger could not be read.')
- }
-}
-
-/** Loads one source, cache first: the last result shows at once, the fresh one replaces it. */
-async function loadSource($: EngineInterface, ctx: Ctx, tab: TabId): Promise<void> {
- const key = await cacheKey($, ctx, tab).catch(() => null)
-
- if (ctx.pane.models[tab] === undefined && key !== null) {
- const cached = await $.store.get(key).catch(() => undefined)
-
- if (isModel(cached)) {
- ctx.pane.models[tab] = cached
- }
- }
-
- ctx.pane.loading = new Set([...ctx.pane.loading, tab])
- $.ui.invalidate('ui.render')
-
- try {
- const model = await buildTab($, ctx, tab)
-
- ctx.pane.models[tab] = model
-
- if (key !== null) {
- await $.store.set(key, model).catch(() => undefined)
- }
- } finally {
- ctx.pane.loading = new Set([...ctx.pane.loading].filter(t => t !== tab))
- $.ui.invalidate('ui.render')
- }
-}
-
-/** Loads every source in the background (all free), then pins the one-line summary under the prompt. */
-async function loadAll($: EngineInterface, ctx: Ctx): Promise<void> {
- // Every row says "checking" from the first frame, not "not loaded".
- ctx.pane.loading = new Set(ROWS.map(row => row.id))
- $.ui.invalidate('ui.render')
- await resolveHost($, ctx)
- await Promise.allSettled(ROWS.map(row => loadSource($, ctx, row.id)))
-
- const rows = ROWS.map(row => rowOf(row.id, ctx.pane.models[row.id], false))
-
- $.ui.status(statusLine(ctx.pane.host, rows))
-}
-
-/** Remembers a site the person gave: for this folder, and as the last one used anywhere. */
-async function rememberTarget($: EngineInterface, ctx: Ctx, value: string): Promise<void> {
- ctx.typed = value.trim()
- ctx.pane.models = {}
- await $.store.set(`target:${await $.session.cwd()}`, ctx.typed).catch(() => undefined)
- await $.store.set('target:last', hostOf(ctx.typed)).catch(() => undefined)
-}
-
-/** The person typed the site in the pane: remember it and load again. */
-async function setTarget($: EngineInterface, ctx: Ctx, value: string): Promise<void> {
- if (hostOf(value) === null) {
- return
- }
-
- await rememberTarget($, ctx, value)
- await loadAll($, ctx)
-}
-
-/** Writes every loaded source into one self-contained HTML page in the working folder; returns its path. */
-async function exportHtml($: EngineInterface, ctx: Ctx, loadAllFirst: boolean): Promise<string> {
- if (loadAllFirst) {
- await resolveHost($, ctx)
-
- for (const tab of TABS) {
- ctx.pane.models[tab.id] = await buildTab($, ctx, tab.id)
- }
- }
-
- const sections = TABS.flatMap(tab => {
- const model = ctx.pane.models[tab.id]
-
- return model === undefined ? [] : [{ ...model, source: `${model.source} · fetched ${model.fetchedAt}`, notes: model.error === null ? model.notes : [model.error, ...model.notes] }]
- })
- const cwd = await $.session.cwd()
- const path = joinPath(cwd, `seo-cockpit-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.html`)
-
- await $.fs.write(path, htmlPage(`SEO Cockpit${ctx.pane.host === null ? '' : `: ${ctx.pane.host}`}`, `Generated ${stamp()} by seo-cockpit from claude-seo data`, sections))
- ctx.pane.exported = path
- $.ui.invalidate('ui.render')
-
- return path
-}
-
-async function cockpitCommand($: EngineInterface, ctx: Ctx, args: string): Promise<{ text: string }> {
- // The engine already names the plugin above a command's answer; the text is the outcome only.
- try {
- const arg = args.trim()
-
- if (arg.toLowerCase() === 'export') {
- return { text: `Dashboard written to ${await exportHtml($, ctx, true)}` }
- }
-
- // `/seo-cockpit claude-seo.md`: that site, remembered for this folder and as the last one used.
- if (arg !== '') {
- if (hostOf(arg) === null) {
- return { text: `"${arg}" is not a site. Try /seo-cockpit example.com, or /seo-cockpit export.` }
- }
-
- await rememberTarget($, ctx, arg)
-
- if (ctx.pane.isOpen) {
- void loadAll($, ctx).catch(() => undefined)
-
- return { text: `Cockpit switched to ${hostOf(arg)}.` }
- }
- } else if (ctx.pane.isOpen) {
- // A second /seo-cockpit closes it, as the official modernization pane does.
- await $.ui.close({ id: PANE_ID }).catch(() => undefined)
- ctx.pane.isOpen = false
-
- return { text: 'Cockpit closed.' }
- }
-
- await resolveHost($, ctx)
-
- // Ask for room: inline, the engine grants up to what the layout spares (a size the person set wins).
- // Docked beside the transcript (fullscreen, 110+ columns), the pane is full height anyway.
- const opened = await $.ui.open({ id: PANE_ID, title: 'SEO Cockpit', focus: true, rows: 40 })
-
- if (opened.isPlaced) {
- ctx.pane.isOpen = true
- ctx.pane.view = 'overview'
- void loadAll($, ctx).catch(() => undefined)
-
- return { text: ctx.pane.host === null ? 'Cockpit open. Type the site in the pane to load its data.' : `Cockpit open for ${ctx.pane.host}.` }
- }
-
- // No pane here (the VS Code chat panel): the HTML page is the cockpit.
- return { text: `No pane on this screen (${opened.reason}). Dashboard written to ${await exportHtml($, ctx, true)}` }
- } catch (error) {
- return { text: `The cockpit could not open: ${error instanceof Error ? error.message : String(error)}` }
- }
-}
-
-async function registerCommands($: EngineInterface): Promise<void> {
- await Promise.all([
- $.command.register({ name: 'seo-spend', description: 'claude-seo DataForSEO spend: today, 7 and 30 days, by endpoint', immediate: true }).catch(() => undefined),
- $.command.register({ name: 'seo-doctor', description: 'claude-seo runtime readiness and where it is installed', immediate: true }).catch(() => undefined),
- $.command.register({ name: 'seo-cockpit', description: 'Charts for Search Console, rankings, Core Web Vitals, the audit, Maps and spend', argumentHint: '[site | export]', immediate: true }).catch(() => undefined),
- ])
-}
-
-async function spendCommand($: EngineInterface, ctx: Ctx): Promise<{ text: string }> {
- const seoRoot = await findRoot($, ctx)
-
- if (seoRoot === null) {
- return { text: 'claude-seo was not found. Set "claude-seo folder" in /config.' }
- }
-
- try {
- const [today, summary] = await Promise.all([
- runScript($, ctx, seoRoot, 'dataforseo_costs.py', ['today']),
- runScript($, ctx, seoRoot, 'dataforseo_costs.py', ['summary', '--days', '30']),
- ])
-
- if (today.exitCode !== 0 || summary.exitCode !== 0) {
- const failed = today.exitCode !== 0 ? today : summary
- // A ledger error prints its reason as JSON on stdout, not on stderr.
- const reason = /"message"\s*:\s*"([^"]*)"/.exec(failed.stdout)?.[1] || failed.stderr.trim().split('\n').at(-1) || 'no detail'
-
- return { text: `The ledger could not be read (${reason}).` }
- }
-
- return { text: spendText(JSON.parse(today.stdout), JSON.parse(summary.stdout)) }
- } catch (error) {
- return { text: `The ledger could not be read (${error instanceof Error ? error.message : String(error)}). Is "${ctx.python}" on PATH? Set "Python command" in /config.` }
- }
-}
-
-async function doctorCommand($: EngineInterface, ctx: Ctx): Promise<{ text: string }> {
- const seoRoot = await findRoot($, ctx)
-
- if (seoRoot === null) {
- return { text: 'claude-seo was not found next to this plugin or in the plugin cache. Set "claude-seo folder" in /config.' }
- }
-
- try {
- // Exit 3 means "setup required" and still prints the report.
- const { stdout } = await runScript($, ctx, seoRoot, 'runtime.py', ['doctor', '--json'])
-
- return { text: `${doctorText(JSON.parse(stdout), seoRoot)}\n guard ${ctx.isGuardOn ? 'on' : 'off'} (Python: ${ctx.python})` }
- } catch (error) {
- return { text: `Doctor failed (${error instanceof Error ? error.message : String(error)}). Is "${ctx.python}" on PATH?` }
- }
-}
-
-/**
- * seo-cockpit: a spend guard over paid SEO API calls and zero-token commands
- * for claude-seo. This is the only file that calls `on()`; the rules live in
- * ./lib and never touch `$`.
- *
- * @param on the engine's registrar
- * @param options the plugin's userConfig values
- */
-export function register(on: On, options: PluginOptions) {
- const ctx: Ctx = {
- setting: typeof options.claudeSeoRoot === 'string' ? options.claudeSeoRoot : '',
- python: typeof options.python === 'string' && options.python.trim() !== '' ? options.python.trim() : 'python3',
- isGuardOn: options.spendGuard !== false,
- allowed: new Set<string>(),
- root: null,
- isEconomy: options.economy === true,
- isBandOn: options.auditBand !== false,
- audit: null,
- isBandHidden: false,
- isReceiptShown: false,
- stopTicker: null,
- site: typeof options.site === 'string' ? options.site : '',
- pageUrl: typeof options.pageUrl === 'string' ? options.pageUrl.trim() : '',
- pane: { view: 'overview', models: {}, loading: new Set(), host: null, hostSource: null, exported: null, isOpen: false },
- typed: null,
- googleAccount: typeof options.googleAccount === 'string' ? options.googleAccount : 'auto',
- auditsFolder: typeof options.auditsFolder === 'string' ? options.auditsFolder.trim() : '',
- googleApiKey: typeof options.googleApiKey === 'string' ? options.googleApiKey.trim() : '',
- }
-
- // ------------------------------------------------------------ spend guard
-
- on('tool.call', { tool: GUARDED_TOOLS }, async ($, e, next) => {
- if (!ctx.isGuardOn) {
- return next(e)
- }
-
- const paid = classify(e.tool, fieldOf(e, 'command'), fieldOf(e, 'url'))
-
- return paid === null ? next(e) : guard($, ctx, paid, () => next(e))
- }).catch(async ($, e, next) =>
- // After the call ran, its result stands: saying it did not run would invite a paid retry.
- next.called
- ? next(e)
- : { deny: `${HELD}: the spend guard failed, so the call did not run. Run /seo-doctor, or turn the spend guard off in /config.` },
- )
-
- // ---------------------------------------------------------- audit progress
-
- on('prompt.submit', async ($, e, next) => {
- const audit = auditFromPrompt(e.text, Date.now())
-
- if (audit !== null) {
- follow($, ctx, audit)
- } else if (ctx.audit !== null && (ctx.audit.finishMs !== null || Date.now() - ctx.audit.startMs > STALE_MS)) {
- // A finished audit's band stays up until the next prompt; an abandoned one goes too.
- setAudit($, ctx, null)
- }
-
- return next(e)
- })
-
- // A slash command may reach the engine as a command run rather than prompt text; observe both.
- on('command.run', { command: ['seo', 'claude-seo:seo'] }, async ($, e, next) => {
- const audit = auditFromPrompt(`/seo ${e.args}`, Date.now())
-
- if (audit !== null && (ctx.audit === null || ctx.audit.domain !== audit.domain || ctx.audit.finishMs !== null)) {
- follow($, ctx, audit)
- }
-
- return next(e)
- })
-
- on('agent.spawn', async ($, e, next) => {
- if (!isSeoAgent(e.subagentType)) {
- return next(e)
- }
-
- const isFollowing = ctx.audit !== null && ctx.audit.finishMs === null
-
- if (ctx.audit !== null && isFollowing) {
- setAudit($, ctx, { ...ctx.audit, agents: { ...ctx.audit.agents, [e.tool_use_id]: { type: e.subagentType, state: 'running', startMs: Date.now() } } })
- }
-
- const model = ctx.isEconomy && e.model === undefined ? economyModel(e.subagentType) : null
- const result = await next(model === null ? e : { ...e, model })
- const run = ctx.audit?.agents[e.tool_use_id]
-
- // The agent's id lets its own turn end close it, which a background agent needs.
- if (ctx.audit !== null && run !== undefined && result.agentId !== undefined) {
- setAudit($, ctx, { ...ctx.audit, agents: { ...ctx.audit.agents, [e.tool_use_id]: { ...run, agentId: result.agentId } } })
- }
-
- return result
- })
-
- // A foreground Agent call returns when its subagent is done; a background one returns at launch.
- on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
- const result = await next(e)
- const run = ctx.audit?.agents[e.tool_use_id]
- const status = (result.result as { status?: unknown } | undefined)?.status
- const isLaunchOnly = status === 'async_launched' || status === 'remote_launched'
-
- if (ctx.audit !== null && run !== undefined && run.state === 'running' && !isLaunchOnly) {
- const state = result.deny !== undefined || result.isError === true ? 'failed' : 'done'
-
- setAudit($, ctx, { ...ctx.audit, agents: { ...ctx.audit.agents, [e.tool_use_id]: { ...run, state, endMs: Date.now() } } })
- }
-
- return result
- })
-
- on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
- const result = await next(e)
- const path = fieldOf(e, 'file_path')
-
- if (path !== undefined && result.deny === undefined && result.isError !== true) {
- const before = ctx.audit
- // A Write carries the whole file; an Edit only a fragment, so its score is not read.
- const after = noteWrite(before, path, e.tool === 'Write' ? fieldOf(e, 'content') : undefined, Date.now())
-
- if (after !== null && after !== before) {
- if (before === null || before.finishMs !== null) {
- follow($, ctx, after)
- } else {
- setAudit($, ctx, after)
- }
- }
- }
-
- return result
- })
-
- on('turn.complete', async ($, e, next) => {
- const result = await next(e)
- const audit = ctx.audit
-
- if (e.agentId !== undefined) {
- // A subagent finished: close its run (the only signal a background agent gives).
- const entry = audit === null ? undefined : Object.entries(audit.agents).find(([, run]) => run.agentId === e.agentId && run.state === 'running')
-
- if (audit !== null && entry !== undefined) {
- setAudit($, ctx, { ...audit, agents: { ...audit.agents, [entry[0]]: { ...entry[1], state: 'done', endMs: Date.now() } } })
- }
-
- return result
- }
-
- // The receipt goes under the main answer, once, when the audit's data file exists.
- if (audit === null || audit.finishMs !== null || audit.score === null || ctx.isReceiptShown) {
- return result
- }
-
- const now = Date.now()
-
- ctx.isReceiptShown = true
- setAudit($, ctx, { ...audit, finishMs: now })
-
- const receipt = receiptText(audit, now)
- // `next` resolves to the answer itself; any other text is shown beneath it. Keep another mod's line, never the answer.
- const theirs = result.text !== '' && result.text !== e.answer ? result.text : ''
-
- return { ...result, text: theirs === '' ? receipt : `${theirs}\n${receipt}` }
- })
-
- on('session.compact', async ($, e, next) => {
- const audit = ctx.audit
-
- if (e.agentId !== undefined || audit === null || audit.finishMs !== null) {
- return next(e)
- }
-
- return next({ ...e, instructions: [e.instructions, compactInstructions(audit)].filter(Boolean).join('\n\n') })
- })
-
- on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
- const audit = ctx.audit
-
- if (!ctx.isBandOn || audit === null || ctx.isBandHidden || e.props.hasSurvey) {
- return next(e)
- }
-
- const { Box, Text, Button } = $.ui.resolve(e)
- const columns = Math.max(20, Math.floor(e.props.bodyColumns) - 10)
- // Other mods' bands sit below ours rather than being replaced.
- const theirs = await next(e)
-
- return Box({
- flexDirection: 'column',
- children: [
- Box({
- flexDirection: 'row',
- columnGap: 1,
- children: [
- Text({ color: audit.finishMs === null ? COLORS.blue : COLORS.good, children: [bandText(audit, Date.now(), columns, ctx.isEconomy)] }),
- Button({
- key: 'seo-cockpit-hide',
- label: 'hide',
- plain: true,
- onPress: () => {
- ctx.isBandHidden = true
- syncTicker($, ctx)
- $.ui.invalidate('ui.render')
- },
- }),
- ],
- }),
- theirs,
- ],
- })
- })
-
- // ------------------------------------------------------------------- pane
-
- on('ui.render', { component: 'Pane' }, async ($, e, next) => {
- if (e.requestId !== PANE_ID) {
- return next(e)
- }
-
- const table = $.ui.resolve(e)
- const kit: Kit = {
- Box: table.Box,
- Text: table.Text,
- Button: table.Button,
- ...('Markdown' in table && { Markdown: table.Markdown }),
- // An Input exists on every surface but mobile.
- ...(e.surface !== 'mobile' && 'Input' in table && { Input: table.Input }),
- // Every table is completed with every element name, so `'Svg' in table` holds on the terminal too, where an Svg draws nothing.
- ...(e.surface !== 'terminal' && 'Svg' in table && { Svg: table.Svg }),
- }
-
- ctx.pane.isOpen = true
-
- return paneView(kit, ctx.pane, Math.max(24, Math.floor(e.props.bodyColumns) - 1), e.props.isFocused, {
- open: tab => {
- ctx.pane.view = tab
- $.ui.invalidate('ui.render')
- },
- back: () => {
- ctx.pane.view = 'overview'
- $.ui.invalidate('ui.render')
- },
- refresh: () => void loadAll($, ctx).catch(() => undefined),
- exportHtml: () => void exportHtml($, ctx, false).catch(() => undefined),
- setTarget: value => void setTarget($, ctx, value).catch(() => undefined),
- })
- })
-
- on('ui.close', async ($, e, next) => {
- if (e.id === PANE_ID) {
- ctx.pane.isOpen = false
- }
-
- return next(e)
- })
-
- // --------------------------------------------------------------- commands
-
- on('session.start', async ($, e, next) => {
- await registerCommands($)
- await restoreAudit($, ctx)
-
- return next(e)
- })
-
- // /clear and /resume skip session.start; registering again replaces the command, so this is safe to repeat.
- on('classic.SessionStart', async ($, e, next) => {
- await registerCommands($)
-
- return next(e)
- })
-
- on('command.run', { command: 'seo-spend' }, async ($, e, next) => spendCommand($, ctx))
-
- on('command.run', { command: 'seo-doctor' }, async ($, e, next) => doctorCommand($, ctx))
-
- on('command.run', { command: 'seo-cockpit' }, async ($, e, next) => cockpitCommand($, ctx, e.args))
-}
diff --git a/plugins/seo-cockpit/hooks/views/pane.ts b/plugins/seo-cockpit/hooks/views/pane.ts
deleted file mode 100644
index b04166b..0000000
--- a/plugins/seo-cockpit/hooks/views/pane.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/**
- * The cockpit pane as an element tree. Pure: register.ts hands in the
- * surface's element constructors and the actions; nothing here touches `$`.
- *
- * One Overview (a line per source, in the order a person checks them) and one
- * detail view per source. Sized to the pane's own width: an inline pane in a
- * narrow terminal gets the same content in fewer columns, never a wrapped row
- * of controls. The first row holds no controls, leaving the engine's close
- * mark at the right edge clear.
- *
- * Charts are text (block characters and colored bars) everywhere; where the
- * surface draws `Svg` (desktop, and VS Code per the 2.1.288 typings), the
- * detail view draws them as SVG instead.
- */
-
-import type { Elements, RenderElement } from 'claude-code'
-
-import { barRow, endsOf, rankColor, sparkRow, svgOf, COLORS, type Chart } from '../lib/charts'
-import { rowOf, ROWS, type Row } from '../lib/overview'
-import type { TabId, TabModel } from '../lib/tabs'
-
-export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> &
- Partial<Pick<Elements['terminal'], 'Markdown' | 'Input'>> & { Svg?: Elements['desktop']['Svg'] }
-
-export type PaneState = {
- /** The Overview, or one source's detail. */
- view: 'overview' | TabId
- models: Partial<Record<TabId, TabModel>>
- loading: ReadonlySet<TabId>
- /** The site the cockpit is about, and where that came from. */
- host: string | null
- hostSource: 'setting' | 'typed' | 'folder' | 'last' | null
- /** The last HTML export, as a file path. */
- exported: string | null
-}
-
-export type PaneActions = {
- open: (tab: TabId) => void
- back: () => void
- refresh: () => void
- exportHtml: () => void
- setTarget: (value: string) => void
-}
-
-const cut = (text: string, width: number): string => (text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`)
-const pad = (text: string, width: number): string => cut(text, width).padEnd(width)
-
-function textChart(kit: Kit, chart: Chart, columns: number): RenderElement[] {
- const { Box, Text } = kit
- const title = Text({ bold: true, children: [cut(chart.title, columns)] })
-
- if (chart.kind === 'line') {
- const width = Math.max(10, Math.min(90, columns - 30))
- const rows = chart.series.map(series => {
- const { first, last } = endsOf(series.values)
- const ends = first === null || last === null ? 'no data' : `${Math.round(first * 100) / 100} to ${Math.round(last * 100) / 100}`
-
- return Box({ flexDirection: 'row', columnGap: 1, children: [Text({ color: series.color, children: [sparkRow(series.values, width, chart.invert === true)] }), Text({ dimColor: true, children: [cut(`${series.name} ${ends}`, 28)] })] })
- })
-
- return [title, ...rows, Text({ dimColor: true, children: [cut(`${chart.xLabels[0]}${' '.repeat(Math.max(1, width - chart.xLabels[0].length - chart.xLabels[1].length))}${chart.xLabels[1]}`, columns)] })]
- }
-
- if (chart.kind === 'bars') {
- const labelW = Math.min(28, Math.max(8, ...chart.rows.map(row => row.label.length)))
- const barW = Math.max(8, Math.min(40, columns - labelW - 14))
-
- return [
- title,
- ...chart.rows.map(row =>
- Box({ flexDirection: 'row', columnGap: 1, children: [Text({ children: [pad(row.label, labelW)] }), Text({ color: row.color, children: [barRow(row.value, chart.max, barW)] }), Text({ children: [row.text ?? String(row.value)] })] }),
- ),
- ]
- }
-
- return [
- title,
- ...chart.ranks.map((row, r) =>
- Box({ key: `grid-${r}`, flexDirection: 'row', children: row.map(rank => Text({ color: rankColor(rank), children: [rank === null ? ' -- ' : ` ${String(Math.min(rank, 99)).padStart(2)} `] })) }),
- ),
- Text({ dimColor: true, children: ['1-3 green, 4-10 amber, 11+ red, -- not found; north is up'] }),
- ]
-}
-
-function chartView(kit: Kit, chart: Chart, columns: number): RenderElement[] {
- if (kit.Svg !== undefined) {
- const { source, height } = svgOf(chart)
- const width = Math.min(560, Math.max(280, columns * 7))
-
- return [kit.Svg({ source, alt: chart.title, width, height: Math.round((height * width) / 560) })]
- }
-
- return textChart(kit, chart, columns)
-}
-
-function tableView(kit: Kit, table: TabModel['tables'][number], columns: number): RenderElement[] {
- const widths = table.head.map((head, i) => Math.max(head.length, ...table.rows.map(row => (row[i] ?? '').length)))
- const first = Math.max(12, columns - widths.slice(1).reduce((a, b) => a + b + 2, 0) - 2)
- const fit = widths.map((w, i) => (i === 0 ? Math.min(w, first) : w))
- // Numbers right-aligned, words left-aligned.
- const isNumeric = (i: number) => table.rows.every(row => /^[\d.,%$+\-kM ]*$/.test(row[i] ?? ''))
- const line = (cells: readonly string[]) => cells.map((cell, i) => (i === 0 ? pad(cell, fit[0] ?? 12) : isNumeric(i) ? cell.padStart(fit[i] ?? 4) : pad(cell, fit[i] ?? 4))).join(' ')
-
- return [kit.Text({ dimColor: true, children: [cut(line(table.head), columns)] }), ...table.rows.map(row => kit.Text({ children: [cut(line(row), columns)] }))]
-}
-
-const MARK: Record<Row['state'], { mark: string; color?: string }> = {
- ok: { mark: '●', color: COLORS.good },
- loading: { mark: '…' },
- missing: { mark: '○', color: COLORS.muted },
- error: { mark: '!', color: COLORS.poor },
-}
-
-/** Keys work only while the pane holds focus; say how to get it otherwise. */
-function footer(kit: Kit, state: PaneState, isFocused: boolean, actions: PaneActions, extra: RenderElement[] = []): RenderElement {
- const { Box, Text, Button } = kit
- const children: RenderElement[] = isFocused
- ? [...extra, Button({ key: 'refresh', label: 'Refresh', hotkey: 'r', plain: true, onPress: actions.refresh }), Button({ key: 'export', label: 'Export', hotkey: 'e', plain: true, onPress: actions.exportHtml })]
- : [Text({ dimColor: true, children: ['ctrl+x tab to use the keys'] })]
-
- if (state.exported !== null && kit.Markdown !== undefined) {
- // A Link takes only https (or http://localhost) and refuses the whole tree otherwise; Markdown links may use file:.
- children.push(kit.Markdown({ text: `[open export](file://${encodeURI(state.exported)})` }))
- }
-
- return Box({ flexDirection: 'row', columnGap: 2, marginTop: 1, children })
-}
-
-/** The Overview: which site, then one line per source; missing data stays visible with its fix. */
-export function overviewView(kit: Kit, state: PaneState, columns: number, isFocused: boolean, actions: PaneActions): RenderElement {
- const { Box, Text, Button } = kit
- const where = { setting: 'default', typed: 'chosen here', folder: 'from this folder', last: 'last used', none: '' }[state.hostSource ?? 'none']
- const children: RenderElement[] = [
- // Row 1 carries no controls: the engine draws its close mark at the right edge.
- Text({ children: [Text({ bold: true, children: [cut(state.host ?? 'No site yet', Math.max(10, columns - 24))] }), Text({ dimColor: true, children: [where === '' ? '' : ` ${where}`] })] }),
- ]
-
- // No site, or only the last one used elsewhere: offer the field to set this folder's own.
- if ((state.host === null || state.hostSource === 'last') && kit.Input !== undefined) {
- children.push(kit.Input({ key: 'target', label: 'Site', placeholder: state.host ?? 'example.com', submitLabel: 'go', ...(state.host === null && { autoFocus: true }), onSubmit: value => actions.setTarget(value) }))
- }
-
- const labelWidth = Math.max(...ROWS.map(row => row.label.length))
-
- for (const row of ROWS.map(r => rowOf(r.id, state.models[r.id], state.loading.has(r.id)))) {
- const { mark } = MARK[row.state]
- // The hotkey draws as "1: " before a plain label; keep the whole line inside the pane.
- const label = cut(`${mark} ${row.label.padEnd(labelWidth)} ${row.line}`, Math.max(12, columns - 4))
-
- children.push(Button({ key: `row-${row.id}`, label, hotkey: row.key, plain: true, onPress: () => actions.open(row.id) }))
- }
-
- children.push(footer(kit, state, isFocused, actions))
-
- return Box({ flexDirection: 'column', children })
-}
-
-/** One source in detail: its numbers, charts and tables, with a way back. */
-export function detailView(kit: Kit, state: PaneState, tab: TabId, columns: number, isFocused: boolean, actions: PaneActions): RenderElement {
- const { Box, Text, Button } = kit
- const model = state.models[tab]
- const label = ROWS.find(row => row.id === tab)?.label ?? tab
- const body: RenderElement[] = [Text({ children: [Text({ bold: true, children: [model?.heading ?? label] })] })]
-
- if (model === undefined) {
- body.push(Text({ dimColor: true, children: [state.loading.has(tab) ? 'checking…' : 'not loaded yet: press r'] }))
- } else {
- body.push(Text({ dimColor: true, children: [cut(`${model.source} · ${model.fetchedAt}`, columns)] }))
-
- if (model.error !== null) {
- body.push(Text({ color: COLORS.poor, children: [cut(model.error, columns * 3)] }))
- }
-
- for (const kpi of model.kpis) {
- body.push(Text({ children: [`${kpi.label}: `, Text({ bold: true, children: [kpi.value] })] }))
- }
-
- for (const chart of model.charts) {
- body.push(Box({ flexDirection: 'column', marginTop: 1, children: chartView(kit, chart, columns) }))
- }
-
- for (const table of model.tables) {
- body.push(Box({ flexDirection: 'column', marginTop: 1, children: tableView(kit, table, columns) }))
- }
-
- body.push(...model.notes.map(note => Text({ dimColor: true, children: [cut(note, columns * 3)] })))
- }
-
- const back = Button({ key: 'back', label: 'Back', hotkey: 'b', plain: true, onPress: actions.back })
-
- return Box({ flexDirection: 'column', children: [...body, footer(kit, state, isFocused, actions, isFocused ? [back] : [])] })
-}
-
-/** The whole pane for its current view. */
-export function paneView(kit: Kit, state: PaneState, columns: number, isFocused: boolean, actions: PaneActions): RenderElement {
- return state.view === 'overview' ? overviewView(kit, state, columns, isFocused, actions) : detailView(kit, state, state.view, columns, isFocused, actions)
-}
diff --git a/plugins/seo-cockpit/tests/audit-logic.test.ts b/plugins/seo-cockpit/tests/audit-logic.test.ts
deleted file mode 100644
index db69d2a..0000000
--- a/plugins/seo-cockpit/tests/audit-logic.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { describe, expect, test } from 'claude-code/testing'
-
-import { auditFromPrompt, auditPathOf, bandText, compactInstructions, domainOf, economyModel, isSeoAgent, newAudit, noteWrite, receiptText, scoresOf } from '../hooks/lib/audit'
-
-const DATA = JSON.stringify({ summary: { health_score: 72 }, categories: [{ name: 'Technical SEO', score: 81 }, { name: 'Schema', score: 40 }, { name: 'Content', score: 55 }] })
-
-describe('starting an audit', () => {
- test('the /seo audit prompt starts one, namespaced or not', () => {
- expect(auditFromPrompt('/seo audit https://www.Example.com/shop', 5)?.domain).toBe('example.com')
- expect(auditFromPrompt('/claude-seo:seo audit example.org', 5)?.domain).toBe('example.org')
- expect(auditFromPrompt('/seo page https://example.com', 5)).toBeNull()
- expect(auditFromPrompt('please audit my site', 5)).toBeNull()
- })
-
- test('domainOf needs a dotted host', () => {
- expect(domainOf('<https://sub.example.co.uk/x>')).toBe('sub.example.co.uk')
- expect(domainOf('localhost')).toBeNull()
- })
-
- test('a write into a *-audit folder starts one when none is running', () => {
- const audit = noteWrite(null, '/work/example.com-audit/findings/technical.md', '# t', 10)
-
- expect(audit?.domain).toBe('example.com')
- expect(audit?.dir).toBe('/work/example.com-audit')
- expect(audit?.findings).toEqual(['technical.md'])
- })
-})
-
-describe('following it', () => {
- test('auditPathOf tells findings, data and other files apart, either slash', () => {
- expect(auditPathOf('/w/a.com-audit/findings/schema.md')?.kind).toBe('finding')
- expect(auditPathOf('C:\\w\\a.com-audit\\audit-data.json')?.kind).toBe('data')
- expect(auditPathOf('/w/a.com-audit/screenshots/x.png')?.kind).toBe('other')
- expect(auditPathOf('/w/src/index.html')).toBeNull()
- })
-
- test('the data file carries the score; junk carries none', () => {
- expect(scoresOf(DATA).score).toBe(72)
- expect(scoresOf(DATA).categories.length).toBe(3)
- expect(scoresOf('{oops')).toEqual({ score: null, categories: [] })
- })
-
- test('a findings file is counted once', () => {
- const one = noteWrite(newAudit('a.com', 0), '/w/a.com-audit/findings/geo.md', 'x', 1)
- const two = noteWrite(one, '/w/a.com-audit/findings/geo.md', 'y', 2)
-
- expect(two?.findings).toEqual(['geo.md'])
- })
-
- test('economy routes only the five Opus agents', () => {
- expect(economyModel('claude-seo:seo-geo')).toBe('sonnet')
- expect(economyModel('seo-technical')).toBeNull()
- expect(isSeoAgent('claude-seo:seo-technical')).toBe(true)
- expect(isSeoAgent('Explore')).toBe(false)
- })
-})
-
-describe('what it shows', () => {
- const audit = {
- ...newAudit('example.com', 0),
- dir: '/w/example.com-audit',
- agents: { a: { type: 'seo-technical', state: 'done' as const, startMs: 0 }, b: { type: 'seo-geo', state: 'running' as const, startMs: 0 } },
- findings: ['technical.md'],
- spentUsd: 0.42,
- }
-
- test('the band line counts agents, findings, spend and time, and fits the width', () => {
- expect(bandText(audit, 252_000, 200, true)).toBe('seo audit example.com 1 running, 1 done findings 1 spend $0.42 4m12s economy')
- expect(bandText(audit, 252_000, 20, false).length).toBe(20)
- })
-
- test('the receipt names the score, the weakest categories and the report', () => {
- const done = { ...audit, ...scoresOf(DATA) }
- const text = receiptText(done, 60_000)
-
- expect(text).toContain('score 72/100')
- expect(text).toContain('weakest Schema 40, Content 55')
- expect(text).toContain('/w/example.com-audit/FULL-AUDIT-REPORT.md')
- })
-
- test('compaction keeps the folder, agents and findings', () => {
- const text = compactInstructions(audit)
-
- expect(text).toContain('/w/example.com-audit')
- expect(text).toContain('agents finished: seo-technical; still running: seo-geo')
- expect(text).toContain('technical.md')
- })
-})
diff --git a/plugins/seo-cockpit/tests/audit.test.ts b/plugins/seo-cockpit/tests/audit.test.ts
deleted file mode 100644
index bad995b..0000000
--- a/plugins/seo-cockpit/tests/audit.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, expect, mock, test } from 'claude-code/testing'
-
-import { worldOf } from './fixtures/world'
-
-const DATA = JSON.stringify({ summary: { health_score: 72 }, categories: [{ name: 'Schema', score: 40 }] })
-const BAND = {
- plugin: 'seo-cockpit',
- component: 'AbovePrompt' as const,
- viewport: { columns: 140, rows: 40 },
- props: { hasSurvey: false, isWorking: true, maxRows: 10, bodyColumns: 140, scroll: { offset: 0, bodyRows: 10 }, view: {} },
-}
-const prompt = (text: string) => ({ text, wait: false, origin: { kind: 'composer' as const } })
-// The kit's inputs for these events carry engine fields a test does not need; the casts keep the tests readable.
-const spawn = (id: string, subagentType: string) =>
- ({ tool_use_id: id, prompt: 'p', description: 'd', subagentType, provider: { plugin: 'claude-seo', tier: 'user' }, parentModel: 'claude-opus-5-5' }) as never
-const turnDone = () => ({ turnId: 't1', answer: 'Audit complete.', durationMs: 1000, isAborted: false, reason: 'answer' }) as never
-
-/** The engine's own answers at the bottom of each event the audit hooks pass on. */
-function engine(on: Parameters<typeof worldOf>[0]) {
- const seen = { models: [] as (string | undefined)[], instructions: [] as (string | undefined)[] }
-
- on('prompt.submit', ($, e) => ({ text: e.text }))
- on('agent.spawn', ($, e) => {
- seen.models.push(e.model)
-
- return { model: e.model ?? 'inherit' }
- })
- // As the engine answers: the turn's own answer text.
- on('turn.complete', ($, e) => ({ text: (e as unknown as { answer: string }).answer }))
- on('session.compact', ($, e) => {
- seen.instructions.push(e.instructions)
-
- return { messages: e.messages }
- })
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['drawn by Claude Code'] }) as never)
-
- return seen
-}
-
-describe('audit band and receipt', () => {
- test('an audit is followed from prompt to receipt, and the band shows it', async ($, on) => {
- mock.clock(on)
- const world = worldOf(on)
-
- engine(on)
- await $.prompt.submit(prompt('/seo audit https://example.com'))
- await $.agent.spawn(spawn('call-1', 'claude-seo:seo-technical'))
- await $.agent.spawn(spawn('call-2', 'claude-seo:seo-geo'))
- await $.tool.call({ tool: 'Agent', tool_use_id: 'call-1', prompt: 'p', description: 'd', subagent_type: 'seo-technical' } as never)
- await $.tool.call({ tool: 'Write', file_path: '/work/example.com-audit/findings/technical.md', content: '# Technical' })
-
- const ui = await $.ui.mount({ ...BAND, surface: 'terminal' })
-
- expect(await ui.find({ type: 'Text', text: /seo audit example\.com {2}1 running, 1 done {2}findings 1/ })).toBeDefined()
- await ui.unmount()
-
- await $.tool.call({ tool: 'Write', file_path: '/work/example.com-audit/audit-data.json', content: DATA })
- const result = await $.turn.complete(turnDone())
-
- expect(result.text).toContain('score 72/100')
- expect(result.text).toContain('weakest Schema 40')
- // The receipt alone: the answer is not repeated beneath itself.
- expect(result.text).not.toContain('Audit complete.')
- expect(world.ran.filter(tool => tool === 'Write').length).toBe(2)
- })
-
- test('the receipt is shown once', async ($, on) => {
- mock.clock(on)
- worldOf(on)
- engine(on)
- await $.tool.call({ tool: 'Write', file_path: '/work/a.com-audit/audit-data.json', content: DATA })
-
- expect((await $.turn.complete(turnDone())).text).toContain('score 72/100')
- expect((await $.turn.complete(turnDone())).text).toBe('Audit complete.')
- })
-
- test('other mods\' bands stay visible under ours', async ($, on) => {
- mock.clock(on)
- worldOf(on)
- engine(on)
- await $.prompt.submit(prompt('/seo audit example.com'))
-
- const ui = await $.ui.mount({ ...BAND, surface: 'terminal' })
-
- expect(await ui.find({ type: 'Text', text: /seo audit example\.com/ })).toBeDefined()
- expect(await ui.find({ type: 'Text', text: 'drawn by Claude Code' })).toBeDefined()
- })
-
- test('with no audit the band is Claude Code\'s own', async ($, on) => {
- worldOf(on)
- engine(on)
-
- const ui = await $.ui.mount({ ...BAND, surface: 'terminal' })
-
- expect(await ui.find({ type: 'Text', text: 'drawn by Claude Code' })).toBeDefined()
- })
-
- test('compaction during an audit keeps its state', async ($, on) => {
- mock.clock(on)
- worldOf(on)
-
- const seen = engine(on)
-
- await $.prompt.submit(prompt('/seo audit example.com'))
- // A compaction always leaves at least one message; the engine refuses an empty list.
- await $.session.compact({ trigger: 'auto', messages: [{ role: 'user', text: 'Audit example.com', toolUses: [] }] })
-
- expect(seen.instructions[0]).toContain('A claude-seo audit of example.com is in progress')
- })
-})
-
-describe('economy mode', () => {
- test('routes Opus agents to Sonnet and leaves the rest', { options: { economy: true } }, async ($, on) => {
- worldOf(on)
-
- const seen = engine(on)
-
- await $.agent.spawn(spawn('c1', 'claude-seo:seo-content'))
- await $.agent.spawn(spawn('c2', 'claude-seo:seo-technical'))
- await $.agent.spawn(spawn('c3', 'Explore'))
-
- expect(seen.models).toEqual(['sonnet', undefined, undefined])
- })
-
- test('is off by default', async ($, on) => {
- worldOf(on)
-
- const seen = engine(on)
-
- await $.agent.spawn(spawn('c1', 'claude-seo:seo-content'))
-
- expect(seen.models).toEqual([undefined])
- })
-})
diff --git a/plugins/seo-cockpit/tests/cockpit-logic.test.ts b/plugins/seo-cockpit/tests/cockpit-logic.test.ts
deleted file mode 100644
index adf3432..0000000
--- a/plugins/seo-cockpit/tests/cockpit-logic.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { describe, expect, test } from 'claude-code/testing'
-
-import { barRow, htmlPage, rankColor, resample, scoreColor, sparkRow, svgOf, vitalColor, COLORS } from '../hooks/lib/charts'
-import { auditModel, gscModel, mapsModel, rankingsModel, spendModel, vitalsModel } from '../hooks/lib/tabs'
-
-const day = (i: number) => new Date(Date.UTC(2026, 6, 3) + i * 86_400_000).toISOString().slice(0, 10)
-const GSC_DATE = { property: 'sc-domain:a.com', error: null, rows: Array.from({ length: 60 }, (_, i) => ({ keys: [day(i)], date: day(i), clicks: i < 32 ? 10 : 20, impressions: 100, ctr: 10, position: 10 - i / 10 })) }
-const GSC_QUERY = { error: null, rows: [{ keys: ['a'], query: 'a', clicks: 5, impressions: 50, ctr: 10, position: 2 }, { keys: ['b'], query: 'b', clicks: 1, impressions: 90, ctr: 1, position: 7 }] }
-
-describe('chart helpers', () => {
- test('spark rows scale to their own range and invert for positions', () => {
- expect(sparkRow([1, 2, 3], 3)).toBe('▁▅█')
- expect(sparkRow([1, 2, 3], 3, true)).toBe('█▅▁')
- expect(sparkRow([1, null, 3], 3)).toBe('▁ █')
- })
-
- test('resample averages buckets down to the width', () => {
- expect(resample([1, 3, 5, 7], 2)).toEqual([2, 6])
- })
-
- test('bars fill to the value', () => {
- expect(barRow(5, 10, 4)).toBe('██░░')
- })
-
- test('status colors follow the thresholds', () => {
- expect(scoreColor(85)).toBe(COLORS.good)
- expect(scoreColor(40)).toBe(COLORS.poor)
- expect(rankColor(null)).toBe(COLORS.muted)
- expect(rankColor(2)).toBe(COLORS.good)
- expect(vitalColor(3000, 2500, 4000)).toBe(COLORS.warn)
- })
-
- test('every chart kind makes an SVG well under the size limit', () => {
- const charts = [
- svgOf({ kind: 'line', title: 'L', series: [{ name: 'x', values: Array.from({ length: 90 }, (_, i) => i), color: COLORS.blue }], xLabels: ['a', 'b'], bands: { good: 10, poor: 50 } }),
- svgOf({ kind: 'bars', title: 'B', rows: [{ label: 'x', value: 3, color: COLORS.good }], max: 5 }),
- svgOf({ kind: 'grid', title: 'G', ranks: [[1, null], [5, 30]] }),
- ]
-
- for (const chart of charts) {
- expect(chart.source.startsWith('<svg')).toBe(true)
- expect(chart.source.length).toBeLessThan(131_072)
- }
- })
-
- test('the HTML export is self-contained and escapes text', () => {
- const html = htmlPage('T', 'now', [{ heading: '<b>x</b>', source: 's', kpis: [], charts: [], tables: [], notes: [] }])
-
- expect(html).toContain('&lt;b&gt;x&lt;/b&gt;')
- expect(html).not.toContain('<script')
- expect(html).toContain('prefers-color-scheme:dark')
- })
-})
-
-describe('tab models', () => {
- test('Search Console compares the last 28 days with the 28 before', () => {
- const model = gscModel(GSC_DATE, GSC_QUERY, 'sc-domain:a.com', 'now')
-
- expect(model.kpis[0]).toEqual({ label: 'Clicks, 28 days', value: '560 (+100%)' })
- expect(model.tables[0]?.rows[0]?.[0]).toBe('a')
- })
-
- test('an API error becomes a message with the fix', () => {
- const model = gscModel({ error: 'no credentials', rows: [] }, null, '', 'now')
-
- expect(model.error).toBe('no credentials')
- expect(model.notes.join(' ')).toContain('/seo google setup')
- })
-
- test('Rankings buckets queries and lists striking distance', () => {
- const model = rankingsModel(GSC_DATE, GSC_QUERY, null, 'sc-domain:a.com', 'now')
-
- expect(model.kpis.find(k => k.label === 'Queries in top 3')?.value).toBe('1')
- expect(model.tables[0]?.rows[0]?.[0]).toBe('b')
- })
-
- test('Vitals reads p75 against the thresholds', () => {
- const model = vitalsModel({ target: 'https://a.com', metrics: { largest_contentful_paint: { p75_values: [3000, 2400], good_threshold: 2500, poor_threshold: 4000 } }, collection_periods: [] }, 'https://a.com', 'now')
-
- expect(model.kpis).toEqual([{ label: 'LCP p75', value: '2400 ms good' }])
- })
-
- test('the audit is sorted weakest first and keeps critical findings', () => {
- const model = auditModel({ summary: { health_score: 60 }, categories: [{ name: 'A', score: 90, findings: [] }, { name: 'B', score: 30, findings: [{ title: 'bad', severity: 'Critical' }] }] }, 'x-audit/audit-data.json', 'now')
- const bars = model.charts[0]
-
- expect(bars?.kind === 'bars' ? bars.rows.map(r => r.label) : []).toEqual(['B', 'A'])
- expect(model.tables[0]?.rows).toEqual([['Critical', 'B', 'bad']])
- })
-
- test('Maps computes share of local voice from the grid', () => {
- const model = mapsModel({ keyword: 'k', ranks: [[1, 2], [5, null]] }, 'g.json', 'now')
-
- expect(model.kpis[0]).toEqual({ label: 'Share of local voice', value: '50%' })
- expect(model.kpis[3]).toEqual({ label: 'Not found', value: '1' })
- })
-
- test('a missing audit or grid says how to make one', () => {
- expect(auditModel(null, '', 'now').notes.join(' ')).toContain('/seo audit')
- expect(mapsModel(null, '', 'now').notes.join(' ')).toContain('/seo maps grid')
- })
-
- test('Spend leaves out the reset row', () => {
- const model = spendModel({ date: '2026-10-03', total_usd: 1, daily_limit_usd: 10, by_endpoint: { _audit_reset: { cost_usd: 0 }, x: { cost_usd: 1 } } }, { daily_totals: {} }, 'now')
- const bars = model.charts[1]
-
- expect(bars?.kind === 'bars' ? bars.rows.map(r => r.label) : []).toEqual(['x'])
- })
-})
diff --git a/plugins/seo-cockpit/tests/cockpit.test.ts b/plugins/seo-cockpit/tests/cockpit.test.ts
deleted file mode 100644
index a06c9cf..0000000
--- a/plugins/seo-cockpit/tests/cockpit.test.ts
+++ /dev/null
@@ -1,241 +0,0 @@
-import { describe, expect, mock, test } from 'claude-code/testing'
-
-import { command, worldOf } from './fixtures/world'
-
-// As the owner's terminal drew it: an inline pane about 53 cells wide.
-const NARROW = { plugin: 'seo-cockpit', component: 'Pane' as const, requestId: 'seo-cockpit', viewport: { columns: 55, rows: 40 }, props: { title: 'SEO Cockpit', isFocused: true, bodyColumns: 53, placement: 'inline' as const, scroll: { offset: 0, bodyRows: 12 }, view: {} } }
-const WIDE = { ...NARROW, viewport: { columns: 160, rows: 50 }, props: { ...NARROW.props, bodyColumns: 110, placement: 'dock' as const, scroll: { offset: 0, bodyRows: 40 } } }
-
-const AUDIT = JSON.stringify({ summary: { health_score: 85 }, categories: [{ name: 'Schema', score: 76, findings: [] }, { name: 'Technical SEO', score: 94, findings: [] }], meta: { site: 'https://claude-seo.md' } })
-
-/** The listing of a working folder holding one audit. */
-const LISTING = { '/work': [{ name: 'claude-seo.md-audit', kind: 'dir' as const }], '/work/claude-seo.md-audit': [{ name: 'audit-data.json', kind: 'file' as const }] }
-
-/** The rest of that folder: its files' contents, and the engine calls the pane makes. */
-function auditFolder(on: Parameters<typeof worldOf>[0]) {
- on('session.cwd', () => ({ value: '/work' }))
- on('fs.stat', () => ({ value: { kind: 'file', size: AUDIT.length, mtimeMs: 1, isLink: false } }) as never)
- on('fs.read', ($, e) => (e.path.endsWith('audit-data.json') ? { value: AUDIT } : { deny: 'ENOENT' }))
- on('store.get', () => ({ value: undefined }))
- on('store.set', () => ({ value: undefined }))
- on('ui.status', () => ({ value: undefined }))
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
-}
-
-describe('cockpit', () => {
- test('/seo-cockpit opens on the Overview for the site this folder shows, with no setup', async ($, on) => {
- worldOf(on, { listing: LISTING, scripts: { run: { exitCode: 3, stdout: '', stderr: 'Claude SEO runtime is not ready.' } } })
- auditFolder(on)
-
- const opened: string[] = []
-
- on('ui.open', ($, e) => {
- opened.push(`${e.id}${e.focus === true ? ' focused' : ''}${e.closeOnEscape === true ? ' esc' : ''}`)
-
- return { value: { isPlaced: true } } as never
- })
- mock.clock(on)
-
- const result = await $.command.run(command('seo-cockpit'))
-
- expect(opened).toEqual(['seo-cockpit focused'])
- // The engine names the plugin itself; the reply is the outcome only.
- expect(result.text).toBe('Cockpit open for claude-seo.md.')
-
- const ui = await $.ui.mount({ ...NARROW, surface: 'terminal' })
-
- expect(await ui.find({ type: 'Text', text: /claude-seo\.md/ })).toBeDefined()
- expect(await ui.find({ key: 'row-audit' })).toBeDefined()
- expect(await ui.find({ key: 'row-vitals' })).toBeDefined()
- })
-
- test('a second /seo-cockpit closes it', async ($, on) => {
- worldOf(on, { listing: LISTING })
- auditFolder(on)
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.close', () => ({ value: undefined }))
- mock.clock(on)
-
- await $.command.run(command('seo-cockpit'))
-
- expect((await $.command.run(command('seo-cockpit'))).text).toBe('Cockpit closed.')
- })
-
- test('with no site to infer, the pane asks for one in place', async ($, on) => {
- worldOf(on)
- on('session.cwd', () => ({ value: '/empty' }))
- on('store.get', () => ({ value: undefined }))
- on('store.set', () => ({ value: undefined }))
- on('ui.status', () => ({ value: undefined }))
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
- mock.clock(on)
-
- expect((await $.command.run(command('seo-cockpit'))).text).toContain('Type the site in the pane')
-
- const ui = await $.ui.mount({ ...NARROW, surface: 'terminal' })
-
- expect(await ui.find({ key: 'target' })).toBeDefined()
- })
-
- test('in a folder with no audit, the last site used anywhere is shown, and can be changed', async ($, on) => {
- worldOf(on)
- on('session.cwd', () => ({ value: '/elsewhere' }))
- on('store.get', ($, e) => ({ value: e.key === 'target:last' ? 'claude-seo.md' : undefined }))
- on('store.set', () => ({ value: undefined }))
- on('ui.status', () => ({ value: undefined }))
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
- mock.clock(on)
-
- expect((await $.command.run(command('seo-cockpit'))).text).toBe('Cockpit open for claude-seo.md.')
-
- const ui = await $.ui.mount({ ...NARROW, surface: 'terminal' })
-
- expect(await ui.find({ type: 'Text', text: /last used/ })).toBeDefined()
- expect(await ui.find({ key: 'target' })).toBeDefined()
- })
-
- test('/seo-cockpit <site> opens that site and remembers it here and as the last one', async ($, on) => {
- worldOf(on)
-
- const saved: Record<string, unknown> = {}
-
- on('session.cwd', () => ({ value: '/elsewhere' }))
- on('store.get', ($, e) => ({ value: saved[e.key] }))
- on('store.set', ($, e) => {
- saved[e.key] = e.value
-
- return { value: undefined }
- })
- on('ui.status', () => ({ value: undefined }))
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
- mock.clock(on)
-
- expect((await $.command.run(command('seo-cockpit', 'claude-seo.md'))).text).toBe('Cockpit open for claude-seo.md.')
- expect(saved['target:/elsewhere']).toBe('claude-seo.md')
- expect(saved['target:last']).toBe('claude-seo.md')
- expect((await $.command.run(command('seo-cockpit', 'claude-ads.md'))).text).toBe('Cockpit switched to claude-ads.md.')
- expect((await $.command.run(command('seo-cockpit', 'not a site'))).text).toContain('is not a site')
- })
-
- test('the default site opens from any folder, with its remembered audit', { options: { site: 'claude-seo.md' } }, async ($, on) => {
- worldOf(on)
- on('session.cwd', () => ({ value: '/anywhere' }))
- on('store.get', ($, e) => ({ value: e.key === 'audit:claude-seo.md' ? '/work/claude-seo.md-audit/audit-data.json' : undefined }))
- on('store.set', () => ({ value: undefined }))
- on('fs.read', ($, e) => (e.path.endsWith('audit-data.json') ? { value: AUDIT } : { deny: 'ENOENT' }))
- on('ui.status', () => ({ value: undefined }))
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
- mock.clock(on)
-
- expect((await $.command.run(command('seo-cockpit'))).text).toBe('Cockpit open for claude-seo.md.')
-
- const ui = await $.ui.mount({ ...NARROW, surface: 'terminal' })
-
- expect(await ui.find({ type: 'Text', text: /default/ })).toBeDefined()
- await ui.press({ key: 'refresh' })
- expect(await ui.find({ key: 'row-audit' })).toBeDefined()
- })
-
- test('a bare default site queries the sc-domain property, and the audits folder finds its audit', { options: { site: 'claude-seo.md', auditsFolder: '/audits' } }, async ($, on) => {
- const world = worldOf(on, { scripts: { run: { stdout: { error: null, rows: [] } } } })
-
- on('session.cwd', () => ({ value: '/anywhere' }))
- on('store.get', () => ({ value: undefined }))
- on('store.set', () => ({ value: undefined }))
- on('fs.read', ($, e) => (e.path === '/audits/claude-seo.md-audit/audit-data.json' ? { value: AUDIT } : { deny: 'ENOENT' }))
- on('ui.status', () => ({ value: undefined }))
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
- mock.clock(on)
-
- await $.command.run(command('seo-cockpit'))
-
- const ui = await $.ui.mount({ ...WIDE, surface: 'terminal' })
-
- await ui.press({ key: 'refresh' })
- // Search Console needs sc-domain:claude-seo.md; the bare name is not a property.
- expect(world.runs.some(run => run.includes('--property sc-domain:claude-seo.md'))).toBe(true)
- expect(world.runs.some(run => / --property claude-seo\.md/.test(run))).toBe(false)
- await ui.press({ key: 'row-audit' })
- expect(await ui.find({ type: 'Text', text: /85\/100/ })).toBeDefined()
- })
-
- test('a site chosen in a folder beats the default', { options: { site: 'claude-seo.md' } }, async ($, on) => {
- worldOf(on)
- on('session.cwd', () => ({ value: '/client' }))
- on('store.get', ($, e) => ({ value: e.key === 'target:/client' ? 'client.example' : undefined }))
- on('store.set', () => ({ value: undefined }))
- on('ui.status', () => ({ value: undefined }))
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)
- mock.clock(on)
-
- expect((await $.command.run(command('seo-cockpit'))).text).toBe('Cockpit open for client.example.')
- })
-
- test('with no pane on screen, it writes the HTML dashboard instead', async ($, on) => {
- worldOf(on)
-
- const written: string[] = []
-
- on('ui.open', () => ({ value: { isPlaced: false, reason: 'no pane here' } }) as never)
- on('session.cwd', () => ({ value: '/work' }))
- on('store.get', () => ({ value: undefined }))
- on('fs.write', ($, e) => {
- written.push(e.path)
-
- return { value: undefined }
- })
-
- const result = await $.command.run(command('seo-cockpit'))
-
- expect(result.text).toContain('No pane on this screen (no pane here)')
- expect(written.length).toBe(1)
- expect(written[0]).toMatch(/^\/work\/seo-cockpit-.*\.html$/)
- })
-
- test('a row opens its detail; charts are text in the terminal and SVG on the desktop', async ($, on) => {
- const day = (i: number) => new Date(Date.UTC(2026, 6, 3) + i * 86_400_000).toISOString().slice(0, 10)
- const gsc = { property: 'sc-domain:claude-seo.md', error: null, rows: Array.from({ length: 60 }, (_, i) => ({ keys: [day(i)], date: day(i), query: 'q', clicks: i, impressions: 10 * i, ctr: 1, position: 5 })) }
-
- // runtime.py run <script> ...: the fixture keys on the subcommand, `run`.
- worldOf(on, { listing: LISTING, scripts: { run: { stdout: gsc } } })
- auditFolder(on)
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- mock.clock(on)
-
- await $.command.run(command('seo-cockpit'))
-
- const terminal = await $.ui.mount({ ...WIDE, surface: 'terminal' })
-
- await terminal.press({ key: 'refresh' })
- await terminal.press({ key: 'row-gsc' })
- expect(await terminal.find({ type: 'Text', text: /Clicks per day/ })).toBeDefined()
- expect(await terminal.find({ type: 'Svg' })).toBeUndefined()
- await terminal.unmount()
-
- const desktop = await $.ui.mount({ ...WIDE, surface: 'desktop' })
-
- expect(await desktop.find({ type: 'Svg' })).toBeDefined()
- await desktop.press({ key: 'back' })
- expect(await desktop.find({ key: 'row-audit' })).toBeDefined()
- })
-
- test('unfocused, the footer says how to reach the keys instead of listing them', async ($, on) => {
- worldOf(on, { listing: LISTING })
- auditFolder(on)
- on('ui.open', () => ({ value: { isPlaced: true } }) as never)
- mock.clock(on)
-
- await $.command.run(command('seo-cockpit'))
-
- const ui = await $.ui.mount({ ...NARROW, surface: 'terminal', props: { ...NARROW.props, isFocused: false } })
-
- expect(await ui.find({ type: 'Text', text: /ctrl\+x tab/ })).toBeDefined()
- expect(await ui.find({ key: 'refresh' })).toBeUndefined()
- })
-})
diff --git a/plugins/seo-cockpit/tests/fixtures/world.ts b/plugins/seo-cockpit/tests/fixtures/world.ts
deleted file mode 100644
index 3205af7..0000000
--- a/plugins/seo-cockpit/tests/fixtures/world.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import type { On } from 'claude-code'
-
-/**
- * The world beneath seo-cockpit, in memory: what each claude-seo script
- * answers, what the person answers when asked, and a record of everything
- * the plugin asked for.
- */
-export type World = {
- /** Every argv the plugin ran, joined by spaces, after the interpreter. */
- runs: string[]
- /** The environment each run was given, in the same order. */
- envs: Array<Readonly<Record<string, string>>>
- /** Every question the plugin asked. */
- asked: string[]
- /** Calls that reached the tool beneath the plugin. */
- ran: string[]
- commands: string[]
-}
-
-type Reply = { exitCode?: number; stdout?: unknown; stderr?: string } | 'throw'
-
-export type Setup = {
- /** What the tool beneath the plugin answers: a result (default) or an error result. */
- toolFails?: boolean
- /** Answers by script subcommand (`check`, `log`, `today`, `summary`, `doctor`). */
- scripts?: Partial<Record<string, Reply>>
- /** The label the person picks; `null` dismisses the dialog. */
- answer?: string | null
- /** Whether claude-seo is found on disk. */
- hasRoot?: boolean
- /** Folder listings by path, for tests that need files to exist; any other path is missing. */
- listing?: Readonly<Record<string, ReadonlyArray<{ name: string; kind: 'file' | 'dir' }>>>
-}
-
-export function worldOf(on: On, setup: Setup = {}): World {
- const world: World = { runs: [], envs: [], asked: [], ran: [], commands: [] }
-
- // The kit's bottom hook throws for an event no stub answers; a session start needs one.
- on('session.start', () => ({ cwd: '/work' }))
- on('fs.exists', ($, e) => ({ value: setup.hasRoot !== false && e.path.endsWith('scripts/dataforseo_costs.py') }))
- on('fs.list', ($, e) => {
- const entries = setup.listing?.[e.path]
-
- return (entries === undefined ? { deny: 'ENOENT' } : { value: entries.map(entry => ({ ...entry, size: 0 })) }) as never
- })
-
- on('process.run', ($, e) => {
- const args = e.argv.slice(1)
- const script = (args[0] ?? '').split('/').at(-1) ?? ''
- const sub = args[1] ?? ''
-
- world.runs.push([script, ...args.slice(1)].join(' '))
- world.envs.push(e.init?.env ?? {})
-
- const reply = setup.scripts?.[sub]
-
- if (reply === 'throw') {
- return { deny: 'spawn python3 ENOENT' }
- }
-
- const stdout = reply?.stdout === undefined ? '{}' : typeof reply.stdout === 'string' ? reply.stdout : JSON.stringify(reply.stdout)
-
- return { value: { exitCode: reply?.exitCode ?? 0, stdout, stderr: reply?.stderr ?? '', isStdoutTruncated: false, isStderrTruncated: false } }
- })
-
- on('command.register', ($, e) => {
- world.commands.push(e.name)
-
- return { value: { command: e.name } }
- })
-
- // The dialog `$.ui.ask` raises, and the tool beneath the plugin.
- on('tool.call', ($, e) => {
- if (e.tool === 'AskUserQuestion') {
- const question = e.questions[0]?.question ?? ''
-
- world.asked.push(question)
-
- return setup.answer === null || setup.answer === undefined
- ? { deny: 'dismissed' }
- : { result: { questions: e.questions, answers: { [question]: setup.answer } }, text: setup.answer }
- }
-
- world.ran.push(e.tool)
-
- return setup.toolFails === true ? { isError: true as const, result: 'error', text: 'task failed' } : { result: 'ok', text: 'ok' }
- })
-
- return world
-}
-
-export const SESSION = { surface: 'terminal' as const, isInteractive: true, cwd: '/work' }
-
-export const command = (name: string, args = '') => ({
- command: name,
- args,
- origin: { kind: 'composer' as const },
- presentation: { isFullscreen: false, columns: 120 },
-})
-
-export const APPROVED = { status: 'approved', total_cost_usd: 0.002, today_spend_usd: 1.5, daily_remaining_usd: 8.5 }
-export const NEEDS = { status: 'needs_approval', total_cost_usd: 0.103, today_spend_usd: 1.5, daily_remaining_usd: 8.5, approval_reason: 'warn_endpoint', message: 'm' }
-export const BLOCKED = { status: 'blocked', message: 'Daily limit $10.00 would be exceeded.' }
diff --git a/plugins/seo-cockpit/tests/logic.test.ts b/plugins/seo-cockpit/tests/logic.test.ts
deleted file mode 100644
index 3f1021a..0000000
--- a/plugins/seo-cockpit/tests/logic.test.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { describe, expect, test } from 'claude-code/testing'
-
-import { lastDays, spark, spendText } from '../hooks/lib/format'
-import { classify, mcpParts, merchantEndpoints, segmentsOf } from '../hooks/lib/paid'
-import { candidatesOf, latestVersion, parentOf, runtimeEnvOf } from '../hooks/lib/root'
-import { combine, isUnpriced, parseCheck } from '../hooks/lib/verdict'
-
-describe('classify', () => {
- test('DataForSEO MCP tools are priced by endpoint', () => {
- expect(classify('mcp__dataforseo__serp_organic_live_advanced', undefined)).toEqual({
- kind: 'dataforseo', endpoints: ['serp_organic_live_advanced'], label: 'DataForSEO serp_organic_live_advanced',
- })
- })
-
- test('free DataForSEO reference lookups are not held', () => {
- expect(classify('mcp__dataforseo__serp_locations', undefined)).toBeNull()
- expect(classify('mcp__dataforseo__ai_opt_llm_ment_loc_and_lang', undefined)).toBeNull()
- expect(classify('mcp__dataforseo__ai_optimization_llm_models', undefined)).toBeNull()
- })
-
- test('other paid MCP servers ask, keyed by server', () => {
- expect(classify('mcp__ahrefs__site_explorer', undefined)).toEqual({ kind: 'ask', label: 'Ahrefs (site_explorer)', allowKey: 'mcp:ahrefs' })
- expect(classify('mcp__firecrawl-mcp__scrape', undefined)?.kind).toBe('ask')
- expect(classify('mcp__nanobanana-mcp__generate_image', undefined)?.kind).toBe('ask')
- })
-
- test('free tools and free MCP servers are not held', () => {
- expect(classify('Read', undefined)).toBeNull()
- expect(classify('mcp__github__create_issue', undefined)).toBeNull()
- expect(classify('Bash', 'git status')).toBeNull()
- expect(classify('Bash', 'python3 scripts/pagespeed_check.py https://example.com --json')).toBeNull()
- })
-
- test('paid scripts through Bash are held; ledger bookkeeping alone is not', () => {
- expect(classify('Bash', 'python3 scripts/moz_api.py metrics example.com')?.kind).toBe('ask')
- expect(classify('Bash', '"$R/scripts/claude-seo" run --extension banana generate.py --prompt "x"')?.kind).toBe('ask')
- expect(classify('PowerShell', 'python extensions\\banana\\scripts\\generate.py --prompt x')?.kind).toBe('ask')
- expect(classify('Bash', '"$R/scripts/claude-seo" run dataforseo_costs.py check serp_organic_live_advanced')).toBeNull()
- })
-
- test('a cost check chained in front of a paid script does not hide it', () => {
- expect(classify('Bash', 'python3 dataforseo_costs.py check x && "$R/scripts/claude-seo" run dataforseo_merchant.py search shoes')).toEqual({
- kind: 'dataforseo', endpoints: ['merchant_google_products_search'], label: 'DataForSEO Merchant (merchant_google_products_search)',
- })
- expect(classify('Bash', 'run --extension banana generate.py --prompt x; python3 cost_tracker.py log')?.kind).toBe('ask')
- })
-
- test('the merchant script is priced by subcommand and marketplace', () => {
- expect(merchantEndpoints('dataforseo_merchant.py search shoes')).toEqual(['merchant_google_products_search'])
- expect(merchantEndpoints('dataforseo_merchant.py search shoes --marketplace amazon')).toEqual(['merchant_amazon_products_search'])
- expect(merchantEndpoints('dataforseo_merchant.py sellers shoes')).toEqual(['merchant_google_sellers_search'])
- expect(merchantEndpoints('dataforseo_merchant.py compare shoes')).toEqual(['merchant_google_products_search', 'merchant_amazon_products_search'])
- })
-
- test('paid APIs reached with curl or WebFetch ask', () => {
- expect(classify('Bash', 'curl -s https://api4.seranking.com/sites')?.kind).toBe('ask')
- expect(classify('WebFetch', undefined, 'https://api.tryprofound.com/v1/x')?.kind).toBe('ask')
- expect(classify('WebFetch', undefined, 'https://example.com')).toBeNull()
- })
-
- test('segmentsOf splits a shell line', () => {
- expect(segmentsOf('a && b || c; d | e\nf')).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])
- })
-
- test('mcpParts splits server and tool', () => {
- expect(mcpParts('mcp__plugin_x__do_thing')).toEqual({ server: 'plugin_x', name: 'do_thing' })
- expect(mcpParts('Bash')).toBeNull()
- })
-})
-
-describe('parseCheck', () => {
- test('reads each verdict', () => {
- expect(parseCheck(0, JSON.stringify({ status: 'approved', total_cost_usd: 0.002, today_spend_usd: 1, daily_remaining_usd: 9 })).decision).toBe('approved')
- expect(parseCheck(0, JSON.stringify({ status: 'blocked', message: 'cap' }))).toEqual({ decision: 'blocked', message: 'cap' })
- })
-
- test('an unknown endpoint carries only an estimate', () => {
- const verdict = parseCheck(0, JSON.stringify({ status: 'needs_approval', approval_reason: 'unknown_endpoint', estimated_cost_usd: 0.05 }))
-
- expect(verdict).toEqual({ decision: 'needs_approval', costUsd: 0.05, todayUsd: 0, remainingUsd: null, reason: 'unknown_endpoint', message: '' })
- })
-
- test('anything unreadable is an error, never an approval', () => {
- expect(parseCheck(1, '{"status":"approved"}').decision).toBe('error')
- expect(parseCheck(0, 'not json').decision).toBe('error')
- expect(parseCheck(0, '{"status":"maybe"}').decision).toBe('error')
- expect(parseCheck(0, 'null').decision).toBe('error')
- })
-})
-
-describe('combine', () => {
- const approved = { decision: 'approved' as const, costUsd: 0.02, todayUsd: 1, remainingUsd: 9 }
- const asks = { decision: 'needs_approval' as const, costUsd: 0.02, todayUsd: 1, remainingUsd: 9, reason: 'warn_endpoint', message: 'm' }
-
- test('the strictest verdict wins and costs add up', () => {
- expect(combine([approved, approved])).toEqual({ decision: 'approved', costUsd: 0.04, todayUsd: 1, remainingUsd: 9 })
- expect(combine([approved, asks]).decision).toBe('needs_approval')
- expect(combine([asks, { decision: 'blocked', message: 'cap' }])).toEqual({ decision: 'blocked', message: 'cap' })
- expect(combine([]).decision).toBe('error')
- })
-
- test('an unknown endpoint is unpriced and never logged', () => {
- expect(isUnpriced({ ...asks, reason: 'unknown_endpoint' })).toBe(true)
- expect(isUnpriced(asks)).toBe(false)
- })
-
- test('a ledger error keeps its reason', () => {
- expect(parseCheck(1, '{"status":"error","message":"ledger is corrupt"}')).toEqual({ decision: 'error', message: 'cost check exited 1 (ledger is corrupt)' })
- })
-})
-
-describe('root', () => {
- test('a checkout and an install are both candidates', () => {
- expect(candidatesOf('/repo/claude-seo/plugins/seo-cockpit', '')).toEqual({ fixed: ['/repo/claude-seo'], cacheDir: '/repo/claude-seo/claude-seo', cacheRoot: '/repo' })
- expect(candidatesOf('/c/mkt/seo-cockpit/0.1.0', '/opt/seo/')).toEqual({ fixed: ['/opt/seo', '/c/mkt'], cacheDir: '/c/mkt/claude-seo', cacheRoot: '/c' })
- })
-
- test('the latest version folder wins, numerically', () => {
- expect(latestVersion(['2.4.1', '2.10.0', '2.9.9', 'tmp'])).toBe('2.10.0')
- expect(latestVersion(['tmp'])).toBeNull()
- expect(latestVersion(['2.5.0-rc1', '2.5.0', '2.4.9'])).toBe('2.5.0')
- })
-
- test('runtime.py gets claude-seo\'s own data folder, never the calling plugin\'s', () => {
- expect(runtimeEnvOf('/home/u/.claude/plugins/cache/agricidaniel-claude-seo/claude-seo/2.4.1')).toEqual({
- CLAUDE_PLUGIN_DATA: '/home/u/.claude/plugins/data/claude-seo-agricidaniel-claude-seo',
- CLAUDE_PLUGIN_ROOT: '/home/u/.claude/plugins/cache/agricidaniel-claude-seo/claude-seo/2.4.1',
- })
- // A checkout: clear both, so runtime.py uses the checkout's own environment.
- expect(runtimeEnvOf('/home/u/Desktop/Skills/Public/claude-seo')).toEqual({ CLAUDE_PLUGIN_DATA: '', CLAUDE_PLUGIN_ROOT: '' })
- })
-
- test('parentOf trims trailing slashes', () => {
- expect(parentOf('/a/b/')).toBe('/a')
- })
-})
-
-describe('format', () => {
- test('spark scales to the largest value and leaves zero days blank', () => {
- expect(spark([0, 1, 2, 4])).toBe(' ▂▄█')
- expect(spark([0, 0])).toBe(' ')
- })
-
- test('lastDays counts back from today', () => {
- expect(lastDays('2026-10-03', 3)).toEqual(['2026-10-01', '2026-10-02', '2026-10-03'])
- })
-
- test('spendText reports today, the week and the month', () => {
- const text = spendText(
- { date: '2026-10-03', total_usd: 0.5, daily_limit_usd: 10, remaining_usd: 9.5, calls: 3, by_endpoint: { backlinks_summary: { cost_usd: 0.4, calls: 2 } } },
- // The script's own 30-day window reaches into day 31 (2026-09-03 here); the text keeps to 30 calendar days.
- { daily_totals: { '2026-09-03': { total_usd: 2.5, calls: 17 }, '2026-10-01': { total_usd: 1, calls: 2 }, '2026-10-03': { total_usd: 0.5, calls: 3 } }, grand_total_usd: 4, total_calls: 22 },
- )
-
- expect(text).toContain('today $0.50 of $10.00 cap, 3 calls')
- expect(text).toContain('7 days $1.50')
- expect(text).toContain('30 days $1.50, 5 calls')
- expect(text).toContain('backlinks_summary')
- })
-
- test('a ledger reset row is not counted as a call', () => {
- const text = spendText(
- { date: '2026-10-03', total_usd: 0, daily_limit_usd: 10, remaining_usd: 10, calls: 1, by_endpoint: { _audit_reset: { cost_usd: 0, calls: 1 } } },
- { daily_totals: {}, grand_total_usd: 0, total_calls: 1 },
- )
-
- expect(text).toContain('cap, 0 calls')
- expect(text).not.toContain('_audit_reset')
- })
-})
diff --git a/plugins/seo-cockpit/tests/register.test.ts b/plugins/seo-cockpit/tests/register.test.ts
deleted file mode 100644
index 3b6fb48..0000000
--- a/plugins/seo-cockpit/tests/register.test.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { describe, expect, test } from 'claude-code/testing'
-
-import { APPROVED, BLOCKED, command, NEEDS, SESSION, worldOf } from './fixtures/world'
-
-// MCP tool inputs are typed from the servers connected on the machine that last loaded the mod,
-// so a test naming servers that machine lacks casts its input.
-const SERP = { tool: 'mcp__dataforseo__serp_organic_live_advanced' } as never
-const LLM = { tool: 'mcp__dataforseo__ai_opt_llm_ment_search' } as never
-const AHREFS = { tool: 'mcp__ahrefs__site_explorer' } as never
-
-describe('spend guard', () => {
- test('a free tool passes untouched and runs nothing', async ($, on) => {
- const world = worldOf(on)
-
- await $.tool.call({ tool: 'Read', file_path: '/work/a.md' })
-
- expect(world.ran).toEqual(['Read'])
- expect(world.runs).toEqual([])
- })
-
- test('an approved DataForSEO call runs, is logged, and tells Claude not to log it again', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { stdout: APPROVED }, log: { stdout: { status: 'logged' } } } })
-
- const result = await $.tool.call(SERP)
-
- expect(world.ran).toEqual(['mcp__dataforseo__serp_organic_live_advanced'])
- expect(world.runs).toEqual(['dataforseo_costs.py check serp_organic_live_advanced', 'dataforseo_costs.py log serp_organic_live_advanced 0.002 --note seo-cockpit estimate'])
- expect(world.asked).toEqual([])
- expect(JSON.stringify(result)).toContain('Do not run dataforseo_costs.py log')
- })
-
- test('a blocked call never reaches the tool', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { stdout: BLOCKED } } })
-
- const result = await $.tool.call(SERP)
-
- expect(world.ran).toEqual([])
- expect(result.deny).toContain('Daily limit $10.00')
- })
-
- test('a cost check that fails holds the call', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { exitCode: 1, stdout: '' } } })
-
- const result = await $.tool.call(SERP)
-
- expect(world.ran).toEqual([])
- expect(result.deny).toContain('cost check exited 1')
- })
-
- test('claude-seo missing holds the call and says how to fix it', async ($, on) => {
- const world = worldOf(on, { hasRoot: false })
-
- const result = await $.tool.call(SERP)
-
- expect(world.ran).toEqual([])
- expect(result.deny).toContain('claude-seo folder')
- })
-
- test('a spawn failure is caught and holds the call', async ($, on) => {
- const world = worldOf(on, { scripts: { check: 'throw' } })
-
- const result = await $.tool.call(SERP)
-
- expect(world.ran).toEqual([])
- expect(result.deny).toContain('spend guard failed')
- })
-
- test('a call that needs approval runs once the person approves', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { stdout: NEEDS } }, answer: 'Approve' })
-
- await $.tool.call(LLM)
-
- expect(world.asked.length).toBe(1)
- expect(world.asked[0]).toContain('about $0.10')
- expect(world.ran).toEqual(['mcp__dataforseo__ai_opt_llm_ment_search'])
- })
-
- test('a call that needs approval is held when the dialog is dismissed', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { stdout: NEEDS } }, answer: null })
-
- const result = await $.tool.call(LLM)
-
- expect(world.ran).toEqual([])
- expect(result.deny).toContain('did not approve')
- })
-
- test('"Allow until reload" stops asking about that server', async ($, on) => {
- const world = worldOf(on, { answer: 'Allow until reload' })
-
- await $.tool.call(AHREFS)
- await $.tool.call(AHREFS)
-
- expect(world.asked.length).toBe(1)
- expect(world.ran).toEqual(['mcp__ahrefs__site_explorer', 'mcp__ahrefs__site_explorer'])
- })
-
- test('a call that failed is not logged as spend', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { stdout: APPROVED } }, toolFails: true })
-
- const result = await $.tool.call(SERP)
-
- expect(world.runs).toEqual(['dataforseo_costs.py check serp_organic_live_advanced'])
- expect(JSON.stringify(result)).toContain('did not log')
- })
-
- test('an approved unknown endpoint runs but is not logged at a guessed price', async ($, on) => {
- const world = worldOf(on, {
- scripts: { check: { stdout: { status: 'needs_approval', approval_reason: 'unknown_endpoint', estimated_cost_usd: 0.05, message: 'm' } } },
- answer: 'Approve',
- })
-
- const result = await $.tool.call({ tool: 'mcp__dataforseo__brand_new_endpoint' } as never)
-
- expect(world.asked[0]).toContain('has no listed price')
- expect(world.runs).toEqual(['dataforseo_costs.py check brand_new_endpoint'])
- expect(JSON.stringify(result)).toContain('no price in the cost table')
- })
-
- test('the merchant compare checks both endpoints and logs both', async ($, on) => {
- const world = worldOf(on, { scripts: { check: { stdout: APPROVED }, log: { stdout: { status: 'logged' } } } })
-
- await $.tool.call({ tool: 'Bash', command: 'run dataforseo_merchant.py compare shoes' })
-
- expect(world.runs.filter(run => run.includes(' check '))).toEqual([
- 'dataforseo_costs.py check merchant_google_products_search',
- 'dataforseo_costs.py check merchant_amazon_products_search',
- ])
- expect(world.runs.filter(run => run.includes(' log ')).length).toBe(2)
- })
-
- test('the safe answer is listed first in every question', async ($, on) => {
- const choices: string[][] = []
-
- on('tool.call', { tool: 'AskUserQuestion' }, ($, e, next) => {
- choices.push((e.questions[0]?.options ?? []).map(option => option.label))
-
- return next(e)
- })
- worldOf(on, { scripts: { check: { stdout: NEEDS } }, answer: null })
-
- await $.tool.call(AHREFS)
- await $.tool.call(LLM)
-
- expect(choices.map(list => list[0])).toEqual(['Hold it', 'Hold it'])
- })
-
- test('with the guard off, paid calls pass without a check', { options: { spendGuard: false } }, async ($, on) => {
- const world = worldOf(on)
-
- await $.tool.call(SERP)
-
- expect(world.runs).toEqual([])
- expect(world.ran).toEqual(['mcp__dataforseo__serp_organic_live_advanced'])
- })
-})
-
-describe('google settings', () => {
- test('/config Google settings reach claude-seo\'s scripts, and only them', { options: { googleAccount: 'gcloud', googleApiKey: 'test-key' } }, async ($, on) => {
- const world = worldOf(on, { scripts: { today: { stdout: {} }, summary: { stdout: {} } } })
-
- await $.command.run(command('seo-spend'))
-
- expect(world.envs[0]?.CLAUDE_SEO_GOOGLE_AUTH).toBe('adc')
- expect(world.envs[0]?.GOOGLE_API_KEY).toBe('test-key')
- // A checkout: claude-seo uses its own runtime folder, never this plugin's.
- expect(world.envs[0]?.CLAUDE_PLUGIN_DATA).toBe('')
- })
-
- test('auto leaves claude-seo\'s own order alone', async ($, on) => {
- const world = worldOf(on, { scripts: { today: { stdout: {} }, summary: { stdout: {} } } })
-
- await $.command.run(command('seo-spend'))
-
- expect(world.envs[0]?.CLAUDE_SEO_GOOGLE_AUTH).toBeUndefined()
- expect(world.envs[0]?.GOOGLE_API_KEY).toBeUndefined()
- })
-})
-
-describe('commands', () => {
- test('the start registers all three commands', async ($, on) => {
- const world = worldOf(on)
-
- await $.session.start(SESSION)
-
- expect(world.commands.sort()).toEqual(['seo-cockpit', 'seo-doctor', 'seo-spend'])
- })
-
- test('/seo-spend answers from the ledger without a turn', async ($, on) => {
- worldOf(on, {
- scripts: {
- today: { stdout: { date: '2026-10-03', total_usd: 0.25, daily_limit_usd: 10, remaining_usd: 9.75, calls: 5, by_endpoint: {} } },
- summary: { stdout: { daily_totals: { '2026-10-03': { total_usd: 0.25 } }, grand_total_usd: 0.25, total_calls: 5 } },
- },
- })
-
- const result = await $.command.run(command('seo-spend'))
-
- expect(result.text).toContain('today $0.25 of $10.00 cap, 5 calls')
- })
-
- test('/seo-doctor reports setup required with the fix', async ($, on) => {
- worldOf(on, { scripts: { doctor: { exitCode: 3, stdout: { ready: false, mode: 'plugin', plugin_version: '2.4.1', python_version: '3.12', browser_ready: false, reasons: ['venv missing'] } } } })
-
- const result = await $.command.run(command('seo-doctor'))
-
- expect(result.text).toContain('setup required')
- expect(result.text).toContain('venv missing')
- expect(result.text).toContain('guard on')
- })
-})
diff --git a/plugins/seo-cockpit/tsconfig.json b/plugins/seo-cockpit/tsconfig.json
deleted file mode 100644
index 6a6c369..0000000
--- a/plugins/seo-cockpit/tsconfig.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2023", "lib": ["es2023"], "types": [],
- "module": "esnext", "moduleResolution": "bundler",
- "strict": true, "noUncheckedIndexedAccess": true,
- "noEmit": true, "skipLibCheck": true,
- "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
- },
- "include": [".claude-plugin/types", "hooks", "tests"]
-}
diff --git a/tests/test_manifest_consistency.py b/tests/test_manifest_consistency.py
index 3dcb544..3c9c6ac 100644
--- a/tests/test_manifest_consistency.py
+++ b/tests/test_manifest_consistency.py
@@ -466,3 +466,35 @@ def test_claude_md_script_inventory_lists_every_tracked_script():
listed = set(re.findall(r"^\s{4}([a-z0-9_]+\.py)\s", (REPO_ROOT / "CLAUDE.md").read_text(encoding="utf-8"), re.M))
assert tracked - listed == set(), f"unlisted scripts: {sorted(tracked - listed)}"
assert listed - tracked == set(), f"listed but not shipped: {sorted(listed - tracked)}"
+
+
+def test_no_nested_plugin_manifest_inside_the_plugin_root():
+ """Claude Desktop skips a plugin whose folder holds another plugin.json (#344).
+
+ The claude-seo marketplace entry uses ``source: "./"``, so the whole
+ repository is the plugin folder. Only the root manifest may exist.
+ """
+ root_manifest = (REPO_ROOT / ".claude-plugin" / "plugin.json").resolve()
+ nested = [
+ p.relative_to(REPO_ROOT).as_posix()
+ for p in REPO_ROOT.rglob("plugin.json")
+ if p.parent.name == ".claude-plugin"
+ and p.resolve() != root_manifest
+ and not {".git", ".venv", "node_modules"} & set(p.relative_to(REPO_ROOT).parts)
+ ]
+ assert not nested, f"nested plugin manifests break Claude Desktop installs: {nested}"
+
+
+def test_seo_cockpit_installs_from_a_pinned_branch():
+ """seo-cockpit is served from the seo-cockpit branch, pinned to a commit."""
+ mp = json.loads(MARKETPLACE_JSON.read_text(encoding="utf-8"))
+ entries = {e["name"]: e for e in mp["plugins"]}
+ assert mp["plugins"][0]["name"] == "claude-seo"
+ assert mp["plugins"][0]["source"] == "./"
+ source = entries["seo-cockpit"]["source"]
+ assert isinstance(source, dict), "seo-cockpit must not be a relative path inside the plugin root"
+ assert source["source"] == "git-subdir"
+ assert source["url"] == "AgriciDaniel/claude-seo"
+ assert source["path"] == "plugins/seo-cockpit"
+ assert source["ref"] == "seo-cockpit"
+ assert re.fullmatch(r"[0-9a-f]{40}", source["sha"]), source.get("sha")