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.
feat(seo-cockpit): mods companion with a spend guard and zero-token commands
Agrici Danielba21d0c5fd70
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex b2a47f0..e53846b 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -57,6 +57,24 @@"ai-citation-optimization","synthesis-framework"]+ },+ {+ "name": "seo-cockpit",+ "source": "./plugins/seo-cockpit",+ "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",+ "keywords": [+ "seo",+ "mods",+ "cost-guard",+ "dataforseo",+ "budget"+ ]}]}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 03041f3..688335f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- `plugins/seo-cockpit`: an optional mods companion plugin (Claude Code+ 2.1.287+), listed as a second entry in the marketplace. It holds paid SEO+ API calls against the DataForSEO budget before they run (DataForSEO MCP+ tools and the Merchant script are priced by `dataforseo_costs.py`; Ahrefs,+ Firecrawl, image generation, Moz, Keywords Everywhere, Cloud NLP, the+ Indexing API, and curl or WebFetch calls to SE Ranking and Profound ask+ first), fails closed, logs what it approved, and adds zero-token+ `/seo-spend` and `/seo-doctor` commands. Kit tests are written against the+ 2.1.288 typings but not yet executed: mods are switched off remotely for+ the maintainer's account.++### Changed++- `dataforseo_costs.py check` returns `credentials_in_env` on every result,+ so a budget approval is not read as proof the call can run.++### Fixed++- Schema hook (`hooks/validate-schema.py`): diagnostics went to stdout,+ which Claude Code ignores, so Claude never saw them. Critical errors now+ exit 2 with the errors on stderr (fed back to Claude); warnings exit 0+ with `hookSpecificOutput.additionalContext` JSON, which Claude reads+ without an error notice. Wording no longer claims the edit is blocked: a+ PostToolUse hook runs after the file is written.+- `ai_opt_llm_ment_search` costs about $0.103 per the official response+ example, not $0.05 (`dataforseo_costs.py` and both `cost-tiers.md`).+## [2.4.1] - 2026-09-29Google-currency patch. Every changed fact was re-checked against itsdiff --git a/plugins/seo-cockpit/.claude-plugin/plugin.json b/plugins/seo-cockpit/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..04f8699--- /dev/null+++ b/plugins/seo-cockpit/.claude-plugin/plugin.json@@ -0,0 +1,30 @@+{+ "name": "seo-cockpit",+ "version": "0.1.0",+ "description": "Mods companion for claude-seo: a spend guard on paid SEO APIs and zero-token /seo-spend and /seo-doctor 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+ }+ }+}diff --git a/plugins/seo-cockpit/.gitignore b/plugins/seo-cockpit/.gitignorenew file mode 100644index 0000000..c743e50--- /dev/null+++ b/plugins/seo-cockpit/.gitignore@@ -0,0 +1 @@+.claude-plugin/types/diff --git a/plugins/seo-cockpit/README.md b/plugins/seo-cockpit/README.mdnew file mode 100644index 0000000..07c6a4d--- /dev/null+++ b/plugins/seo-cockpit/README.md@@ -0,0 +1,87 @@+# 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. Mods need Claude Code 2.1.287 or newer; on older builds, install claude-seo alone.++## What it does (0.1.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.++**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.++## 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 |++## 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.+- 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.++## Status++The kit tests in `tests/` are written against the Claude Code 2.1.288 typings but have not yet been executed: mods are switched off remotely for the maintainer's account (`claude plugin test` refuses to run). Verified on 2026-10-03:++- type-check (`tsc`, strict)+- `claude plugin validate --strict`+- the brain's static scan (reach L2, no critical or high flags)+- 34 end-to-end scenarios run through a stand-in for the hook chain against the real claude-seo scripts and an isolated ledger++## 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/`.++## Roadmap++- 0.2.0: an audit progress band (agents running and done, findings written, spend), a receipt when an audit finishes, an economy mode that routes the Opus agents to Sonnet, and compaction that keeps audit state.+- 0.3.0: a visual cockpit pane covering Search Console, rankings and trends, Core Web Vitals, the audit scorecard, the Maps geo-grid, and spend. Charts draw in the terminal and on desktop, with an HTML export for VS Code.diff --git a/plugins/seo-cockpit/hooks/hooks.json b/plugins/seo-cockpit/hooks/hooks.jsonnew file mode 100644index 0000000..9f45101--- /dev/null+++ b/plugins/seo-cockpit/hooks/hooks.json@@ -0,0 +1,3 @@+{+ "modules": ["./register.ts"]+}diff --git a/plugins/seo-cockpit/hooks/lib/format.ts b/plugins/seo-cockpit/hooks/lib/format.tsnew file mode 100644index 0000000..7dee5a8--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/format.ts@@ -0,0 +1,93 @@+/**+ * 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/paid.ts b/plugins/seo-cockpit/hooks/lib/paid.tsnew file mode 100644index 0000000..58a5f2e--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/paid.ts@@ -0,0 +1,149 @@+/**+ * 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.tsnew file mode 100644index 0000000..ed7470b--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/root.ts@@ -0,0 +1,78 @@+/**+ * 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+}diff --git a/plugins/seo-cockpit/hooks/lib/verdict.ts b/plugins/seo-cockpit/hooks/lib/verdict.tsnew file mode 100644index 0000000..c6d9658--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/verdict.ts@@ -0,0 +1,102 @@+/**+ * 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.tsnew file mode 100644index 0000000..f3297d4--- /dev/null+++ b/plugins/seo-cockpit/hooks/register.ts@@ -0,0 +1,295 @@+import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code'++import { doctorText, spendText } from './lib/format'+import { classify, type PaidCall } from './lib/paid'+import { candidatesOf, joinPath, latestVersion, MARKER } from './lib/root'+import { combine, isUnpriced, parseCheck, usd, type Verdict } from './lib/verdict'++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+}++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+}++/** 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 })+}++/** 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)+ // 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}.` }+ }+ }+}++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),+ ])+}++async function spendCommand($: EngineInterface, ctx: Ctx): Promise<{ text: string }> {+ const seoRoot = await findRoot($, ctx)++ if (seoRoot === null) {+ return { text: 'seo-cockpit: 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: `seo-cockpit: the ledger could not be read (${reason}).` }+ }++ return { text: spendText(JSON.parse(today.stdout), JSON.parse(summary.stdout)) }+ } catch (error) {+ return { text: `seo-cockpit: 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: 'seo-cockpit: 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: `seo-cockpit: 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,+ }++ // ------------------------------------------------------------ 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.` },+ )++ // --------------------------------------------------------------- commands++ on('session.start', async ($, e, next) => {+ await registerCommands($)++ 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))+}diff --git a/plugins/seo-cockpit/tests/fixtures/world.ts b/plugins/seo-cockpit/tests/fixtures/world.tsnew file mode 100644index 0000000..7437d30--- /dev/null+++ b/plugins/seo-cockpit/tests/fixtures/world.ts@@ -0,0 +1,94 @@+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[]+ /** 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+}++export function worldOf(on: On, setup: Setup = {}): World {+ const world: World = { runs: [], 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', () => ({ deny: 'ENOENT' }))++ 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(' '))++ 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.tsnew file mode 100644index 0000000..61a2a7a--- /dev/null+++ b/plugins/seo-cockpit/tests/logic.test.ts@@ -0,0 +1,160 @@+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 } 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('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 } } },+ { daily_totals: { '2026-10-01': { total_usd: 1 }, '2026-10-03': { total_usd: 0.5 } }, grand_total_usd: 4, total_calls: 20 },+ )++ expect(text).toContain('today $0.50 of $10.00 cap, 3 calls')+ expect(text).toContain('7 days $1.50')+ expect(text).toContain('30 days $4.00, 20 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.tsnew file mode 100644index 0000000..0e75612--- /dev/null+++ b/plugins/seo-cockpit/tests/register.test.ts@@ -0,0 +1,186 @@+import { describe, expect, test } from 'claude-code/testing'++import { APPROVED, BLOCKED, command, NEEDS, SESSION, worldOf } from './fixtures/world'++const SERP = { tool: 'mcp__dataforseo__serp_organic_live_advanced' as const }+const LLM = { tool: 'mcp__dataforseo__ai_opt_llm_ment_search' as const }+const AHREFS = { tool: 'mcp__ahrefs__site_explorer' as const }++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' })++ 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('commands', () => {+ test('the start registers both commands', async ($, on) => {+ const world = worldOf(on)++ await $.session.start(SESSION)++ expect(world.commands.sort()).toEqual(['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.jsonnew file mode 100644index 0000000..6a6c369--- /dev/null+++ b/plugins/seo-cockpit/tsconfig.json@@ -0,0 +1,10 @@+{+ "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"]+}