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.3.0 visual cockpit and HTML dashboard
Agrici Daniel82bae28f0c0c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5195c7..a0e5f9b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0(agents running and done, findings written, spend, time), a receipt linewith the health score when an audit finishes, an opt-in economy modethat runs the five Opus agents on Sonnet, and compaction instructions- that keep audit state. Kit tests are written against the+ that keep audit state. 0.3.0 adds `/seo-cockpit`: a pane with six views+ (Search Console, rankings, Core Web Vitals, the audit scorecard, the Maps+ geo-grid, spend) drawn as text charts in the terminal and SVG on the+ desktop, and a self-contained HTML dashboard export that also covers the+ VS Code chat panel, where panes do not draw.+- `seo-maps`: a geo-grid scan now also saves its grid as+ `{business}-maps/geo-grid-{keyword}-{date}.json`, for comparison over+ time and for the seo-cockpit Maps view. 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 03a13c1..3ded05d 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.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",+ "version": "0.3.0",+ "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"},@@ -37,6 +37,18 @@"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": "Search Console property",+ "description": "For the cockpit: sc-domain:example.com or https://example.com/. Leave empty to use claude-seo's default property.",+ "default": ""+ },+ "pageUrl": {+ "type": "string",+ "title": "Page for Core Web Vitals",+ "description": "For the cockpit's Vitals and drift views: a URL or origin. Leave empty to use the Search Console property's site.",+ "default": ""}}}diff --git a/plugins/seo-cockpit/README.md b/plugins/seo-cockpit/README.mdindex 6fc6149..4860f87 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.2.0)+## 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`):@@ -41,10 +41,26 @@ seo audit example.com: score 72/100 | weakest Schema 40, Content 55 | 17 age**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`). A pane with six views of the data claude-seo already collects. Keys 1 to 6 pick a view, `r` loads it, `e` exports HTML, `x` closes. Nothing is fetched until you press `r`, and no view calls a paid API.++| View | Shows | Source |+|---|---|---|+| 1 Search Console | Clicks and impressions per day for 90 days, 28-day KPIs with change against the 28 days before, top queries | `gsc_query.py` |+| 2 Rankings | Average position over time, queries by position band, striking-distance queries (positions 4 to 15), drift issues over time | `gsc_query.py`, `drift_history.py` |+| 3 Vitals | LCP, INP and CLS p75 per CrUX period against Google's good and poor thresholds | `crux_history.py` |+| 4 Audit | Health score, category scores weakest first, critical and high findings, quick wins | newest `*-audit/audit-data.json` |+| 5 Maps | Geo-grid heatmap, share of local voice, average rank | newest `*-maps/geo-grid-*.json` (saved by `/seo maps grid`) |+| 6 Spend | DataForSEO spend per day for 30 days, today by endpoint | `dataforseo_costs.py` |++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, and the last result of each view is kept for the next session.++**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 [export]`: the visual cockpit, or with `export` the HTML dashboard.## Install@@ -65,11 +81,14 @@ Auto-update is off by default for third-party marketplaces. Run `claude plugin u| 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 |+| Search Console property | empty | For the cockpit: `sc-domain:example.com` or `https://example.com/`. Empty uses claude-seo's default property |+| Page for Core Web Vitals | empty | For the Vitals and drift views. Empty uses the property's site |## 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.+- 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.@@ -80,7 +99,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.+- **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.- **Background agents** return at once, so they count as done when started. claude-seo's audit runs its agents in the foreground.## Status@@ -90,7 +110,9 @@ 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)-- 52 end-to-end scenarios run through a stand-in for the hook chain against the real claude-seo scripts and an isolated ledger+- 70 end-to-end scenarios run through a stand-in for the hook chain against the real claude-seo scripts and an isolated ledger (Search Console, CrUX and drift from fixtures, so no Google account was called)+- the 47 pure-logic tests (`logic`, `audit-logic`, `cockpit-logic`), run with a minimal stand-in for the kit's `describe`, `test` and `expect`+- the HTML export rendered in Chromium, light and dark## Development@@ -102,7 +124,3 @@ 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.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/charts.ts b/plugins/seo-cockpit/hooks/lib/charts.tsnew file mode 100644index 0000000..61c0250--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/charts.ts@@ -0,0 +1,258 @@+/**+ * 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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')++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/tabs.ts b/plugins/seo-cockpit/hooks/lib/tabs.tsnew file mode 100644index 0000000..ecc44f3--- /dev/null+++ b/plugins/seo-cockpit/hooks/lib/tabs.ts@@ -0,0 +1,333 @@+/**+ * 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/register.ts b/plugins/seo-cockpit/hooks/register.tsindex b3ca123..4d46131 100644--- a/plugins/seo-cockpit/hooks/register.ts+++ b/plugins/seo-cockpit/hooks/register.ts@@ -1,10 +1,13 @@import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code'import { auditFromPrompt, bandText, compactInstructions, economyModel, isSeoAgent, noteWrite, receiptText, type Audit } from './lib/audit'+import { htmlPage } from './lib/charts'import { doctorText, spendText } from './lib/format'import { classify, type PaidCall } from './lib/paid'import { candidatesOf, joinPath, latestVersion, MARKER } from './lib/root'+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']@@ -24,8 +27,23 @@ type Ctx = {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; models: Partial<Record<TabId, TabModel>> }}+const PANE_ID = 'seo-cockpit'++/** `sc-domain:example.com` or `https://example.com/` as a URL CrUX can read. */+function urlOfSite(site: string): string {+ const domain = /^sc-domain:(.+)$/.exec(site.trim())?.[1]++ return domain !== undefined ? `https://${domain}` : site.trim()+}++const stamp = (): string => new Date().toISOString().slice(0, 16).replace('T', ' ')+const HELD = 'seo-cockpit held this paid call'const ALLOW = 'Allow until reload'@@ -225,10 +243,216 @@ function follow($: EngineInterface, ctx: Ctx, audit: Audit): void {$.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 })++ 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+}++async function readJson($: EngineInterface, path: string): Promise<unknown> {+ try {+ return JSON.parse(await $.fs.read(path))+ } catch {+ return null+ }+}++/** Builds one tab'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 property = ctx.site.trim()+ const propertyArgs = property === '' ? [] : ['--property', property]++ if (tab === 'gsc' || tab === 'rankings') {+ 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 target = ctx.pageUrl || urlOfSite(property)+ const drift = target === '' ? { data: null } : await runtimeJson($, ctx, seoRoot, 'drift_history.py', [target, '--limit', '20'])++ return rankingsModel(byDate.data, byQuery.data, drift.data, property, at)+ }++ if (tab === 'vitals') {+ const target = ctx.pageUrl || urlOfSite(property) || (ctx.audit === null ? '' : `https://${ctx.audit.domain}`)++ if (target === '') {+ return emptyModel(label, 'crux_history.py', at, 'No URL to measure. Set "Search Console property" or "Page for Core Web Vitals" in /config.')+ }++ const crux = await runtimeJson($, ctx, seoRoot, 'crux_history.py', [target, '--json'])++ return crux.error !== null ? emptyModel(label, 'crux_history.py', at, crux.error) : vitalsModel(crux.data, target, at)+ }++ if (tab === 'audit') {+ const path = ctx.audit?.dir != null ? joinPath(ctx.audit.dir, 'audit-data.json') : await newestFile($, '-audit', name => name === 'audit-data.json')++ return auditModel(path === null ? null : await readJson($, path), await shown($, path), 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 a tab into the pane and the cache, redrawing as it goes. */+async function loadTab($: EngineInterface, ctx: Ctx, tab: TabId): Promise<void> {+ ctx.pane.isLoading = true+ $.ui.invalidate('ui.render')++ try {+ const model = await buildTab($, ctx, tab)++ ctx.pane.models[tab] = model+ await $.store.set(`tab:${tab}`, model).catch(() => undefined)+ } finally {+ ctx.pane.isLoading = false+ ctx.pane.model = ctx.pane.models[ctx.pane.tab] ?? null+ $.ui.invalidate('ui.render')+ }+}++/** Shows a tab: its last result (this session or the cache) at once; nothing is fetched until asked. */+async function pickTab($: EngineInterface, ctx: Ctx, tab: TabId): Promise<void> {+ ctx.pane.tab = tab++ if (ctx.pane.models[tab] === undefined) {+ const cached = await $.store.get(`tab:${tab}`).catch(() => undefined)++ if (typeof cached === 'object' && cached !== null && 'heading' in cached) {+ ctx.pane.models[tab] = cached as TabModel+ }+ }++ ctx.pane.model = ctx.pane.models[tab] ?? null+ $.ui.invalidate('ui.render')+}++/** Writes every loaded tab into one self-contained HTML page in the working folder; returns its path. */+async function exportHtml($: EngineInterface, ctx: Ctx, loadAll: boolean): Promise<string> {+ if (loadAll) {+ 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-${stamp().replace(/[: ]/g, '-')}.html`)++ await $.fs.write(path, htmlPage('SEO Cockpit', `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 }> {+ try {+ if (args.trim().toLowerCase() === 'export') {+ return { text: `seo-cockpit: dashboard written to ${await exportHtml($, ctx, true)}` }+ }++ await pickTab($, ctx, ctx.pane.tab)++ const opened = await $.ui.open({ id: PANE_ID, title: 'SEO Cockpit' })++ if (opened.isPlaced) {+ ctx.pane.isOpen = true++ return { text: 'seo-cockpit: pane open. Keys 1 to 6 pick a view, r loads it, e exports HTML, x closes.' }+ }++ // No pane here (the VS Code chat panel, a narrow terminal): the HTML page is the cockpit.+ return { text: `seo-cockpit: no pane on this screen (${opened.reason}). Dashboard written to ${await exportHtml($, ctx, true)}` }+ } catch (error) {+ return { text: `seo-cockpit: ${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: '[export]', immediate: true }).catch(() => undefined),])}@@ -297,6 +521,9 @@ export function register(on: On, options: PluginOptions) {isBandHidden: false,isReceiptShown: false,stopTicker: null,+ site: typeof options.site === 'string' ? options.site : '',+ pageUrl: typeof options.pageUrl === 'string' ? options.pageUrl.trim() : '',+ pane: { tab: 'gsc', model: null, isLoading: false, exported: null, isOpen: false, models: {} },}// ------------------------------------------------------------ spend guard@@ -443,6 +670,40 @@ export function register(on: On, options: PluginOptions) {})})+ // ------------------------------------------------------------------- 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,+ ...('Link' in table && { Link: table.Link }),+ ...('Svg' in table && { Svg: table.Svg }),+ }++ ctx.pane.isOpen = true++ return paneView(kit, ctx.pane, Math.max(30, Math.floor(e.props.bodyColumns) - 2), {+ pick: tab => void pickTab($, ctx, tab).catch(() => undefined),+ refresh: () => void loadTab($, ctx, ctx.pane.tab).catch(() => undefined),+ exportHtml: () => void exportHtml($, ctx, false).catch(() => undefined),+ close: () => void $.ui.close({ id: PANE_ID }).catch(() => undefined),+ })+ })++ on('ui.close', async ($, e, next) => {+ if (e.id === PANE_ID) {+ ctx.pane.isOpen = false+ }++ return next(e)+ })+// --------------------------------------------------------------- commandson('session.start', async ($, e, next) => {@@ -461,4 +722,6 @@ export function register(on: On, options: PluginOptions) {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.tsnew file mode 100644index 0000000..90162a1--- /dev/null+++ b/plugins/seo-cockpit/hooks/views/pane.ts@@ -0,0 +1,142 @@+/**+ * The cockpit pane as an element tree. Pure: register.ts hands in the+ * surface's element constructors and the actions; nothing here touches `$`.+ *+ * Every surface gets text charts (block characters and colored bars). Where+ * the surface draws `Svg` (desktop, and VS Code per the 2.1.288 typings), the+ * charts are drawn as SVG instead.+ */++import type { Elements, RenderElement } from 'claude-code'++import { barRow, endsOf, rankColor, sparkRow, svgOf, type Chart } from '../lib/charts'+import { TABS, type TabId, type TabModel } from '../lib/tabs'++export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & Partial<Pick<Elements['terminal'], 'Link'>> & { Svg?: Elements['desktop']['Svg'] }++export type PaneState = {+ tab: TabId+ model: TabModel | null+ isLoading: boolean+ /** The last HTML export, as a file path. */+ exported: string | null+}++export type PaneActions = {+ pick: (tab: TabId) => void+ refresh: () => void+ exportHtml: () => void+ close: () => 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)] }))]+}++/** The whole pane: tab buttons, the tab's content, and the actions. */+export function paneView(kit: Kit, state: PaneState, columns: number, actions: PaneActions): RenderElement {+ const { Box, Text, Button } = kit+ const tabs = Box({+ flexDirection: 'row',+ columnGap: 1,+ children: TABS.map(tab => Button({ key: `tab-${tab.id}`, label: `${tab.id === state.tab ? '▸' : ''}${tab.key} ${tab.label}`, hotkey: tab.key, plain: true, onPress: () => actions.pick(tab.id) })),+ })+ const body: RenderElement[] = []+ const model = state.model++ if (state.isLoading) {+ body.push(Text({ dimColor: true, children: ['Loading from claude-seo...'] }))+ } else if (model === null) {+ body.push(Text({ dimColor: true, children: ['Press r to load this view. Nothing is fetched until you ask.'] }))+ } else {+ body.push(Text({ bold: true, children: [model.heading] }), Text({ dimColor: true, children: [cut(`${model.source} · fetched ${model.fetchedAt}`, columns * 2)] }))++ if (model.error !== null) {+ body.push(Text({ color: '#dc2626', children: [cut(model.error, columns * 3)] }))+ }++ if (model.kpis.length > 0) {+ body.push(Box({ flexDirection: 'row', columnGap: 3, children: model.kpis.map(kpi => 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 footer: RenderElement[] = [+ Button({ key: 'refresh', label: 'r Refresh', hotkey: 'r', plain: true, onPress: actions.refresh }),+ Button({ key: 'export', label: 'e Export HTML', hotkey: 'e', plain: true, onPress: actions.exportHtml }),+ Button({ key: 'close', label: 'x Close', hotkey: 'x', plain: true, onPress: actions.close }),+ ]++ if (state.exported !== null) {+ footer.push(kit.Link !== undefined ? kit.Link({ href: `file://${encodeURI(state.exported)}`, label: 'open export' }) : Text({ dimColor: true, children: [state.exported] }))+ }++ return Box({ flexDirection: 'column', rowGap: 0, children: [tabs, Box({ flexDirection: 'column', marginTop: 1, children: body }), Box({ flexDirection: 'row', columnGap: 2, marginTop: 1, children: footer })] })+}diff --git a/plugins/seo-cockpit/tests/cockpit-logic.test.ts b/plugins/seo-cockpit/tests/cockpit-logic.test.tsnew file mode 100644index 0000000..adf3432--- /dev/null+++ b/plugins/seo-cockpit/tests/cockpit-logic.test.ts@@ -0,0 +1,109 @@+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('<b>x</b>')+ 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.tsnew file mode 100644index 0000000..378e3d5--- /dev/null+++ b/plugins/seo-cockpit/tests/cockpit.test.ts@@ -0,0 +1,49 @@+import { describe, expect, test } from 'claude-code/testing'++import { command, worldOf } from './fixtures/world'++const PANE = { plugin: 'seo-cockpit', component: 'Pane' as const, requestId: 'seo-cockpit', viewport: { columns: 160, rows: 50 }, props: { title: 'SEO Cockpit', isFocused: true, bodyColumns: 110, placement: 'dock' as const, scroll: { offset: 0, bodyRows: 40 }, view: {} } }++describe('cockpit', () => {+ test('/seo-cockpit opens the pane, which fetches nothing until asked', async ($, on) => {+ const world = worldOf(on)+ const opened: string[] = []++ on('ui.open', ($, e) => {+ opened.push(e.id)++ return { value: { isPlaced: true } } as never+ })+ on('store.get', () => ({ value: undefined }))+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine'] }) as never)++ const result = await $.command.run(command('seo-cockpit'))+ const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })++ expect(opened).toEqual(['seo-cockpit'])+ expect(result.text).toContain('pane open')+ expect(await ui.find({ type: 'Text', text: /Press r to load/ })).toBeDefined()+ expect(world.runs).toEqual([])+ })++ 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('fs.list', () => ({ value: [] }))+ 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$/)+ })+})diff --git a/plugins/seo-cockpit/tests/logic.test.ts b/plugins/seo-cockpit/tests/logic.test.tsindex 61a2a7a..87fde96 100644--- a/plugins/seo-cockpit/tests/logic.test.ts+++ b/plugins/seo-cockpit/tests/logic.test.ts@@ -139,12 +139,13 @@ describe('format', () => {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 },+ // 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 $4.00, 20 calls')+ expect(text).toContain('30 days $1.50, 5 calls')expect(text).toContain('backlinks_summary')})diff --git a/plugins/seo-cockpit/tests/register.test.ts b/plugins/seo-cockpit/tests/register.test.tsindex 0e75612..400d9f3 100644--- a/plugins/seo-cockpit/tests/register.test.ts+++ b/plugins/seo-cockpit/tests/register.test.ts@@ -153,12 +153,12 @@ describe('spend guard', () => {})describe('commands', () => {- test('the start registers both commands', async ($, on) => {+ test('the start registers all three commands', async ($, on) => {const world = worldOf(on)await $.session.start(SESSION)- expect(world.commands.sort()).toEqual(['seo-doctor', 'seo-spend'])+ expect(world.commands.sort()).toEqual(['seo-cockpit', 'seo-doctor', 'seo-spend'])})test('/seo-spend answers from the ledger without a turn', async ($, on) => {diff --git a/skills/seo-maps/SKILL.md b/skills/seo-maps/SKILL.mdindex 2cdcb72..8c61de6 100644--- a/skills/seo-maps/SKILL.md+++ b/skills/seo-maps/SKILL.md@@ -84,6 +84,12 @@ variation across a geographic area. Requires DataForSEO.5. Find target business rank at each point6. Calculate SoLV: `(top_3_count / total_points) * 100`7. Render ASCII heatmap in output+8. Save the grid for later comparison and for the seo-cockpit Maps view:+ `{business-slug}-maps/geo-grid-{keyword-slug}-{YYYY-MM-DD}.json` with+ `{"business", "keyword", "location", "date", "size", "radius_km", "solv",+ "ranks": [[...], ...]}`, where `ranks` is row-major from north-west to+ south-east and each cell is the business's rank at that point (an+ integer), or `null` when it is not in the results### Cost Warning (REQUIRED)