: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): list, refresh and dismiss content opportunities (#108593)
Jordan Mryyan0787d863e1f6
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 3029609ef49f..11614dc464cf 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -253,6 +253,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.web_analytics.backend.api.heatmaps_api.HeatmapViewSet","products.web_analytics.backend.api.heatmaps_api.LegacyHeatmapViewSet","products.web_analytics.backend.api.heatmaps_api.SavedHeatmapViewSet",+ "products.web_analytics.backend.presentation.views.content_autopilot.ContentAutopilotOpportunityViewSet","products.web_analytics.backend.presentation.views.content_autopilot.ContentAutopilotProposalViewSet","products.web_analytics.backend.presentation.views.content_autopilot.ContentAutopilotRunViewSet","products.wizard.backend.presentation.artifacts.views.WizardRunArtifactViewSet",diff --git a/products/web_analytics/backend/facade/content_autopilot.py b/products/web_analytics/backend/facade/content_autopilot.pyindex 599d8515c63c..739051fae553 100644--- a/products/web_analytics/backend/facade/content_autopilot.py+++ b/products/web_analytics/backend/facade/content_autopilot.py@@ -1,3 +1,6 @@+from posthog.models.team import Team++from products.web_analytics.backend.content_autopilot import opportunitiesfrom products.web_analytics.backend.content_autopilot.export import ContentAutopilotExportError, export_proposalfrom products.web_analytics.backend.content_autopilot.lifecycle import (MAX_PROPOSAL_MARKDOWN_CHARS,@@ -24,11 +27,21 @@ __all__ = ["cancel_run","delete_profile","discover_site",+ "dismiss_opportunity","edit_proposal","export_proposal","has_same_public_origin","normalize_site_origin",+ "refresh_opportunities","regenerate_proposal","reject_proposal","start_run",]+++def refresh_opportunities(*, team: Team, profile_id: str) -> None:+ opportunities.refresh_opportunities(team=team, profile_id=profile_id)+++def dismiss_opportunity(*, team: Team, opportunity_id: str) -> None:+ opportunities.dismiss_opportunity(team=team, opportunity_id=opportunity_id)diff --git a/products/web_analytics/backend/presentation/views/content_autopilot.py b/products/web_analytics/backend/presentation/views/content_autopilot.pyindex c7d8e42afc74..6de8d9b898f7 100644--- a/products/web_analytics/backend/presentation/views/content_autopilot.py+++ b/products/web_analytics/backend/presentation/views/content_autopilot.py@@ -31,15 +31,18 @@ from products.web_analytics.backend.facade.content_autopilot import (cancel_run,delete_profile,discover_site,+ dismiss_opportunity,edit_proposal,export_proposal,has_same_public_origin,normalize_site_origin,+ refresh_opportunities,regenerate_proposal,reject_proposal,start_run,)from products.web_analytics.backend.facade.models import (+ ContentAutopilotOpportunity,ContentAutopilotProposal,ContentAutopilotRun,ContentAutopilotSiteProfile,@@ -170,6 +173,39 @@ class ContentAutopilotPackageSerializer(serializers.Serializer):)+class ContentAutopilotEngineAnswerSerializer(serializers.Serializer):+ engine = serializers.CharField(help_text="Answer engine that gave the answer.")+ answer_text = serializers.CharField(help_text="The engine's most recent answer. Third-party text.")+ checked_at = serializers.CharField(help_text="When the answer was recorded, in ISO 8601.")+++class ContentAutopilotCitationGapSerializer(serializers.Serializer):+ checks = serializers.IntegerField(help_text="Successful citation checks in the lookback window.")+ cited_checks = serializers.IntegerField(help_text="Checks whose answer cited the site.")+ mentioned_checks = serializers.IntegerField(+ help_text="Checks whose answer named the site's brand or cited the site.", default=0+ )+ citation_rate = serializers.FloatField(help_text="Share of checks that cited the site, from 0 to 1.")+ engines = serializers.ListField(child=serializers.CharField(), help_text="Engines that answered the prompt.")+ engines_not_citing = serializers.ListField(+ child=serializers.CharField(), help_text="Engines that never cited the site in the window."+ )+ competitor_urls = serializers.ListField(+ child=serializers.CharField(), help_text="Other sites' pages the engines cited, most frequent first."+ )+ competitor_domains = serializers.ListField(+ child=serializers.CharField(), help_text="Domains the engines cited instead, most frequent first."+ )+ engine_search_queries = serializers.ListField(+ child=serializers.CharField(), help_text="Web searches the engines ran while answering."+ )+ our_cited_urls = serializers.ListField(+ child=serializers.CharField(), help_text="Site pages the engines cited when they did cite the site."+ )+ latest_answers = ContentAutopilotEngineAnswerSerializer(many=True, help_text="Most recent answer per engine.")+ last_checked_at = serializers.CharField(help_text="When the prompt was last checked, in ISO 8601.")++class ContentAutopilotSiteProfileSerializer(serializers.ModelSerializer):source_urls = serializers.ListField(child=serializers.URLField(),@@ -400,6 +436,56 @@ class ContentAutopilotExportResponseSerializer(serializers.Serializer):content_package = ContentAutopilotPackageSerializer(help_text="Structured JSON package for a CMS adapter.")+class ContentAutopilotOpportunitySerializer(serializers.ModelSerializer):+ evidence = ContentAutopilotEvidenceSerializer(many=True, help_text="Why this opportunity was selected.")+ gap = ContentAutopilotCitationGapSerializer(help_text="Citation check results behind this opportunity.")++ class Meta:+ model = ContentAutopilotOpportunity+ fields = [+ "id",+ "profile_id",+ "run_id",+ "proposal_id",+ "kind",+ "title",+ "score",+ "recommended_type",+ "target_url",+ "evidence",+ "gap",+ "status",+ "last_refreshed_at",+ "created_at",+ "updated_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "profile_id": {"help_text": "Site profile this opportunity belongs to."},+ "run_id": {"help_text": "Latest run that drafted this opportunity."},+ "proposal_id": {"help_text": "Latest proposal drafted for this opportunity."},+ "kind": {"help_text": "Type of visibility gap."},+ "title": {"help_text": "The prompt the site isn't cited for."},+ "score": {"help_text": "Priority from 0 to 1. Higher means a clearer, more consistent gap."},+ "recommended_type": {+ "help_text": "`page_improvement` when the engines cited a site page for the prompt. Otherwise `new_content`, and drafting decides between a new page and an existing one."+ },+ "target_url": {+ "help_text": "Site page the engines cited for the prompt, to improve. Empty when no page was cited."+ },+ "status": {"help_text": "Where the opportunity is in the drafting workflow."},+ "last_refreshed_at": {"help_text": "When the citation data was last read."},+ }+++class ContentAutopilotOpportunityListQuerySerializer(serializers.Serializer):+ profile_id = serializers.UUIDField(help_text="Site profile to list opportunities for.")+++class ContentAutopilotOpportunityRefreshRequestSerializer(serializers.Serializer):+ profile_id = serializers.UUIDField(help_text="Site profile to refresh opportunities for.")++class ContentAutopilotSiteProfileViewSet(ContentAutopilotViewSetMixin, viewsets.ModelViewSet):serializer_class = ContentAutopilotSiteProfileSerializerqueryset = ContentAutopilotSiteProfile.objects.unscoped()@@ -504,7 +590,7 @@ class ContentAutopilotProposalViewSet(ContentAutopilotViewSetMixin, viewsets.Reaqueryset = queryset.filter(run_id=run_id)if profile_id := filters.get("profile_id"):queryset = queryset.filter(run__profile_id=profile_id)- queryset = queryset.defer("original_markdown", "proposed_markdown")+ queryset = queryset.defer("original_markdown", "proposed_markdown", "brief", "source_ledger", "research")return queryset.order_by("-created_at")@validated_request(@@ -555,3 +641,51 @@ class ContentAutopilotProposalViewSet(ContentAutopilotViewSetMixin, viewsets.Readef export(self, request: Request, **kwargs: Any) -> Response:exported = export_proposal(team=self.team, proposal_id=str(self.get_object().id))return Response(ContentAutopilotExportResponseSerializer(instance=exported).data)+++@extend_schema_view(list=extend_schema(parameters=[ContentAutopilotOpportunityListQuerySerializer]))+class ContentAutopilotOpportunityViewSet(ContentAutopilotViewSetMixin, viewsets.ReadOnlyModelViewSet):+ serializer_class = ContentAutopilotOpportunitySerializer+ queryset = ContentAutopilotOpportunity.objects.unscoped()++ def safely_get_queryset(+ self, queryset: QuerySet[ContentAutopilotOpportunity]+ ) -> QuerySet[ContentAutopilotOpportunity]:+ queryset = ContentAutopilotOpportunity.objects.for_team(self.team_id).filter(profile__deleted=False)+ if self.action == "list":+ filters = self.validated_query_params(ContentAutopilotOpportunityListQuerySerializer)+ queryset = queryset.filter(profile_id=filters["profile_id"])+ return queryset.order_by("-score", "title")++ @validated_request(+ request_serializer=ContentAutopilotOpportunityRefreshRequestSerializer,+ operation_id="web_analytics_content_autopilot_opportunities_refresh",+ summary="Refresh content opportunities",+ description="Re-reads AI citation checks and updates the site's content opportunities. Makes no model calls.",+ responses={200: OpenApiResponse(response=ContentAutopilotOpportunitySerializer(many=True))},+ tags=["web_analytics"],+ )+ @action(detail=False, methods=["post"], required_scopes=["web_analytics:write"], pagination_class=None)+ def refresh(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ profile_id = str(request.validated_data["profile_id"])+ refresh_opportunities(team=self.team, profile_id=profile_id)+ opportunities = (+ ContentAutopilotOpportunity.objects.for_team(self.team_id)+ .filter(profile_id=profile_id, profile__deleted=False)+ .order_by("-score", "title")+ )+ return Response(self.get_serializer(opportunities, many=True).data)++ @validated_request(+ operation_id="web_analytics_content_autopilot_opportunities_dismiss",+ summary="Dismiss a content opportunity",+ description="Marks an opportunity as dismissed. It stays dismissed across refreshes, and list responses still include it with status `dismissed`.",+ responses={200: OpenApiResponse(response=ContentAutopilotOpportunitySerializer)},+ tags=["web_analytics"],+ )+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])+ def dismiss(self, request: Request, **kwargs: Any) -> Response:+ opportunity = self.get_object()+ dismiss_opportunity(team=self.team, opportunity_id=str(opportunity.id))+ opportunity.refresh_from_db()+ return Response(self.get_serializer(opportunity).data)diff --git a/products/web_analytics/backend/routes.py b/products/web_analytics/backend/routes.pyindex 0f33b5b18eef..7c4490473beb 100644--- a/products/web_analytics/backend/routes.py+++ b/products/web_analytics/backend/routes.py@@ -15,6 +15,7 @@ from products.web_analytics.backend.api.web_analytics_path_cleaning_suggestions)from products.web_analytics.backend.presentation.views.capture_settings import HeatmapCaptureSettingsViewSetfrom products.web_analytics.backend.presentation.views.content_autopilot import (+ ContentAutopilotOpportunityViewSet,ContentAutopilotProposalViewSet,ContentAutopilotRunViewSet,ContentAutopilotSiteProfileViewSet,@@ -60,6 +61,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_web_analytics_content_autopilot_proposals",["team_id"],)+ routers.projects.register(+ r"web_analytics_content_autopilot_opportunities",+ ContentAutopilotOpportunityViewSet,+ "project_web_analytics_content_autopilot_opportunities",+ ["team_id"],+ )routers.projects.register(r"web_analytics_achievements",WebAnalyticsAchievementsViewSet,diff --git a/products/web_analytics/backend/test/test_content_autopilot_api.py b/products/web_analytics/backend/test/test_content_autopilot_api.pyindex 0086e5e491d0..c9b9ef15079d 100644--- a/products/web_analytics/backend/test/test_content_autopilot_api.py+++ b/products/web_analytics/backend/test/test_content_autopilot_api.py@@ -13,6 +13,7 @@ from products.web_analytics.backend.models import ContentAutopilotProposal, Contfrom products.web_analytics.backend.presentation.views.content_autopilot import CONTENT_AUTOPILOT_FEATURE_FLAGfrom products.web_analytics.backend.public_url_fetch import FetchedPublicUrl, PublicUrlFetchErrorfrom products.web_analytics.backend.test.content_autopilot_test_utils import (+ create_content_autopilot_opportunity,create_content_autopilot_profile,create_content_autopilot_proposal,create_content_autopilot_run,@@ -47,6 +48,9 @@ class TestContentAutopilotAPI(APIBaseTest):def _proposals_url(self, suffix: str = "") -> str:return f"/api/projects/{self.team.id}/web_analytics_content_autopilot_proposals/{suffix}"+ def _opportunities_url(self, suffix: str = "") -> str:+ return f"/api/projects/{self.team.id}/web_analytics_content_autopilot_opportunities/{suffix}"+def _profile_payload(self, **overrides: object) -> dict[str, object]:payload: dict[str, object] = {"name": "Example",@@ -298,6 +302,25 @@ class TestContentAutopilotAPI(APIBaseTest):self.assertEqual(rejected.json()["lifecycle_status"], ContentAutopilotProposal.LifecycleStatus.REJECTED)self.assertEqual(regenerated.json()["lifecycle_status"], ContentAutopilotProposal.LifecycleStatus.GENERATING)+ def test_opportunities_are_listed_per_site_and_dismissed(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ drafted = create_content_autopilot_opportunity(self.team, profile, cluster_key="drafted")+ dismissed = create_content_autopilot_opportunity(self.team, profile, cluster_key="dismissed")++ missing_profile = self.client.get(self._opportunities_url())+ listed = self.client.get(self._opportunities_url(), {"profile_id": str(profile.id)})+ dismiss = self.client.post(self._opportunities_url(f"{dismissed.id}/dismiss/"), format="json")+ after = self.client.get(self._opportunities_url(), {"profile_id": str(profile.id)})++ self.assertEqual(missing_profile.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual({item["id"] for item in listed.json()["results"]}, {str(drafted.id), str(dismissed.id)})+ self.assertEqual(listed.json()["results"][0]["gap"]["competitor_urls"], ["https://rival.example/replay"])+ self.assertEqual(dismiss.json()["status"], "dismissed")+ self.assertEqual(+ {item["id"]: item["status"] for item in after.json()["results"]},+ {str(drafted.id): "new", str(dismissed.id): "dismissed"},+ )+def test_edit_stores_markdown_whitespace_exactly(self) -> None:proposal = self._reviewable_proposal()markdown = " indented code block\n\n# Reviewed draft\n\nUseful content.\n"@@ -344,10 +367,13 @@ class TestContentAutopilotAPI(APIBaseTest):other_profile = create_content_autopilot_profile(other_team, domain="https://other.example")other_run = create_content_autopilot_run(other_team, other_profile)other_proposal = create_content_autopilot_proposal(other_team, other_run)+ other_opportunity = create_content_autopilot_opportunity(other_team, other_profile)proposal_response = self.client.get(self._proposals_url(f"{other_proposal.id}/"))runs_response = self.client.get(self._runs_url())+ dismiss_response = self.client.post(self._opportunities_url(f"{other_opportunity.id}/dismiss/"))self.assertEqual(proposal_response.status_code, status.HTTP_404_NOT_FOUND)self.assertEqual(runs_response.status_code, status.HTTP_200_OK)self.assertEqual(runs_response.json()["results"], [])+ self.assertEqual(dismiss_response.status_code, status.HTTP_404_NOT_FOUND)diff --git a/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py b/products/web_analytics/backend/test/test_content_autopilot_lifecycle.pyindex 5e34f324b339..5479fe3ad6f9 100644--- a/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py+++ b/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py@@ -16,6 +16,7 @@ from products.web_analytics.backend.content_autopilot.lifecycle import (start_run,)from products.web_analytics.backend.models import (+ ContentAutopilotOpportunity,ContentAutopilotProposal,ContentAutopilotRun,ContentAutopilotSiteProfile,@@ -37,6 +38,7 @@ class TestContentAutopilotLifecycle(BaseTest):create_content_autopilot_profile(other_team, domain="https://other.example")for model in [+ ContentAutopilotOpportunity,ContentAutopilotSiteProfile,ContentAutopilotRun,ContentAutopilotProposal,diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 526beae46c5a..5aa2b20a12e2 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -802,6 +802,174 @@ export interface WebAnalyticsBotRuleApi {items: WebAnalyticsBotConditionApi[]}+/**+ * * `ai_visibility_gap` - AI visibility gap+ */+export type ContentAutopilotOpportunityKindEnumApi =+ (typeof ContentAutopilotOpportunityKindEnumApi)[keyof typeof ContentAutopilotOpportunityKindEnumApi]++export const ContentAutopilotOpportunityKindEnumApi = {+ AiVisibilityGap: 'ai_visibility_gap',+} as const++/**+ * * `new_content` - New content+ * * `page_improvement` - Page improvement+ */+export type ContentAutopilotProposalProposalTypeEnumApi =+ (typeof ContentAutopilotProposalProposalTypeEnumApi)[keyof typeof ContentAutopilotProposalProposalTypeEnumApi]++export const ContentAutopilotProposalProposalTypeEnumApi = {+ NewContent: 'new_content',+ PageImprovement: 'page_improvement',+} as const++/**+ * * `poor_ctr` - Poor click-through rate+ * * `content_gap` - Content gap+ * * `organic_decline` - Organic decline+ * * `ai_visibility_gap` - AI visibility gap+ * * `site_hygiene` - Site hygiene+ */+export type OpportunityKindEnumApi = (typeof OpportunityKindEnumApi)[keyof typeof OpportunityKindEnumApi]++export const OpportunityKindEnumApi = {+ PoorCtr: 'poor_ctr',+ ContentGap: 'content_gap',+ OrganicDecline: 'organic_decline',+ AiVisibilityGap: 'ai_visibility_gap',+ SiteHygiene: 'site_hygiene',+} as const++export interface ContentAutopilotEvidenceApi {+ /** Reason the opportunity was selected.+ *+ * * `poor_ctr` - Poor click-through rate+ * * `content_gap` - Content gap+ * * `organic_decline` - Organic decline+ * * `ai_visibility_gap` - AI visibility gap+ * * `site_hygiene` - Site hygiene */+ opportunity_kind: OpportunityKindEnumApi+ /** Plain-language explanation of the supporting evidence. */+ explanation: string+ /** Page supported by this evidence. */+ page_url?: string+ /** Search query supported by this evidence. */+ query?: string+}++export interface ContentAutopilotEngineAnswerApi {+ /** Answer engine that gave the answer. */+ engine: string+ /** The engine's most recent answer. Third-party text. */+ answer_text: string+ /** When the answer was recorded, in ISO 8601. */+ checked_at: string+}++export interface ContentAutopilotCitationGapApi {+ /** Successful citation checks in the lookback window. */+ checks: number+ /** Checks whose answer cited the site. */+ cited_checks: number+ /** Checks whose answer named the site's brand or cited the site. */+ mentioned_checks?: number+ /** Share of checks that cited the site, from 0 to 1. */+ citation_rate: number+ /** Engines that answered the prompt. */+ engines: string[]+ /** Engines that never cited the site in the window. */+ engines_not_citing: string[]+ /** Other sites' pages the engines cited, most frequent first. */+ competitor_urls: string[]+ /** Domains the engines cited instead, most frequent first. */+ competitor_domains: string[]+ /** Web searches the engines ran while answering. */+ engine_search_queries: string[]+ /** Site pages the engines cited when they did cite the site. */+ our_cited_urls: string[]+ /** Most recent answer per engine. */+ latest_answers: ContentAutopilotEngineAnswerApi[]+ /** When the prompt was last checked, in ISO 8601. */+ last_checked_at: string+}++/**+ * * `new` - New+ * * `dismissed` - Dismissed+ * * `queued` - Queued+ * * `drafted` - Drafted+ */+export type ContentAutopilotOpportunityStatusEnumApi =+ (typeof ContentAutopilotOpportunityStatusEnumApi)[keyof typeof ContentAutopilotOpportunityStatusEnumApi]++export const ContentAutopilotOpportunityStatusEnumApi = {+ New: 'new',+ Dismissed: 'dismissed',+ Queued: 'queued',+ Drafted: 'drafted',+} as const++export interface ContentAutopilotOpportunityApi {+ readonly id: string+ /** Site profile this opportunity belongs to. */+ readonly profile_id: string+ /**+ * Latest run that drafted this opportunity.+ * @nullable+ */+ readonly run_id: string | null+ /**+ * Latest proposal drafted for this opportunity.+ * @nullable+ */+ readonly proposal_id: string | null+ /** Type of visibility gap.+ *+ * * `ai_visibility_gap` - AI visibility gap */+ readonly kind: ContentAutopilotOpportunityKindEnumApi+ /** The prompt the site isn't cited for. */+ readonly title: string+ /** Priority from 0 to 1. Higher means a clearer, more consistent gap. */+ readonly score: number+ /** `page_improvement` when the engines cited a site page for the prompt. Otherwise `new_content`, and drafting decides between a new page and an existing one.+ *+ * * `new_content` - New content+ * * `page_improvement` - Page improvement */+ readonly recommended_type: ContentAutopilotProposalProposalTypeEnumApi+ /** Site page the engines cited for the prompt, to improve. Empty when no page was cited. */+ readonly target_url: string+ /** Why this opportunity was selected. */+ evidence: ContentAutopilotEvidenceApi[]+ /** Citation check results behind this opportunity. */+ gap: ContentAutopilotCitationGapApi+ /** Where the opportunity is in the drafting workflow.+ *+ * * `new` - New+ * * `dismissed` - Dismissed+ * * `queued` - Queued+ * * `drafted` - Drafted */+ readonly status: ContentAutopilotOpportunityStatusEnumApi+ /** When the citation data was last read. */+ readonly last_refreshed_at: string+ readonly created_at: string+ readonly updated_at: string+}++export interface PaginatedContentAutopilotOpportunityListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ContentAutopilotOpportunityApi[]+}++export interface ContentAutopilotOpportunityRefreshRequestApi {+ /** Site profile to refresh opportunities for. */+ profile_id: string+}+export interface ContentAutopilotSiteProfileApi {readonly id: string/**@@ -879,18 +1047,6 @@ export interface ContentAutopilotSiteDiscoveryResponseApi {warnings: string[]}-/**- * * `new_content` - New content- * * `page_improvement` - Page improvement- */-export type ContentAutopilotProposalProposalTypeEnumApi =- (typeof ContentAutopilotProposalProposalTypeEnumApi)[keyof typeof ContentAutopilotProposalProposalTypeEnumApi]--export const ContentAutopilotProposalProposalTypeEnumApi = {- NewContent: 'new_content',- PageImprovement: 'page_improvement',-} as const-/*** * `generating` - Generating* * `ready_for_review` - Ready for review@@ -909,40 +1065,6 @@ export const ContentAutopilotProposalLifecycleStatusEnumApi = {Failed: 'failed',} as const-/**- * * `poor_ctr` - Poor click-through rate- * * `content_gap` - Content gap- * * `organic_decline` - Organic decline- * * `ai_visibility_gap` - AI visibility gap- * * `site_hygiene` - Site hygiene- */-export type OpportunityKindEnumApi = (typeof OpportunityKindEnumApi)[keyof typeof OpportunityKindEnumApi]--export const OpportunityKindEnumApi = {- PoorCtr: 'poor_ctr',- ContentGap: 'content_gap',- OrganicDecline: 'organic_decline',- AiVisibilityGap: 'ai_visibility_gap',- SiteHygiene: 'site_hygiene',-} as const--export interface ContentAutopilotEvidenceApi {- /** Reason the opportunity was selected.- *- * * `poor_ctr` - Poor click-through rate- * * `content_gap` - Content gap- * * `organic_decline` - Organic decline- * * `ai_visibility_gap` - AI visibility gap- * * `site_hygiene` - Site hygiene */- opportunity_kind: OpportunityKindEnumApi- /** Plain-language explanation of the supporting evidence. */- explanation: string- /** Page supported by this evidence. */- page_url?: string- /** Search query supported by this evidence. */- query?: string-}-export interface ContentAutopilotValidationCheckApi {/** Stable identifier for the validation gate. */check_key: string@@ -1492,6 +1614,21 @@ export type WebAnalyticsWeeklyDigestParams = {days?: number}+export type WebAnalyticsContentAutopilotOpportunitiesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Site profile to list opportunities for.+ */+ profile_id: string+}+export type WebAnalyticsContentAutopilotProfilesListParams = {/*** Number of results to return per page.diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex 74c1fc75aa91..2ce76bbc8911 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -14,6 +14,8 @@ import type {AcknowledgeCelebrationResponseApi,ApplyPathCleaningSuggestionResponseApi,ContentAutopilotExportResponseApi,+ ContentAutopilotOpportunityApi,+ ContentAutopilotOpportunityRefreshRequestApi,ContentAutopilotProposalApi,ContentAutopilotProposalEditRequestApi,ContentAutopilotRunApi,@@ -36,6 +38,7 @@ import type {HeatmapsResponseApi,LlmsTxtFetchRequestApi,LlmsTxtFetchResponseApi,+ PaginatedContentAutopilotOpportunityListApi,PaginatedContentAutopilotProposalListListApi,PaginatedContentAutopilotRunListApi,PaginatedContentAutopilotSiteProfileListApi,@@ -54,6 +57,7 @@ import type {SavedHeatmapRequestApi,SavedListParams,WebAnalyticsBotRuleApi,+ WebAnalyticsContentAutopilotOpportunitiesListParams,WebAnalyticsContentAutopilotProfilesListParams,WebAnalyticsContentAutopilotProposalsListParams,WebAnalyticsContentAutopilotRunsListParams,@@ -720,6 +724,103 @@ export const webAnalyticsBotRulesDestroy = async (})}+export const getWebAnalyticsContentAutopilotOpportunitiesListUrl = (+ projectId: string,+ params: WebAnalyticsContentAutopilotOpportunitiesListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/?${stringifiedParams}`+ : `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/`+}++export const webAnalyticsContentAutopilotOpportunitiesList = async (+ projectId: string,+ params: WebAnalyticsContentAutopilotOpportunitiesListParams,+ options?: RequestInit+): Promise<PaginatedContentAutopilotOpportunityListApi> => {+ return apiMutator<PaginatedContentAutopilotOpportunityListApi>(+ getWebAnalyticsContentAutopilotOpportunitiesListUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWebAnalyticsContentAutopilotOpportunitiesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/${id}/`+}++export const webAnalyticsContentAutopilotOpportunitiesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotOpportunityApi> => {+ return apiMutator<ContentAutopilotOpportunityApi>(+ getWebAnalyticsContentAutopilotOpportunitiesRetrieveUrl(projectId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWebAnalyticsContentAutopilotOpportunitiesDismissUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/${id}/dismiss/`+}++/**+ * Marks an opportunity as dismissed. It stays dismissed across refreshes, and list responses still include it with status `dismissed`.+ * @summary Dismiss a content opportunity+ */+export const webAnalyticsContentAutopilotOpportunitiesDismiss = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotOpportunityApi> => {+ return apiMutator<ContentAutopilotOpportunityApi>(+ getWebAnalyticsContentAutopilotOpportunitiesDismissUrl(projectId, id),+ {+ ...options,+ method: 'POST',+ }+ )+}++export const getWebAnalyticsContentAutopilotOpportunitiesRefreshUrl = (projectId: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/refresh/`+}++/**+ * Re-reads AI citation checks and updates the site's content opportunities. Makes no model calls.+ * @summary Refresh content opportunities+ */+export const webAnalyticsContentAutopilotOpportunitiesRefresh = async (+ projectId: string,+ contentAutopilotOpportunityRefreshRequestApi: ContentAutopilotOpportunityRefreshRequestApi,+ options?: RequestInit+): Promise<ContentAutopilotOpportunityApi[]> => {+ return apiMutator<ContentAutopilotOpportunityApi[]>(+ getWebAnalyticsContentAutopilotOpportunitiesRefreshUrl(projectId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(contentAutopilotOpportunityRefreshRequestApi),+ }+ )+}+export const getWebAnalyticsContentAutopilotProfilesListUrl = (projectId: string,params?: WebAnalyticsContentAutopilotProfilesListParamsdiff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.tsindex fe5ae606ccdd..ab1b88118deb 100644--- a/products/web_analytics/frontend/generated/api.zod.ts+++ b/products/web_analytics/frontend/generated/api.zod.ts@@ -353,6 +353,14 @@ export const WebAnalyticsBotRulesCreateBody = /* @__PURE__ */ zod.object({.describe('The conditions of this rule. Each one reads a single event property.'),})+/**+ * Re-reads AI citation checks and updates the site's content opportunities. Makes no model calls.+ * @summary Refresh content opportunities+ */+export const WebAnalyticsContentAutopilotOpportunitiesRefreshBody = /* @__PURE__ */ zod.object({+ profile_id: zod.uuid().describe('Site profile to refresh opportunities for.'),+})+export const webAnalyticsContentAutopilotProfilesCreateBodyNameMax = 255export const webAnalyticsContentAutopilotProfilesCreateBodyDomainMax = 2048diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex 727c39f1c70e..6b623c3af8b8 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -222,6 +222,18 @@ tools:List the project's own bot rules. Each rule names an event property, how to match it, a value, and the labelreported when it matches. Rules extend PostHog's built-in bot list, so `Is bot` (isLikelyBot), `Bot name`,and `Traffic category` reflect them everywhere — insights, web analytics, session filters, and SQL.+ web-analytics-content-autopilot-opportunities-dismiss:+ operation: web_analytics_content_autopilot_opportunities_dismiss+ enabled: false+ web-analytics-content-autopilot-opportunities-list:+ operation: web_analytics_content_autopilot_opportunities_list+ enabled: false+ web-analytics-content-autopilot-opportunities-refresh:+ operation: web_analytics_content_autopilot_opportunities_refresh+ enabled: false+ web-analytics-content-autopilot-opportunities-retrieve:+ operation: web_analytics_content_autopilot_opportunities_retrieve+ enabled: falseweb-analytics-content-autopilot-profiles-create:operation: web_analytics_content_autopilot_profiles_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4061e45b3d0c..f2a2ef824f1d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22341,6 +22341,42 @@ export namespace Schemas {token: string;}+ export interface ContentAutopilotEngineAnswer {+ /** Answer engine that gave the answer. */+ engine: string;+ /** The engine's most recent answer. Third-party text. */+ answer_text: string;+ /** When the answer was recorded, in ISO 8601. */+ checked_at: string;+ }++ export interface ContentAutopilotCitationGap {+ /** Successful citation checks in the lookback window. */+ checks: number;+ /** Checks whose answer cited the site. */+ cited_checks: number;+ /** Checks whose answer named the site's brand or cited the site. */+ mentioned_checks?: number;+ /** Share of checks that cited the site, from 0 to 1. */+ citation_rate: number;+ /** Engines that answered the prompt. */+ engines: string[];+ /** Engines that never cited the site in the window. */+ engines_not_citing: string[];+ /** Other sites' pages the engines cited, most frequent first. */+ competitor_urls: string[];+ /** Domains the engines cited instead, most frequent first. */+ competitor_domains: string[];+ /** Web searches the engines ran while answering. */+ engine_search_queries: string[];+ /** Site pages the engines cited when they did cite the site. */+ our_cited_urls: string[];+ /** Most recent answer per engine. */+ latest_answers: ContentAutopilotEngineAnswer[];+ /** When the prompt was last checked, in ISO 8601. */+ last_checked_at: string;+ }+export interface ContentAutopilotError {/** Stable machine-readable error code. */error_code: string;@@ -22416,6 +22452,16 @@ export namespace Schemas {content_package: ContentAutopilotPackage;}+ /**+ * * `ai_visibility_gap` - AI visibility gap+ */+ export type ContentAutopilotOpportunityKindEnum = typeof ContentAutopilotOpportunityKindEnum[keyof typeof ContentAutopilotOpportunityKindEnum];+++ export const ContentAutopilotOpportunityKindEnum = {+ AiVisibilityGap: 'ai_visibility_gap',+ } as const;+/*** * `new_content` - New content* * `page_improvement` - Page improvement@@ -22428,6 +22474,73 @@ export namespace Schemas {PageImprovement: 'page_improvement',} as const;+ /**+ * * `new` - New+ * * `dismissed` - Dismissed+ * * `queued` - Queued+ * * `drafted` - Drafted+ */+ export type ContentAutopilotOpportunityStatusEnum = typeof ContentAutopilotOpportunityStatusEnum[keyof typeof ContentAutopilotOpportunityStatusEnum];+++ export const ContentAutopilotOpportunityStatusEnum = {+ New: 'new',+ Dismissed: 'dismissed',+ Queued: 'queued',+ Drafted: 'drafted',+ } as const;++ export interface ContentAutopilotOpportunity {+ readonly id: string;+ /** Site profile this opportunity belongs to. */+ readonly profile_id: string;+ /**+ * Latest run that drafted this opportunity.+ * @nullable+ */+ readonly run_id: string | null;+ /**+ * Latest proposal drafted for this opportunity.+ * @nullable+ */+ readonly proposal_id: string | null;+ /** Type of visibility gap.+ *+ * * `ai_visibility_gap` - AI visibility gap */+ readonly kind: ContentAutopilotOpportunityKindEnum;+ /** The prompt the site isn't cited for. */+ readonly title: string;+ /** Priority from 0 to 1. Higher means a clearer, more consistent gap. */+ readonly score: number;+ /** `page_improvement` when the engines cited a site page for the prompt. Otherwise `new_content`, and drafting decides between a new page and an existing one.+ *+ * * `new_content` - New content+ * * `page_improvement` - Page improvement */+ readonly recommended_type: ContentAutopilotProposalProposalTypeEnum;+ /** Site page the engines cited for the prompt, to improve. Empty when no page was cited. */+ readonly target_url: string;+ /** Why this opportunity was selected. */+ evidence: ContentAutopilotEvidence[];+ /** Citation check results behind this opportunity. */+ gap: ContentAutopilotCitationGap;+ /** Where the opportunity is in the drafting workflow.+ *+ * * `new` - New+ * * `dismissed` - Dismissed+ * * `queued` - Queued+ * * `drafted` - Drafted */+ readonly status: ContentAutopilotOpportunityStatusEnum;+ /** When the citation data was last read. */+ readonly last_refreshed_at: string;+ readonly created_at: string;+ readonly updated_at: string;+ }++ export interface ContentAutopilotOpportunityRefreshRequest {+ /** Site profile to refresh opportunities for. */+ profile_id: string;+ }+/*** * `generating` - Generating* * `ready_for_review` - Ready for review@@ -64758,6 +64871,15 @@ export namespace Schemas {results: CommunitySkillList[];}+ export interface PaginatedContentAutopilotOpportunityList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ContentAutopilotOpportunity[];+ }+export interface PaginatedContentAutopilotProposalListList {count: number;/** @nullable */@@ -120722,6 +120844,21 @@ export namespace Schemas {days?: number;};+ export type WebAnalyticsContentAutopilotOpportunitiesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Site profile to list opportunities for.+ */+ profile_id: string;+ };+export type WebAnalyticsContentAutopilotProfilesListParams = {/*** Number of results to return per page.