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): 0.2.0 audit band, receipt, economy mode, compaction
Agrici Daniel10e8bfad3165
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 688335f..a5195c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Firecrawl, image generation, Moz, Keywords Everywhere, Cloud NLP, theIndexing API, and curl or WebFetch calls to SE Ranking and Profound askfirst), fails closed, logs what it approved, and adds zero-token- `/seo-spend` and `/seo-doctor` commands. Kit tests are written against the+ `/seo-spend` and `/seo-doctor` commands. 0.2.0 adds a live audit band+ (agents running and done, findings written, spend, time), a receipt line+ with the health score when an audit finishes, an opt-in economy mode+ that runs the five Opus agents on Sonnet, and compaction instructions+ that keep audit state. Kit tests are written against the2.1.288 typings but not yet executed: mods are switched off remotely forthe maintainer's account.diff --git a/plugins/seo-cockpit/.claude-plugin/plugin.json b/plugins/seo-cockpit/.claude-plugin/plugin.jsonindex 04f8699..03a13c1 100644--- a/plugins/seo-cockpit/.claude-plugin/plugin.json+++ b/plugins/seo-cockpit/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"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",+ "version": "0.2.0",+ "description": "Mods companion for claude-seo: a spend guard on paid SEO APIs, a live audit band with a receipt, an economy mode, and zero-token /seo-spend and /seo-doctor","author": {"name": "Agrici Daniel"},@@ -25,6 +25,18 @@"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}}}diff --git a/plugins/seo-cockpit/README.md b/plugins/seo-cockpit/README.mdindex 07c6a4d..6fc6149 100644--- a/plugins/seo-cockpit/README.md+++ b/plugins/seo-cockpit/README.md@@ -4,7 +4,7 @@ An optional mods companion for [claude-seo](../../README.md). It runs inside ClaTested 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)+## What it does (0.2.0)**Spend guard.** Before a paid SEO API call runs, seo-cockpit checks it against the claude-seo DataForSEO budget (`scripts/dataforseo_costs.py`):@@ -23,6 +23,24 @@ Shell lines are checked one command at a time, so a cost check chained in frontWhat 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 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 their Agent call returns. 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.+**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.@@ -45,6 +63,8 @@ Auto-update is off by default for third-party marketplaces. Run `claude plugin u| 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 |## What it can and cannot see@@ -60,6 +80,8 @@ Auto-update is off by default for third-party marketplaces. Run `claude plugin u- **`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 draws 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.+- **Background agents** return at once, so they count as done when started. claude-seo's audit runs its agents in the foreground.## Status@@ -68,7 +90,7 @@ The kit tests in `tests/` are written against the Claude Code 2.1.288 typings bu- 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+- 52 end-to-end scenarios run through a stand-in for the hook chain against the real claude-seo scripts and an isolated ledger## Development@@ -83,5 +105,4 @@ Layout: `hooks/register.ts` is the only file that calls `on()`. The rules live i## 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/lib/audit.ts b/plugins/seo-cockpit/hooks/lib/audit.tsnew file mode 100644index 0000000..2a5fc48--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/audit.ts@@ -0,0 +1,191 @@+/**+ * 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 }++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/register.ts b/plugins/seo-cockpit/hooks/register.tsindex f3297d4..b3ca123 100644--- a/plugins/seo-cockpit/hooks/register.ts+++ b/plugins/seo-cockpit/hooks/register.ts@@ -1,5 +1,6 @@import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code'+import { auditFromPrompt, bandText, compactInstructions, economyModel, isSeoAgent, noteWrite, receiptText, type Audit } from './lib/audit'import { doctorText, spendText } from './lib/format'import { classify, type PaidCall } from './lib/paid'import { candidatesOf, joinPath, latestVersion, MARKER } from './lib/root'@@ -15,6 +16,14 @@ type Ctx = {/** 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}const HELD = 'seo-cockpit held this paid call'@@ -118,6 +127,10 @@ async function runAndLog($: EngineInterface, ctx: Ctx, seoRoot: string, checks: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.`@@ -189,6 +202,29 @@ async function guard($: EngineInterface, ctx: Ctx, paid: PaidCall, run: () => Pr}}+/** 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+}++/** Starts following a new audit and shows the band again. */+function follow($: EngineInterface, ctx: Ctx, audit: Audit): void {+ ctx.audit = audit+ ctx.isBandHidden = false+ ctx.isReceiptShown = false+ startTicker($, ctx)+ $.ui.invalidate('ui.render')+}+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),@@ -255,6 +291,12 @@ export function register(on: On, options: PluginOptions) {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,}// ------------------------------------------------------------ spend guard@@ -274,6 +316,133 @@ export function register(on: On, options: PluginOptions) {: { 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) {+ // A finished audit's band stays up until the next prompt.+ ctx.audit = null+ $.ui.invalidate('ui.render')+ }++ return next(e)+ })++ on('agent.spawn', async ($, e, next) => {+ if (!isSeoAgent(e.subagentType)) {+ return next(e)+ }++ if (ctx.audit !== null && ctx.audit.finishMs === null) {+ ctx.audit = { ...ctx.audit, agents: { ...ctx.audit.agents, [e.tool_use_id]: { type: e.subagentType, state: 'running', startMs: Date.now() } } }+ $.ui.invalidate('ui.render')+ }++ const model = ctx.isEconomy && e.model === undefined ? economyModel(e.subagentType) : null++ return next(model === null ? e : { ...e, model })+ })++ // A foreground Agent call returns when its subagent is done.+ on('tool.call', { tool: ['Agent', /^Task$/] }, async ($, e, next) => {+ const result = await next(e)+ const run = ctx.audit?.agents[e.tool_use_id]++ if (ctx.audit !== null && run !== undefined) {+ const state = result.deny !== undefined || result.isError === true ? 'failed' : 'done'++ ctx.audit = { ...ctx.audit, agents: { ...ctx.audit.agents, [e.tool_use_id]: { ...run, state, endMs: Date.now() } } }+ $.ui.invalidate('ui.render')+ }++ 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 {+ ctx.audit = after+ $.ui.invalidate('ui.render')+ }+ }+ }++ return result+ })++ on('turn.complete', async ($, e, next) => {+ const result = await next(e)+ const audit = ctx.audit++ // The receipt goes under the main answer, once, when the audit's data file exists.+ if (e.agentId !== undefined || audit === null || audit.finishMs !== null || audit.score === null || ctx.isReceiptShown) {+ return result+ }++ const now = Date.now()++ ctx.audit = { ...audit, finishMs: now }+ ctx.isReceiptShown = true+ stopTicker(ctx)+ $.ui.invalidate('ui.render')++ const receipt = receiptText(audit, now)++ return { ...result, text: result.text ? `${result.text}\n${receipt}` : receipt }+ })++ on('session.compact', async ($, e, next) => {+ const audit = ctx.audit++ if (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)++ return Box({+ flexDirection: 'row',+ columnGap: 1,+ children: [+ Text({ color: audit.finishMs === null ? 'cyan' : 'green', children: [bandText(audit, Date.now(), columns, ctx.isEconomy)] }),+ Button({+ key: 'seo-cockpit-hide',+ label: 'hide',+ plain: true,+ onPress: () => {+ ctx.isBandHidden = true+ $.ui.invalidate('ui.render')+ },+ }),+ ],+ })+ })+// --------------------------------------------------------------- commandson('session.start', async ($, e, next) => {diff --git a/plugins/seo-cockpit/tests/audit-logic.test.ts b/plugins/seo-cockpit/tests/audit-logic.test.tsnew file mode 100644index 0000000..db69d2a--- /dev/null+++ b/plugins/seo-cockpit/tests/audit-logic.test.ts@@ -0,0 +1,88 @@+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.tsnew file mode 100644index 0000000..272a3db--- /dev/null+++ b/plugins/seo-cockpit/tests/audit.test.ts@@ -0,0 +1,118 @@+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', text: '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' }+ })+ on('turn.complete', () => ({ text: '' }))+ on('session.compact', ($, e) => {+ seen.instructions.push(e.instructions)++ return { messages: [] } as never+ })+ 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')+ 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('')+ })++ 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'))+ await $.session.compact({ trigger: 'auto', messages: [] } as never)++ 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])+ })+})