Open-source SEO, GEO, and marketing skills for AI agents.
feat: add SEO business context caching to seo-analysis
Tongd20480468a12
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a66428b7..56259e50 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).---+## [0.9.3] — 2026-04-07++### Added+- **SEO business context** (`seo/shared/business-context.md`) — persistent per-domain business profile for SEO skills. Caches business name, summary, industry, primary goal, target audience, locations, brand terms, competitors, and key topics at `~/.toprank/business-context/<domain>.json`. Fresh for 90 days; auto-refreshes when stale.+- **`seo-analysis` Phase 3.8** — business context generation after GSC data is collected. First run asks 3 targeted questions and infers the rest from GSC + homepage. Subsequent runs are silent (cache load only).+- **`seo-analysis` Phase 2 fast-path** — brand terms are loaded from business context cache when available, skipping the manual question entirely.+- **Phase 6 report Business Profile section** — report now opens with a business context block (name, goal, audience, competitors) so all recommendations read as contextual rather than generic.++---+## [0.9.2] — 2026-04-06### Changeddiff --git a/VERSION b/VERSIONindex 2003b639..965065db 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.9.2+0.9.3diff --git a/seo/seo-analysis/SKILL.md b/seo/seo-analysis/SKILL.mdindex 87860097..5c36da7e 100644--- a/seo/seo-analysis/SKILL.md+++ b/seo/seo-analysis/SKILL.md@@ -120,7 +120,13 @@ Use the target URL from Step 0 and the GSC property list from Phase 1 to findthe matching property.### Collect brand terms-Ask: "What's your brand name? Enter one or more comma-separated terms (e.g. `Acme, AcmeCorp, acme.io`) — used to separate branded from non-branded traffic. Press Enter to skip."++First, run the Loading section from `../shared/business-context.md`. This sets `CACHE_STATUS` (one of `fresh_loaded`, `stale`, or `not_found`).++**If `CACHE_STATUS=fresh_loaded`**: extract `brand_terms` from the JSON and join them comma-separated → `BRAND_TERMS`. Skip asking the user. Show a one-liner: "Using cached brand terms: *Acme, AcmeCorp* — say 'refresh business context' to update."++**If `CACHE_STATUS=stale` or `not_found`**: ask the user:+> "What's your brand name? Enter one or more comma-separated terms (e.g. `Acme, AcmeCorp, acme.io`) — used to separate branded from non-branded traffic. Press Enter to skip."Store the response as `BRAND_TERMS`. If skipped, leave empty — the script handles it gracefully.@@ -375,13 +381,11 @@ Personas are cached at `~/.toprank/personas/` keyed by domain hostname. Checkwhether a persona file already exists:```bash-DOMAIN=$(echo "<target-url>" | python3 -c "import sys; from urllib.parse import urlparse; print(urlparse(sys.stdin.read().strip()).netloc.replace('www.',''))")+DOMAIN=$(python3 -c "import sys; from urllib.parse import urlparse; print(urlparse(sys.argv[1]).netloc.lstrip('www.'))" "$TARGET_URL")PERSONA_FILE="$HOME/.toprank/personas/$DOMAIN.json"[ -f "$PERSONA_FILE" ] && echo "FOUND" && cat "$PERSONA_FILE" || echo "NOT_FOUND"```-Replace `<target-url>` with the actual target URL from Step 0.-**If found and `saved_at` is less than 90 days old**: Show a one-line summary ofeach persona and continue. No confirmation pause needed — the user alreadyapproved these. If the user proactively says "refresh personas" at any point,@@ -488,6 +492,24 @@ audit with GSC access for better persona accuracy.---+## Phase 3.8 — Business Context++Read and follow `../shared/business-context.md`.++By this point you have GSC data (Phase 3) and homepage content — the two inputs needed to infer business facts before asking the user anything. The goal is to ask as few questions as possible while generating a complete, useful profile.++Branch on `CACHE_STATUS` from Phase 2:++**`fresh_loaded`**: business context is already in memory. No action needed — proceed to Phase 4.++**`not_found`**: run the Generation flow from `../shared/business-context.md`. Seed `brand_terms` with `$BRAND_TERMS` from Phase 2 if the user provided them; supplement with additional brand signals inferred from GSC queries.++**`stale`**: run Generation to refresh. `CACHE_STATUS=stale` means the file was loaded — use those values to pre-fill the three questions so the user confirms or corrects rather than re-enters from scratch.++This phase adds ~30 seconds and one exchange with the user on first run. On all subsequent runs it is silent (cache load only). The payoff: Phase 6 recommendations reference the business by name, compare against real competitors, and focus on the primary goal rather than giving generic SEO advice.++---+## Phase 4 — Search Console AnalysisThis is where you earn your keep. Do not just restate the data. Interpret it like@@ -856,6 +878,14 @@ Output a structured report. Use this format exactly:# SEO Analysis Report — [site.com]*Analyzed: [date range] | Data: Google Search Console + URL Inspection + Technical Crawl*+## Business Profile+*(From Phase 3.8 — provides goal and competitive context for all recommendations below)*++**[Business Name]** — [business_summary from context]+- **Primary goal**: [primary_goal]+- **Target audience**: [target_audience]+- **Competitors tracked**: [competitors list, or "none provided"]+## Audience Personas*(From Phase 3.7 — drives all recommendations below)*diff --git a/seo/shared/business-context.md b/seo/shared/business-context.mdnew file mode 100644index 00000000..ca857e47--- /dev/null+++ b/seo/shared/business-context.md@@ -0,0 +1,191 @@+# SEO Business Context++Business context captures stable facts about a business that don't change run-to-run — name, goals, competitors, audience, brand terms. Caching these avoids repeating the same questions on every audit and lets the analysis skip generic observations in favor of recommendations grounded in what this specific business is trying to do.++This is shared logic. Any SEO skill can reference it. The invoking skill controls when it runs. Assumes `preamble.md` has already run (GSC auth and `$SKILL_SCRIPTS` are set). Requires `$TARGET_URL` from Step 0.++---++## Cache location++```bash+DOMAIN=$(python3 -c "import sys; from urllib.parse import urlparse; print(urlparse(sys.argv[1]).netloc.lstrip('www.'))" "$TARGET_URL")+BC_FILE="$HOME/.toprank/business-context/$DOMAIN.json"+```++---++## Loading++Check whether a fresh cache exists and emit a status tag the invoking skill can branch on:++```bash+mkdir -p "$HOME/.toprank/business-context"+if [ -f "$BC_FILE" ]; then+ AGE_DAYS=$(python3 -c "+import json, sys+from datetime import datetime, timezone+data = json.load(open(sys.argv[1]))+gen = datetime.fromisoformat(data.get('generated_at', '1970-01-01T00:00:00+00:00'))+print((datetime.now(timezone.utc) - gen.astimezone(timezone.utc)).days)+" "$BC_FILE")+ cat "$BC_FILE"+ [ "$AGE_DAYS" -lt 90 ] && echo "CACHE_STATUS=fresh_loaded" || echo "CACHE_STATUS=stale"+else+ echo "CACHE_STATUS=not_found"+fi+```++**`CACHE_STATUS=fresh_loaded`**: profile is current. Extract `brand_terms` as a comma-joined string → `$BC_BRAND_TERMS`. Tell the user:+> "Using cached business profile for **$DOMAIN** (saved $AGE_DAYS days ago) — say *'refresh business context'* to update it."++Skip the brand-terms question in Phase 2.++**`CACHE_STATUS=stale`**: cache exists but is over 90 days old. Load the stale data as a pre-fill for questions in Generation below. Tell the user:+> "Your business profile for **$DOMAIN** is over 90 days old — I'll refresh it after collecting your GSC data."++**`CACHE_STATUS=not_found`**: no cache. Proceed to Generation after Phase 3.++---++## Generation (after Phase 3 GSC data is available)++At this point you have GSC data and homepage content. Infer as much as possible first so questions are as few as possible.++### Step 1 — Infer from data you already have++From GSC + homepage, extract:+- **Candidate brand terms**: queries that appear frequently but don't cluster with topical keywords+- **Key topics**: the top 5-8 query clusters by impression volume+- **Primary geographies**: the top 3-5 countries from the country split+- **Business type signals**: presence of `/pricing/`, `/checkout/`, `/shop/`, `/blog/`, `/locations/` in top page paths+- **Business summary clues**: the homepage `<title>` and `<meta description>`++### Step 2 — Ask minimal targeted questions++Ask all three in a single message. Questions 1 and 2 are optional — if the user skips them, fall back to your inferences from Step 1 (note this in the saved `notes` field).++> I'm building a business profile for **$DOMAIN** to make future audit recommendations more specific. Three quick questions — press Enter to skip any and I'll infer from your data:+>+> 1. **Business name and what you do** — one or two sentences. *(e.g., "Acme — project management software for remote engineering teams")*+> 2. **Primary goal of this website** — pick the closest or describe your own:+> `lead generation` · `ecommerce` · `SaaS / subscription` · `local business` · `content / media` · `other`+> 3. **Main competitors** — 2–5 URLs or names *(optional)*++If `CACHE_STATUS=stale`, pre-fill the question with the cached values so the user can confirm or correct rather than re-enter from scratch.++Wait for the user's response before continuing.++### Step 3 — Synthesize and save++Normalize `primary_goal` to a consistent machine-readable form before saving:+```python+# e.g., "SaaS / subscription" → "saas_subscription", "lead generation" → "lead_generation"+raw_goal = user_answer_2.lower().strip()+primary_goal = raw_goal.replace(' / ', '_').replace('/', '_').replace(' ', '_') or "unknown"+```++Then write to cache:++```python+import json, os+from datetime import datetime, timezone++# --- fill from user answers + inferred data ---+domain = "$DOMAIN"+business_name = "<user answer 1, or inferred from homepage title>"+business_summary = "<1-2 sentence distillation>"+industry = "<inferred from homepage + GSC topics>"+primary_goal = "<normalized from user answer 2, or inferred from URL structure>"+target_audience = "<inferred from GSC query patterns + homepage copy>"+target_locations = ["<top countries from GSC country split>"]+brand_terms = ["<name variations from user answer 1 + GSC brand signal queries>"]+competitors = ["<from user answer 3, or []>"]+key_topics = ["<top 5-8 query clusters from GSC>"]+notes = "<note if answers were inferred rather than user-provided>"+# ---------------------------------------------++data = {+ "domain": domain,+ "generated_at": datetime.now(timezone.utc).isoformat(),+ "business_name": business_name,+ "business_summary": business_summary,+ "industry": industry,+ "primary_goal": primary_goal,+ "target_audience": target_audience,+ "target_locations": target_locations,+ "brand_terms": brand_terms,+ "competitors": competitors,+ "key_topics": key_topics,+ "notes": notes,+}++bc_file = os.path.expanduser(f"~/.toprank/business-context/{domain}.json")+os.makedirs(os.path.dirname(bc_file), exist_ok=True)+with open(bc_file, "w") as f:+ json.dump(data, f, indent=2)+print(f"Business context saved to {bc_file}")+```++Output `CACHE_STATUS=fresh_loaded` after saving so downstream phases know context is ready.++Confirm to the user: "Business profile saved for **$DOMAIN** — I'll use this automatically in all future SEO audits."++---++## Using business context in analysis++Once loaded or generated, these values inform every phase that follows:++| Field | Use |+|-------|-----|+| `brand_terms` | Pass to `analyze_gsc.py --brand-terms`; skip the Phase 2 brand-terms question |+| `competitors` | Drive Phase 4.5 keyword gap analysis — compare their rankings to yours |+| `primary_goal` | Focus Phase 6 recommendations — `lead_generation` → landing pages; `ecommerce` → product/category pages; `content_media` → topical authority and freshness |+| `target_audience` | Cross-reference with Phase 3.7 personas — flag tension if personas don't match the stated audience |+| `key_topics` | Anchor content gap recommendations to confirmed topics, not speculative ones |+| `business_summary` | Open Phase 6 report with a one-liner so all recommendations read as contextual, not generic |++---++## Refreshing++If the user says "refresh business context", "update my business profile", or similar:++```bash+rm -f "$BC_FILE"+```++Then re-run Generation. No need to re-run any other phase.++---++## No-GSC fallback++If GSC was unavailable and the audit is technical-only (Phase 5):++- Skip Step 1 (no GSC data to infer from)+- Still ask the three questions in Step 2+- Infer what you can from homepage content alone+- Save the cache with `"notes": "Generated without GSC data — re-run with GSC access for better accuracy"`++---++## Schema reference++```json+{+ "domain": "example.com",+ "generated_at": "2026-04-07T12:00:00+00:00",+ "business_name": "Acme Corp",+ "business_summary": "Project management software for remote engineering teams.",+ "industry": "SaaS / Developer Tools",+ "primary_goal": "lead_generation",+ "target_audience": "Engineering managers at companies with 20-500 employees",+ "target_locations": ["US", "UK", "CA"],+ "brand_terms": ["Acme", "AcmeCorp", "acme.io"],+ "competitors": ["linear.app", "asana.com", "monday.com"],+ "key_topics": ["project management", "sprint planning", "engineering velocity"],+ "notes": ""+}+```