Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(web-analytics): score content opportunities from citation gaps (#108121)

Jordan Mryyand6f1fe55682d
diff --git a/products/web_analytics/backend/content_autopilot/opportunities.py b/products/web_analytics/backend/content_autopilot/opportunities.py
new file mode 100644
index 000000000000..edabafb41ef2
--- /dev/null
+++ b/products/web_analytics/backend/content_autopilot/opportunities.py
@@ -0,0 +1,383 @@
+import math
+import datetime as dt
+from typing import Any
+from urllib.parse import urlparse
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team import Team
+
+from products.aeo.backend.facade.api import list_citation_gaps
+from products.aeo.backend.facade.contracts import CitationGap
+from products.web_analytics.backend.content_autopilot.lifecycle import (
+ ACTIVE_RUN_STATUSES,
+ ContentAutopilotLifecycleError,
+ canonical_team_id,
+ lock_profile,
+ start_run,
+)
+from products.web_analytics.backend.content_autopilot.site_discovery import read_sitemap_urls, site_host
+from products.web_analytics.backend.models import (
+ ContentAutopilotOpportunity,
+ ContentAutopilotProposal,
+ ContentAutopilotRun,
+ ContentAutopilotSiteProfile,
+)
+
+OPPORTUNITY_LOOKBACK_DAYS = 14
+MAX_DRAFTS_PER_RUN = 5
+SITEMAP_CACHE_SECONDS = 6 * 60 * 60
+FULL_CONFIDENCE_CHECKS = 9
+FULL_TRAFFIC_SIGNAL = 100
+SITE_PAGE_VIEWS_LOOKBACK_DAYS = 30
+MAX_ANSWER_CHARS_IN_GAP = 4000
+
+ENGINE_LABELS = {
+ "claude-web-search": "Claude",
+ "openai-web-search": "ChatGPT",
+ "exa-answer": "Exa",
+}
+
+
+def engine_label(engine: str) -> str:
+ return ENGINE_LABELS.get(engine, engine)
+
+
+def canonical_site_url(url: str, *, origin: str, page_urls: list[str], boundaries: list[str]) -> str | None:
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ path = parsed.path.rstrip("/") or "/"
+ host = site_host(url)
+ if not host or host != site_host(origin) or path == "/":
+ return None
+ if not page_urls:
+ within = any(path.startswith(boundary.rstrip("/") or "/") for boundary in boundaries or ["/"])
+ return f"{origin.rstrip('/')}{path}" if within else None
+ return next((page for page in page_urls if (urlparse(page).path.rstrip("/") or "/") == path), None)
+
+
+def score_gap(gap: CitationGap, traffic: dict[str, int] | None = None) -> float:
+ severity = 1 - gap.citation_rate
+ agreement = len(gap.engines_not_citing) / len(gap.engines) if gap.engines else 0.0
+ mentioned_not_cited = max(0, gap.mentioned_checks - gap.cited_checks) / gap.checks if gap.checks else 0.0
+ ai_traffic = (traffic or {}).get("ai_visitors", 0) + (traffic or {}).get("ai_crawls", 0) / 10
+ traffic_signal = min(1.0, math.log1p(ai_traffic) / math.log1p(FULL_TRAFFIC_SIGNAL))
+ confidence = min(1.0, gap.checks / FULL_CONFIDENCE_CHECKS)
+ priority = 0.45 * severity + 0.25 * agreement + 0.2 * mentioned_not_cited + 0.1 * traffic_signal
+ return round(priority * (0.5 + 0.5 * confidence), 4)
+
+
+def site_page_urls(profile: ContentAutopilotSiteProfile) -> list[str]:
+ cache_key = f"content_autopilot:sitemap:{profile.id}:{profile.updated_at.timestamp()}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+ urls = read_sitemap_urls(list(profile.source_urls), origin=profile.domain)
+ boundaries = [str(boundary) for boundary in profile.content_boundaries] or ["/"]
+ urls = [url for url in urls if any(urlparse(url).path.startswith(boundary) for boundary in boundaries)]
+ cache.set(cache_key, urls, SITEMAP_CACHE_SECONDS)
+ return urls
+
+
+def page_ai_traffic(team: Team, origin: str, paths: list[str], *, include_hostless: bool) -> dict[str, dict[str, int]]:
+ if not paths:
+ return {}
+ query = parse_select(
+ """
+ SELECT
+ coalesce(nullIf(trimRight(properties.$pathname, '/'), ''), '/') AS path,
+ countIf(`$virt_is_bot` = true AND `$virt_traffic_category` IN ('ai_crawler', 'ai_assistant', 'ai_search')) AS ai_crawls,
+ uniqIf(person_id, event = '$pageview' AND NOT `$virt_is_bot` AND session.$channel_type = 'AI') AS ai_visitors
+ FROM events
+ WHERE timestamp >= now() - toIntervalDay({lookback_days})
+ AND event IN ('$pageview', '$http_log')
+ AND properties.$pathname IN {paths}
+ AND lower(coalesce(properties.$host, '')) IN {hosts}
+ GROUP BY path
+ """,
+ placeholders={
+ "lookback_days": ast.Constant(value=OPPORTUNITY_LOOKBACK_DAYS),
+ "paths": ast.Tuple(
+ exprs=[ast.Constant(value=variant) for path in paths for variant in {path, f"{path.rstrip('/')}/"}]
+ ),
+ "hosts": ast.Tuple(
+ exprs=[ast.Constant(value=host) for host in _site_hosts(origin, include_unknown=include_hostless)]
+ ),
+ },
+ )
+ with tags_context(
+ product=Product.WEB_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk, org_id=team.organization_id
+ ):
+ response = execute_hogql_query(query=query, team=team, query_type="content_autopilot_page_ai_traffic")
+ return {
+ str(row[0]): {"ai_crawls": int(row[1] or 0), "ai_visitors": int(row[2] or 0)} for row in response.results or []
+ }
+
+
+def _site_hosts(origin: str, *, include_unknown: bool = False) -> list[str]:
+ host = site_host(origin)
+ return [host, f"www.{host}", *([""] if include_unknown else [])]
+
+
+def _is_aeo_target(origin: str) -> bool:
+ return site_host(origin) in {site_host(f"https://{domain}") for domain in settings.AEO_TARGET_DOMAINS}
+
+
+def _being_drafted(opportunity: ContentAutopilotOpportunity) -> bool:
+ return (
+ opportunity.status == ContentAutopilotOpportunity.Status.QUEUED
+ and opportunity.run is not None
+ and opportunity.run.run_status in ACTIVE_RUN_STATUSES
+ )
+
+
+def _page_path(url: str) -> str:
+ return urlparse(url).path.rstrip("/") or "/"
+
+
+def _most_viewed_paths(team: Team, origin: str, limit: int) -> list[str]:
+ query = parse_select(
+ """
+ SELECT properties.$pathname AS path, count() AS views
+ FROM events
+ WHERE event = '$pageview'
+ AND timestamp >= now() - toIntervalDay({lookback_days})
+ AND lower(properties.$host) IN {hosts}
+ GROUP BY path
+ ORDER BY views DESC
+ LIMIT {limit}
+ """,
+ placeholders={
+ "lookback_days": ast.Constant(value=SITE_PAGE_VIEWS_LOOKBACK_DAYS),
+ "hosts": ast.Tuple(exprs=[ast.Constant(value=host) for host in _site_hosts(origin)]),
+ "limit": ast.Constant(value=limit),
+ },
+ )
+ with tags_context(
+ product=Product.WEB_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk, org_id=team.organization_id
+ ):
+ response = execute_hogql_query(query=query, team=team, query_type="content_autopilot_most_viewed_pages")
+ return [_page_path(str(row[0])) for row in response.results or [] if row[0]]
+
+
+def top_site_pages(team: Team, *, origin: str, page_urls: list[str], limit: int) -> list[str]:
+ by_path: dict[str, str] = {}
+ for url in page_urls:
+ by_path.setdefault(_page_path(url), url)
+ try:
+ viewed = [by_path[path] for path in _most_viewed_paths(team, origin, limit * 10) if path in by_path]
+ except Exception as error:
+ capture_exception(error)
+ viewed = []
+ shallow = [url for url in page_urls if len([part for part in urlparse(url).path.split("/") if part]) <= 1]
+ return list(dict.fromkeys([*viewed, *shallow, *page_urls]))[:limit]
+
+
+def _join_labels(labels: list[str]) -> str:
+ if len(labels) <= 1:
+ return "".join(labels)
+ return f"{', '.join(labels[:-1])} and {labels[-1]}"
+
+
+def _evidence(gap: CitationGap, target_url: str, traffic: dict[str, int] | None) -> list[dict[str, str]]:
+ missing = [engine_label(engine) for engine in gap.engines_not_citing]
+ uncited = gap.checks - gap.cited_checks
+ explanation = (
+ f"{_join_labels(missing)} answered without citing the site in {uncited} of {gap.checks} "
+ f"{'check' if gap.checks == 1 else 'checks'} over the last {OPPORTUNITY_LOOKBACK_DAYS} days."
+ )
+ if gap.competitor_domains:
+ explanation += f" They cited {_join_labels(list(gap.competitor_domains[:3]))} instead."
+ evidence = [{"opportunity_kind": "ai_visibility_gap", "explanation": explanation, "query": gap.prompt_text}]
+ if target_url:
+ page_explanation = "AI assistants cited this page in some of their answers to this question."
+ if traffic is not None:
+ page_explanation += (
+ f" In the last {OPPORTUNITY_LOOKBACK_DAYS} days AI crawlers fetched it {traffic['ai_crawls']} times "
+ f"and {traffic['ai_visitors']} visitors arrived from AI assistants."
+ )
+ evidence.append(
+ {"opportunity_kind": "ai_visibility_gap", "explanation": page_explanation, "page_url": target_url}
+ )
+ return evidence
+
+
+def _gap_payload(gap: CitationGap) -> dict[str, Any]:
+ return {
+ "checks": gap.checks,
+ "cited_checks": gap.cited_checks,
+ "mentioned_checks": gap.mentioned_checks,
+ "citation_rate": gap.citation_rate,
+ "engines": list(gap.engines),
+ "engines_not_citing": list(gap.engines_not_citing),
+ "competitor_urls": list(gap.competitor_urls),
+ "competitor_domains": list(gap.competitor_domains),
+ "engine_search_queries": list(gap.engine_search_queries),
+ "our_cited_urls": list(gap.our_cited_urls),
+ "latest_answers": [
+ {
+ "engine": answer.engine,
+ "answer_text": answer.answer_text[:MAX_ANSWER_CHARS_IN_GAP],
+ "checked_at": answer.checked_at.isoformat(),
+ }
+ for answer in gap.latest_answers
+ ],
+ "last_checked_at": gap.last_checked_at.isoformat(),
+ }
+
+
+def refresh_opportunities(
+ *, team: Team, profile_id: str, page_urls: list[str] | None = None
+) -> list[ContentAutopilotOpportunity]:
+ team_id = canonical_team_id(team)
+ try:
+ profile = ContentAutopilotSiteProfile.objects.for_team(team_id, canonical=True).get(
+ id=profile_id, deleted=False
+ )
+ except ContentAutopilotSiteProfile.DoesNotExist as error:
+ raise ContentAutopilotLifecycleError("That site could not be found.") from error
+ gaps = (
+ list_citation_gaps(team_id, since=timezone.now() - dt.timedelta(days=OPPORTUNITY_LOOKBACK_DAYS))
+ if _is_aeo_target(profile.domain)
+ else []
+ )
+ boundaries = [str(boundary) for boundary in profile.content_boundaries]
+ if page_urls is None:
+ page_urls = site_page_urls(profile) if gaps else []
+
+ targets: dict[str, str] = {}
+ for gap in gaps:
+ cited = (
+ canonical_site_url(url, origin=profile.domain, page_urls=page_urls, boundaries=boundaries)
+ for url in gap.our_cited_urls
+ )
+ targets[gap.prompt_hash] = next((url for url in cited if url), "")
+
+ paths = sorted({_page_path(url) for url in targets.values() if url})
+ only_site = not (
+ ContentAutopilotSiteProfile.objects.for_team(team_id, canonical=True)
+ .filter(deleted=False)
+ .exclude(id=profile.id)
+ .exists()
+ )
+ traffic_by_path = page_ai_traffic(team, profile.domain, paths, include_hostless=only_site)
+
+ now = timezone.now()
+ with transaction.atomic():
+ existing = {
+ opportunity.cluster_key: opportunity
+ for opportunity in ContentAutopilotOpportunity.objects.for_team(team_id, canonical=True)
+ .select_related("run")
+ .select_for_update(of=("self",))
+ .filter(profile=profile)
+ }
+ for gap in gaps:
+ target_url = targets[gap.prompt_hash]
+ traffic = traffic_by_path.get(_page_path(target_url))
+ fields = {
+ "aeo_prompt_id": gap.prompt_id,
+ "title": gap.prompt_text,
+ "score": score_gap(gap, traffic),
+ "recommended_type": (
+ ContentAutopilotProposal.ProposalType.PAGE_IMPROVEMENT
+ if target_url
+ else ContentAutopilotProposal.ProposalType.NEW_CONTENT
+ ),
+ "target_url": target_url,
+ "evidence": _evidence(gap, target_url, traffic),
+ "gap": _gap_payload(gap),
+ "last_refreshed_at": now,
+ }
+ opportunity = existing.get(gap.prompt_hash)
+ if opportunity is None:
+ ContentAutopilotOpportunity.objects.for_team(team_id, canonical=True).create(
+ team_id=team_id, profile=profile, cluster_key=gap.prompt_hash, **fields
+ )
+ continue
+ if _being_drafted(opportunity):
+ continue
+ if opportunity.status == ContentAutopilotOpportunity.Status.QUEUED:
+ fields["status"] = ContentAutopilotOpportunity.Status.NEW
+ for name, value in fields.items():
+ setattr(opportunity, name, value)
+ opportunity.save(update_fields=[*fields.keys(), "updated_at"])
+
+ current = {gap.prompt_hash for gap in gaps}
+ stale = [
+ opportunity.id
+ for key, opportunity in existing.items()
+ if key not in current
+ and opportunity.status
+ in (ContentAutopilotOpportunity.Status.NEW, ContentAutopilotOpportunity.Status.QUEUED)
+ and not _being_drafted(opportunity)
+ ]
+ if stale:
+ ContentAutopilotOpportunity.objects.for_team(team_id, canonical=True).filter(id__in=stale).delete()
+
+ return list_opportunities(team=team, profile_id=profile_id)
+
+
+def list_opportunities(*, team: Team, profile_id: str) -> list[ContentAutopilotOpportunity]:
+ return list(
+ ContentAutopilotOpportunity.objects.for_team(canonical_team_id(team), canonical=True)
+ .filter(profile_id=profile_id, profile__deleted=False)
+ .order_by("-score", "title")
+ )
+
+
+def _lock_opportunities(team_id: int, opportunity_ids: list[str]) -> list[ContentAutopilotOpportunity]:
+ opportunities = list(
+ ContentAutopilotOpportunity.objects.for_team(team_id, canonical=True)
+ .select_related("run")
+ .select_for_update(of=("self",))
+ .filter(id__in=opportunity_ids, profile__deleted=False)
+ )
+ if len(opportunities) != len(set(opportunity_ids)):
+ raise ContentAutopilotLifecycleError("One or more opportunities could not be found.")
+ return opportunities
+
+
+def dismiss_opportunity(*, team: Team, opportunity_id: str) -> ContentAutopilotOpportunity:
+ with transaction.atomic():
+ (opportunity,) = _lock_opportunities(canonical_team_id(team), [opportunity_id])
+ if _being_drafted(opportunity):
+ raise ContentAutopilotLifecycleError("This opportunity is being drafted and can't be dismissed.")
+ opportunity.status = ContentAutopilotOpportunity.Status.DISMISSED
+ opportunity.save(update_fields=["status", "updated_at"])
+ return opportunity
+
+
+def draft_opportunities(
+ *, team: Team, profile_id: str, opportunity_ids: list[str], triggered_by_id: int | None
+) -> ContentAutopilotRun:
+ if not opportunity_ids:
+ raise ContentAutopilotLifecycleError("Select at least one opportunity to draft.")
+ if len(set(opportunity_ids)) > MAX_DRAFTS_PER_RUN:
+ raise ContentAutopilotLifecycleError(f"Draft up to {MAX_DRAFTS_PER_RUN} opportunities at a time.")
+ team_id = canonical_team_id(team)
+ with transaction.atomic():
+ lock_profile(team_id, profile_id)
+ opportunities = _lock_opportunities(team_id, opportunity_ids)
+ if any(str(opportunity.profile_id) != str(profile_id) for opportunity in opportunities):
+ raise ContentAutopilotLifecycleError("Every opportunity must belong to the selected site.")
+ if any(_being_drafted(opportunity) for opportunity in opportunities):
+ raise ContentAutopilotLifecycleError("One or more opportunities are already being drafted.")
+ if any(opportunity.status == ContentAutopilotOpportunity.Status.DISMISSED for opportunity in opportunities):
+ raise ContentAutopilotLifecycleError("Dismissed opportunities can't be drafted.")
+ run = start_run(team=team, profile_id=profile_id, triggered_by_id=triggered_by_id)
+ for opportunity in opportunities:
+ opportunity.status = ContentAutopilotOpportunity.Status.QUEUED
+ opportunity.run = run
+ opportunity.save(update_fields=["status", "run", "updated_at"])
+ return run
diff --git a/products/web_analytics/backend/content_autopilot/site_discovery.py b/products/web_analytics/backend/content_autopilot/site_discovery.py
index 168d139b10fb..c87fbedf7a92 100644
--- a/products/web_analytics/backend/content_autopilot/site_discovery.py
+++ b/products/web_analytics/backend/content_autopilot/site_discovery.py
@@ -1,5 +1,6 @@
import re
import time
+from collections import deque
from html.parser import HTMLParser
from typing import TypedDict
from urllib.parse import urljoin, urlparse, urlunparse
@@ -145,9 +146,13 @@ def _public_host(url: str) -> str:
return hostname
+def site_host(url: str) -> str:
+ return _public_host(url).removeprefix("www.")
+
+
def has_same_public_site(first_url: str, second_url: str) -> bool:
- first = _public_host(first_url).removeprefix("www.")
- second = _public_host(second_url).removeprefix("www.")
+ first = site_host(first_url)
+ second = site_host(second_url)
if not first or not second:
return False
return first == second or first.endswith(f".{second}") or second.endswith(f".{first}")
@@ -271,3 +276,74 @@ def discover_site(raw_url: str) -> SiteDiscoveryResult:
"sitemap_detected": sitemap_detected,
"warnings": warnings,
}
+
+
+_MAX_SITEMAP_BYTES = 8 * 1024 * 1024
+_MAX_SITEMAP_FETCHES = 12
+_MAX_SITEMAP_SECONDS = 60.0
+_MAX_SITEMAP_URLS = 20_000
+
+
+def _fetch_sitemap(url: str, *, deadline: float) -> str | None:
+ try:
+ response = fetch_public_url(
+ strip_userinfo(url),
+ headers={"Accept": "application/xml,text/xml;q=0.9,*/*;q=0.1", "User-Agent": "PostHog content research"},
+ max_bytes=_MAX_SITEMAP_BYTES,
+ deadline=deadline,
+ connect_timeout_seconds=3.0,
+ read_timeout_seconds=15.0,
+ )
+ except PublicUrlFetchError:
+ return None
+ if not 200 <= response.status_code < 300:
+ return None
+ return response.body.decode("utf-8", errors="replace")
+
+
+def _is_on_site(url: str, origin: str) -> bool:
+ try:
+ parsed = urlparse(url)
+ port = parsed.port
+ except ValueError:
+ return False
+ scheme = parsed.scheme.lower()
+ if scheme not in _DEFAULT_PORTS or port not in (None, _DEFAULT_PORTS[scheme]):
+ return False
+ if scheme != urlparse(origin).scheme.lower():
+ return False
+ host = site_host(url)
+ return bool(host) and host == site_host(origin)
+
+
+def read_sitemap_urls(source_urls: list[str], *, origin: str) -> list[str]:
+ deadline = time.monotonic() + _MAX_SITEMAP_SECONDS
+ queued = list(dict.fromkeys(url for url in source_urls if has_same_public_origin(url, origin)))[
+ :_MAX_SITEMAP_FETCHES
+ ]
+ queue = deque(queued)
+ seen_sitemaps = set(queued)
+ pages: dict[str, None] = {}
+ while queue and time.monotonic() < deadline:
+ sitemap_url = queue.popleft()
+ text = _fetch_sitemap(sitemap_url, deadline=deadline)
+ if text is None:
+ continue
+ try:
+ root = ET.fromstring(text)
+ except (DefusedParseError, DefusedXmlException):
+ continue
+ is_index = root.tag.rsplit("}", 1)[-1].lower() == "sitemapindex"
+ for element in root.iter():
+ if element.tag.rsplit("}", 1)[-1].lower() != "loc" or not element.text:
+ continue
+ location = element.text.strip()
+ if not _is_on_site(location, origin):
+ continue
+ if is_index:
+ if location not in seen_sitemaps and len(seen_sitemaps) < _MAX_SITEMAP_FETCHES:
+ seen_sitemaps.add(location)
+ queue.append(location)
+ elif len(pages) < _MAX_SITEMAP_URLS:
+ pages[location] = None
+ return list(pages)
diff --git a/products/web_analytics/backend/test/content_autopilot_test_utils.py b/products/web_analytics/backend/test/content_autopilot_test_utils.py
index 3c7dc1a92b9c..e0db1d87be9a 100644
--- a/products/web_analytics/backend/test/content_autopilot_test_utils.py
+++ b/products/web_analytics/backend/test/content_autopilot_test_utils.py
@@ -1,6 +1,9 @@
+from django.utils import timezone
+
from posthog.models.team import Team
from products.web_analytics.backend.models import (
+ ContentAutopilotOpportunity,
ContentAutopilotProposal,
ContentAutopilotRun,
ContentAutopilotSiteProfile,
@@ -78,3 +81,42 @@ def create_content_autopilot_proposal(
content_package=default_package if content_package is UNSET_CONTENT_PACKAGE else content_package,
proposed_markdown=markdown,
)
+
+
+def create_content_autopilot_opportunity(
+ team: Team,
+ profile: ContentAutopilotSiteProfile,
+ *,
+ title: str = "What is the best open source session replay tool?",
+ cluster_key: str = "prompt-hash",
+ status: str = ContentAutopilotOpportunity.Status.NEW,
+ recommended_type: str = ContentAutopilotProposal.ProposalType.NEW_CONTENT,
+ target_url: str = "",
+ gap: dict[str, object] | None = None,
+) -> ContentAutopilotOpportunity:
+ return ContentAutopilotOpportunity.objects.for_team(team.id).create(
+ team=team,
+ profile=profile,
+ cluster_key=cluster_key,
+ title=title,
+ score=0.9,
+ recommended_type=recommended_type,
+ target_url=target_url,
+ evidence=[{"opportunity_kind": "ai_visibility_gap", "explanation": "Not cited.", "query": title}],
+ gap={
+ "checks": 3,
+ "cited_checks": 0,
+ "citation_rate": 0.0,
+ "engines": ["claude-web-search"],
+ "engines_not_citing": ["claude-web-search"],
+ "competitor_urls": ["https://rival.example/replay"],
+ "competitor_domains": ["rival.example"],
+ "engine_search_queries": [],
+ "our_cited_urls": [],
+ "latest_answers": [],
+ "last_checked_at": timezone.now().isoformat(),
+ **(gap or {}),
+ },
+ status=status,
+ last_refreshed_at=timezone.now(),
+ )
diff --git a/products/web_analytics/backend/test/test_content_autopilot_opportunities.py b/products/web_analytics/backend/test/test_content_autopilot_opportunities.py
new file mode 100644
index 000000000000..64cad0025ceb
--- /dev/null
+++ b/products/web_analytics/backend/test/test_content_autopilot_opportunities.py
@@ -0,0 +1,298 @@
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.aeo.backend.facade.contracts import CitationGap, EngineAnswer
+from products.web_analytics.backend.content_autopilot.lifecycle import ContentAutopilotLifecycleError
+from products.web_analytics.backend.content_autopilot.opportunities import (
+ MAX_DRAFTS_PER_RUN,
+ dismiss_opportunity,
+ draft_opportunities,
+ page_ai_traffic,
+ refresh_opportunities,
+ score_gap,
+ top_site_pages,
+)
+from products.web_analytics.backend.models import ContentAutopilotOpportunity, ContentAutopilotRun
+from products.web_analytics.backend.test.content_autopilot_test_utils import (
+ create_content_autopilot_opportunity,
+ create_content_autopilot_profile,
+ create_content_autopilot_run,
+)
+
+SITE_PAGES = [
+ "https://example.com/",
+ "https://example.com/pricing",
+ "https://example.com/docs/session-replay",
+ "https://example.com/docs/session-replay/privacy-controls",
+ "https://example.com/blog/best-open-source-analytics-tools",
+ "https://example.com/compare/best-adobe-analytics-alternatives",
+ "https://example.com/compare/best-plausible-alternatives",
+]
+
+
+def _gap(
+ prompt: str,
+ *,
+ checks: int = 9,
+ cited_checks: int = 0,
+ mentioned_checks: int = 0,
+ engines: tuple[str, ...] = ("claude-web-search", "openai-web-search", "exa-answer"),
+ engines_not_citing: tuple[str, ...] = ("claude-web-search", "openai-web-search", "exa-answer"),
+ our_cited_urls: tuple[str, ...] = (),
+) -> CitationGap:
+ return CitationGap(
+ prompt_id="0190a3b4-0000-0000-0000-000000000001",
+ prompt_hash=f"hash-{prompt}",
+ prompt_text=prompt,
+ checks=checks,
+ cited_checks=cited_checks,
+ mentioned_checks=mentioned_checks,
+ engines=engines,
+ engines_not_citing=engines_not_citing,
+ competitor_urls=("https://rival.example/replay",),
+ competitor_domains=("rival.example",),
+ engine_search_queries=("session replay tools",),
+ our_cited_urls=our_cited_urls,
+ latest_answers=(
+ EngineAnswer(engine="claude-web-search", answer_text="Rival is great.", checked_at=timezone.now()),
+ ),
+ last_checked_at=timezone.now(),
+ )
+
+
+class TestOpportunityScoring(SimpleTestCase):
+ def test_consistent_gaps_outrank_partial_and_thin_ones(self) -> None:
+ consistent = score_gap(_gap("a"))
+ partial = score_gap(
+ _gap("b", cited_checks=4, engines_not_citing=("exa-answer",)),
+ )
+ thin = score_gap(_gap("c", checks=2))
+ mentioned = score_gap(_gap("d", mentioned_checks=6))
+ assert consistent > partial
+ assert consistent > thin
+ assert mentioned > consistent
+
+
+@override_settings(AEO_TARGET_DOMAINS=["example.com"])
+class TestRefreshOpportunities(ClickhouseTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.profile = create_content_autopilot_profile(self.team)
+
+ def _refresh(
+ self, gaps: list[CitationGap], *, profile_id: str | None = None, page_urls: list[str] | None = SITE_PAGES
+ ) -> list[ContentAutopilotOpportunity]:
+ with patch(
+ "products.web_analytics.backend.content_autopilot.opportunities.list_citation_gaps", return_value=gaps
+ ):
+ return refresh_opportunities(
+ team=self.team, profile_id=profile_id or str(self.profile.id), page_urls=page_urls
+ )
+
+ def test_only_a_site_the_aeo_checks_track_gets_opportunities(self) -> None:
+ other = create_content_autopilot_profile(self.team, domain="https://other.example")
+
+ assert self._refresh([_gap("What is the best CRM?")], profile_id=str(other.id)) == []
+ assert len(self._refresh([_gap("What is the best CRM?")])) == 1
+
+ def test_an_empty_sitemap_still_limits_cited_pages_to_the_site_boundaries(self) -> None:
+ self.profile.content_boundaries = ["/docs"]
+ self.profile.save()
+
+ opportunities = self._refresh(
+ [
+ _gap("Admin question", our_cited_urls=("https://example.com/admin/users",)),
+ _gap("Docs question", our_cited_urls=("https://example.com/docs/replay",)),
+ ],
+ page_urls=[],
+ )
+
+ by_title = {opportunity.title: opportunity.target_url for opportunity in opportunities}
+ assert by_title == {"Admin question": "", "Docs question": "https://example.com/docs/replay"}
+
+ def test_recommends_improving_only_a_page_the_engines_cited(self) -> None:
+ opportunities = self._refresh(
+ [
+ _gap("What is the best CRM for startups?"),
+ _gap("How does session replay work?"),
+ _gap("Is it cheap?", our_cited_urls=("https://example.com/pricing",)),
+ _gap(
+ "Is it fast?",
+ our_cited_urls=("https://archive.example.com/pricing", "https://example.com/pricing?utm_source=ai"),
+ ),
+ ]
+ )
+
+ by_title = {opportunity.title: opportunity for opportunity in opportunities}
+ assert by_title["What is the best CRM for startups?"].recommended_type == "new_content"
+ assert by_title["How does session replay work?"].target_url == ""
+ assert by_title["How does session replay work?"].recommended_type == "new_content"
+ assert by_title["Is it cheap?"].recommended_type == "page_improvement"
+ assert by_title["Is it cheap?"].target_url == "https://example.com/pricing"
+ assert by_title["Is it fast?"].target_url == "https://example.com/pricing"
+ assert "rival.example" in by_title["What is the best CRM for startups?"].evidence[0]["explanation"]
+ assert (
+ by_title["What is the best CRM for startups?"].gap["latest_answers"][0]["answer_text"] == "Rival is great."
+ )
+
+ def test_counts_ai_crawls_on_a_page_with_and_without_a_trailing_slash(self) -> None:
+ for index, (path, host) in enumerate(
+ [
+ ("/pricing", None),
+ ("/pricing/", "www.example.com"),
+ ("/pricing/", None),
+ ("/docs", None),
+ ("/pricing", "other.example"),
+ ]
+ ):
+ _create_event(
+ team=self.team,
+ event="$http_log",
+ distinct_id=f"crawler-{index}",
+ properties={
+ "$pathname": path,
+ "$raw_user_agent": "Mozilla/5.0 (compatible; GPTBot/1.2)",
+ **({"$host": host} if host else {}),
+ },
+ )
+ flush_persons_and_events()
+
+ traffic = page_ai_traffic(self.team, "https://example.com", ["/pricing"], include_hostless=True)
+ shared = page_ai_traffic(self.team, "https://example.com", ["/pricing"], include_hostless=False)
+
+ assert traffic["/pricing"]["ai_crawls"] == 3
+ assert "/docs" not in traffic
+ assert shared["/pricing"]["ai_crawls"] == 1
+
+ def test_ranks_sitemap_pages_by_views_on_the_site_then_fills_with_shallow_pages(self) -> None:
+ for path, views in [("/docs/session-replay", 3), ("/pricing/", 1), ("/not-in-sitemap", 5)]:
+ for index in range(views):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=f"visitor-{path}-{index}",
+ properties={"$host": "www.example.com", "$pathname": path},
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="other-site",
+ properties={"$host": "app.other.example", "$pathname": "/docs/session-replay/privacy-controls"},
+ )
+ flush_persons_and_events()
+
+ pages = top_site_pages(self.team, origin="https://example.com", page_urls=SITE_PAGES, limit=4)
+
+ assert pages == [
+ "https://example.com/docs/session-replay",
+ "https://example.com/pricing",
+ "https://example.com/",
+ "https://example.com/docs/session-replay/privacy-controls",
+ ]
+
+ def test_refresh_keeps_dismissals_and_active_drafts_and_drops_gaps_that_closed(self) -> None:
+ dismissed = create_content_autopilot_opportunity(self.team, self.profile, cluster_key="hash-dismissed")
+ dismiss_opportunity(team=self.team, opportunity_id=str(dismissed.id))
+ queued = create_content_autopilot_opportunity(
+ self.team, self.profile, cluster_key="hash-queued", status=ContentAutopilotOpportunity.Status.QUEUED
+ )
+ queued.run = create_content_autopilot_run(self.team, self.profile)
+ queued.save()
+ stuck = create_content_autopilot_opportunity(
+ self.team, self.profile, cluster_key="hash-stuck", status=ContentAutopilotOpportunity.Status.QUEUED
+ )
+ stuck.run = create_content_autopilot_run(
+ self.team, self.profile, run_status=ContentAutopilotRun.RunStatus.CANCELED
+ )
+ stuck.save()
+ closed = create_content_autopilot_opportunity(self.team, self.profile, cluster_key="hash-closed")
+ closed_while_stuck = create_content_autopilot_opportunity(
+ self.team, self.profile, cluster_key="hash-closed-stuck", status=ContentAutopilotOpportunity.Status.QUEUED
+ )
+ closed_while_stuck.run = stuck.run
+ closed_while_stuck.save()
+
+ self._refresh([_gap("dismissed"), _gap("queued"), _gap("stuck")])
+
+ dismissed.refresh_from_db()
+ queued.refresh_from_db()
+ stuck.refresh_from_db()
+ assert dismissed.status == ContentAutopilotOpportunity.Status.DISMISSED
+ assert dismissed.title == "dismissed"
+ assert queued.status == ContentAutopilotOpportunity.Status.QUEUED
+ assert queued.title == "What is the best open source session replay tool?"
+ assert (stuck.status, stuck.title) == (ContentAutopilotOpportunity.Status.NEW, "stuck")
+ assert (
+ not ContentAutopilotOpportunity.objects.for_team(self.team.id)
+ .filter(id__in=[closed.id, closed_while_stuck.id])
+ .exists()
+ )
+
+
+class TestDraftOpportunities(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.profile = create_content_autopilot_profile(self.team)
+
+ def test_queues_opportunities_on_a_new_pending_run(self) -> None:
+ opportunity = create_content_autopilot_opportunity(self.team, self.profile)
+
+ run = draft_opportunities(
+ team=self.team, profile_id=str(self.profile.id), opportunity_ids=[str(opportunity.id)], triggered_by_id=None
+ )
+
+ opportunity.refresh_from_db()
+ assert run.run_status == ContentAutopilotRun.RunStatus.PENDING
+ assert opportunity.status == ContentAutopilotOpportunity.Status.QUEUED
+ assert opportunity.run_id == run.id
+
+ @parameterized.expand(
+ [
+ ("too_many", MAX_DRAFTS_PER_RUN + 1, "up to"),
+ ("none", 0, "at least one"),
+ ]
+ )
+ def test_rejects_invalid_selection_sizes(self, _name: str, count: int, message: str) -> None:
+ ids = [
+ str(create_content_autopilot_opportunity(self.team, self.profile, cluster_key=f"hash-{index}").id)
+ for index in range(count)
+ ]
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, message):
+ draft_opportunities(
+ team=self.team, profile_id=str(self.profile.id), opportunity_ids=ids, triggered_by_id=None
+ )
+
+ def test_rejects_opportunities_from_another_site_already_queued_or_dismissed(self) -> None:
+ other_profile = create_content_autopilot_profile(self.team, domain="https://other.example")
+ foreign = create_content_autopilot_opportunity(self.team, other_profile)
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "selected site"):
+ draft_opportunities(
+ team=self.team, profile_id=str(self.profile.id), opportunity_ids=[str(foreign.id)], triggered_by_id=None
+ )
+
+ queued = create_content_autopilot_opportunity(
+ self.team, self.profile, cluster_key="queued", status=ContentAutopilotOpportunity.Status.QUEUED
+ )
+ queued.run = create_content_autopilot_run(self.team, self.profile)
+ queued.save()
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "already being drafted"):
+ draft_opportunities(
+ team=self.team, profile_id=str(self.profile.id), opportunity_ids=[str(queued.id)], triggered_by_id=None
+ )
+
+ dismissed = create_content_autopilot_opportunity(
+ self.team, self.profile, cluster_key="dismissed", status=ContentAutopilotOpportunity.Status.DISMISSED
+ )
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "Dismissed"):
+ draft_opportunities(
+ team=self.team,
+ profile_id=str(self.profile.id),
+ opportunity_ids=[str(dismissed.id)],
+ triggered_by_id=None,
+ )
+ assert ContentAutopilotRun.objects.for_team(self.team.id).count() == 1
diff --git a/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py b/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py
index c41c8912ec79..0f8b42462827 100644
--- a/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py
+++ b/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py
@@ -10,6 +10,7 @@ from products.web_analytics.backend.content_autopilot.site_discovery import (
has_same_public_origin,
has_same_public_site,
normalize_site_origin,
+ read_sitemap_urls,
)
from products.web_analytics.backend.public_url_fetch import FetchedPublicUrl, PublicUrlFetchError
@@ -194,3 +195,35 @@ class TestContentAutopilotSiteDiscovery(SimpleTestCase):
self.assertEqual(result["source_urls"], ["https://example.com/sitemap.xml"])
self.assertTrue(result["sitemap_detected"])
+
+ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")
+ def test_reads_only_sitemaps_and_pages_on_the_site_host(self, fetch_public_url: MagicMock) -> None:
+ index = b"""<sitemapindex>
+ <sitemap><loc>https://www.example.com/pages.xml</loc></sitemap>
+ <sitemap><loc>https://internal.example.com/private.xml</loc></sitemap>
+ <sitemap><loc>https://example.com:8080/admin.xml</loc></sitemap>
+ <sitemap><loc>http://example.com:443/odd.xml</loc></sitemap>
+ <sitemap><loc>http://example.com/plain.xml</loc></sitemap>
+ </sitemapindex>"""
+ pages = b"""<urlset>
+ <url><loc>https://www.example.com/docs</loc></url>
+ <url><loc>https://blog.example.com/post</loc></url>
+ <url><loc>http://example.com/insecure</loc></url>
+ </urlset>"""
+
+ def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:
+ if url == "https://example.com/sitemap.xml":
+ return _response(body=index)
+ if url == "https://www.example.com/pages.xml":
+ return _response(body=pages)
+ return _response(body=b"<urlset><url><loc>https://example.com/should-not-appear</loc></url></urlset>")
+
+ fetch_public_url.side_effect = response_for
+
+ result = read_sitemap_urls(["https://example.com/sitemap.xml"], origin="https://example.com")
+
+ self.assertEqual(result, ["https://www.example.com/docs"])
+ self.assertEqual(
+ [call.args[0] for call in fetch_public_url.call_args_list],
+ ["https://example.com/sitemap.xml", "https://www.example.com/pages.xml"],
+ )
diff --git a/tach.toml b/tach.toml
index 31303c7a5be3..4b99b4aee205 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1077,6 +1077,7 @@ layer = "modules"
path = "products.web_analytics"
depends_on = [
"products.access_control",
+ "products.aeo",
"products.cohorts",
"ee",
"posthog",