: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): add content autopilot domain foundation (#91086)
Jordan Mryyana84a9d35435f
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex db45921172f0..6596644d2bca 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -104,6 +104,9 @@ rules:|CohortBackfillRun|CohortBackfillRunCohort|Comment+ |ContentAutopilotProposal+ |ContentAutopilotRun+ |ContentAutopilotSiteProfile|Conversation|ConversationRestoreToken|CoreMemory@@ -479,6 +482,9 @@ rules:|CohortBackfillRun|CohortBackfillRunCohort|Comment+ |ContentAutopilotProposal+ |ContentAutopilotRun+ |ContentAutopilotSiteProfile|Conversation|ConversationRestoreToken|CoreMemorydiff --git a/products/web_analytics/backend/content_autopilot/export.py b/products/web_analytics/backend/content_autopilot/export.pynew file mode 100644index 000000000000..df1ea6cd7c19--- /dev/null+++ b/products/web_analytics/backend/content_autopilot/export.py@@ -0,0 +1,69 @@+from pathlib import PurePosixPath++from django.db import transaction++from posthog.dataclasses import frozen+from posthog.models.team import Team++from products.web_analytics.backend.content_autopilot.lifecycle import ContentAutopilotLifecycleError, lock_proposal+from products.web_analytics.backend.models import ContentAutopilotProposal+++class ContentAutopilotExportError(Exception):+ pass+++@frozen+class ExportedProposal:+ filename: str+ markdown: str+ content_package: dict[str, object]+++MAX_EXPORT_FILENAME_CHARS = 255+++def _export_filename(*, file_path: object, proposal_id: str) -> str:+ fallback = f"{proposal_id}.md"+ if not isinstance(file_path, str):+ return fallback++ filename = PurePosixPath(file_path.replace("\\", "/")).name+ if (+ not filename+ or filename == ".."+ or len(filename) > MAX_EXPORT_FILENAME_CHARS+ or any(ord(character) < 32 or ord(character) == 127 for character in filename)+ ):+ return fallback+ return filename+++def export_proposal(*, team: Team, proposal_id: str) -> ExportedProposal:+ with transaction.atomic():+ try:+ locked_proposal = lock_proposal(team, proposal_id)+ except ContentAutopilotLifecycleError as error:+ raise ContentAutopilotExportError(str(error)) from error++ if locked_proposal.lifecycle_status != ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW:+ raise ContentAutopilotExportError("Only a proposal ready for review can be exported.")+ if locked_proposal.validation_report.get("passed") is not True:+ raise ContentAutopilotExportError("Resolve the failed validation checks before exporting this proposal.")+ if not locked_proposal.proposed_markdown.strip():+ raise ContentAutopilotExportError("Add Markdown to this proposal before exporting it.")+ if not isinstance(locked_proposal.content_package, dict):+ raise ContentAutopilotExportError(+ "This proposal does not have valid export details. Regenerate it and try again."+ )++ content_package = locked_proposal.content_package+ filename = _export_filename(file_path=content_package.get("file_path"), proposal_id=str(locked_proposal.id))+ locked_proposal.lifecycle_status = ContentAutopilotProposal.LifecycleStatus.EXPORTED+ locked_proposal.save(update_fields=["lifecycle_status", "updated_at"])++ return ExportedProposal(+ filename=filename,+ markdown=locked_proposal.proposed_markdown,+ content_package=content_package,+ )diff --git a/products/web_analytics/backend/content_autopilot/lifecycle.py b/products/web_analytics/backend/content_autopilot/lifecycle.pynew file mode 100644index 000000000000..8f0ee25bcf2c--- /dev/null+++ b/products/web_analytics/backend/content_autopilot/lifecycle.py@@ -0,0 +1,149 @@+from django.db import transaction+from django.utils import timezone++from posthog.models.team import Team++from products.web_analytics.backend.models import (+ ContentAutopilotProposal,+ ContentAutopilotRun,+ ContentAutopilotSiteProfile,+)+from products.web_analytics.backend.models.content_autopilot import default_content_autopilot_validation_report+++class ContentAutopilotLifecycleError(Exception):+ pass+++MAX_PROPOSAL_MARKDOWN_CHARS = 500_000++ACTIVE_RUN_STATUSES = {ContentAutopilotRun.RunStatus.PENDING, ContentAutopilotRun.RunStatus.GENERATING}+++def canonical_team_id(team: Team) -> int:+ return team.parent_team_id or team.id+++def lock_run(team: Team, run_id: str) -> ContentAutopilotRun:+ try:+ return (+ ContentAutopilotRun.objects.for_team(canonical_team_id(team), canonical=True)+ .select_for_update()+ .get(id=run_id)+ )+ except ContentAutopilotRun.DoesNotExist as error:+ raise ContentAutopilotLifecycleError("That content run could not be found.") from error+++def lock_proposal(team: Team, proposal_id: str) -> ContentAutopilotProposal:+ try:+ return (+ ContentAutopilotProposal.objects.for_team(canonical_team_id(team), canonical=True)+ .select_for_update()+ .get(id=proposal_id)+ )+ except ContentAutopilotProposal.DoesNotExist as error:+ raise ContentAutopilotLifecycleError("That proposal could not be found.") from error+++def start_run(*, team: Team, profile_id: str, triggered_by_id: int | None) -> ContentAutopilotRun:+ team_id = canonical_team_id(team)+ with transaction.atomic():+ try:+ profile = (+ ContentAutopilotSiteProfile.objects.for_team(team_id, canonical=True)+ .select_for_update()+ .get(id=profile_id)+ )+ except ContentAutopilotSiteProfile.DoesNotExist as error:+ raise ContentAutopilotLifecycleError("Select a site before starting a content run.") from error++ if (+ ContentAutopilotRun.objects.for_team(team_id, canonical=True)+ .filter(profile=profile, run_status__in=ACTIVE_RUN_STATUSES)+ .exists()+ ):+ raise ContentAutopilotLifecycleError("A content run is already in progress for this site.")++ return ContentAutopilotRun.objects.for_team(team_id, canonical=True).create(+ team=team,+ profile=profile,+ run_status=ContentAutopilotRun.RunStatus.PENDING,+ input_snapshot={+ "captured_at": timezone.now().isoformat(),+ "domain": profile.domain,+ "search_console_connected": profile.search_console_enabled,+ "confidence": "standard" if profile.search_console_enabled else "lower",+ "source_urls": profile.source_urls,+ "content_boundaries": profile.content_boundaries,+ "brand_rules": profile.brand_rules,+ },+ triggered_by_id=triggered_by_id,+ )+++def cancel_run(*, team: Team, run_id: str) -> ContentAutopilotRun:+ with transaction.atomic():+ locked_run = lock_run(team, run_id)+ if locked_run.run_status not in ACTIVE_RUN_STATUSES:+ raise ContentAutopilotLifecycleError("Only a pending or generating run can be canceled.")+ locked_run.run_status = ContentAutopilotRun.RunStatus.CANCELED+ locked_run.completed_at = timezone.now()+ locked_run.save(update_fields=["run_status", "completed_at", "updated_at"])+ return locked_run+++def reject_proposal(*, team: Team, proposal_id: str) -> ContentAutopilotProposal:+ with transaction.atomic():+ locked_proposal = lock_proposal(team, proposal_id)+ if locked_proposal.lifecycle_status != ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW:+ raise ContentAutopilotLifecycleError("Only a proposal ready for review can be rejected.")+ locked_proposal.lifecycle_status = ContentAutopilotProposal.LifecycleStatus.REJECTED+ locked_proposal.save(update_fields=["lifecycle_status", "updated_at"])+ return locked_proposal+++def _reset_for_regeneration(proposal: ContentAutopilotProposal) -> list[str]:+ proposal.lifecycle_status = ContentAutopilotProposal.LifecycleStatus.GENERATING+ proposal.validation_report = default_content_autopilot_validation_report()+ return ["lifecycle_status", "validation_report"]+++def regenerate_proposal(*, team: Team, proposal_id: str) -> ContentAutopilotProposal:+ with transaction.atomic():+ locked_proposal = lock_proposal(team, proposal_id)+ if locked_proposal.lifecycle_status not in {+ ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW,+ ContentAutopilotProposal.LifecycleStatus.FAILED,+ }:+ raise ContentAutopilotLifecycleError("Only proposals ready for review or failed can be regenerated.")+ locked_proposal.save(update_fields=[*_reset_for_regeneration(locked_proposal), "updated_at"])+ return locked_proposal+++def edit_proposal(+ *,+ team: Team,+ proposal_id: str,+ proposed_markdown: str,+ content_package: dict[str, object],+) -> ContentAutopilotProposal:+ if len(proposed_markdown) > MAX_PROPOSAL_MARKDOWN_CHARS:+ raise ContentAutopilotLifecycleError(+ f"Proposal Markdown must be {MAX_PROPOSAL_MARKDOWN_CHARS:,} characters or fewer."+ )+ with transaction.atomic():+ locked_proposal = lock_proposal(team, proposal_id)+ if locked_proposal.lifecycle_status != ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW:+ raise ContentAutopilotLifecycleError("Only a proposal ready for review can be edited.")+ locked_proposal.proposed_markdown = proposed_markdown+ locked_proposal.content_package = {key: value for key, value in content_package.items() if key != "markdown"}+ locked_proposal.save(+ update_fields=[+ "proposed_markdown",+ "content_package",+ *_reset_for_regeneration(locked_proposal),+ "updated_at",+ ]+ )+ return locked_proposaldiff --git a/products/web_analytics/backend/migrations/0009_content_autopilot.py b/products/web_analytics/backend/migrations/0009_content_autopilot.pynew file mode 100644index 000000000000..b2f30a2f9f79--- /dev/null+++ b/products/web_analytics/backend/migrations/0009_content_autopilot.py@@ -0,0 +1,210 @@+# Generated by Django 5.2.17 on 2026-08-31 19:04++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt++import products.web_analytics.backend.models.content_autopilot+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1245_duckgres_sink_schema_state"),+ ("web_analytics", "0008_savedheatmap_source"),+ ]++ operations = [+ migrations.CreateModel(+ name="ContentAutopilotSiteProfile",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(blank=True, default="", max_length=255)),+ ("domain", models.URLField(max_length=2048)),+ ("source_urls", models.JSONField(default=list)),+ ("content_boundaries", models.JSONField(default=list)),+ ("brand_rules", models.JSONField(default=list)),+ ("search_console_enabled", models.BooleanField(default=False)),+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),+ ("updated_by_id", models.BigIntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_contentautopilotsiteprofile",+ },+ ),+ migrations.CreateModel(+ name="ContentAutopilotRun",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "run_status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("generating", "Generating"),+ ("ready_for_review", "Ready for review"),+ ("completed", "Completed"),+ ("canceled", "Canceled"),+ ("failed", "Failed"),+ ],+ default="pending",+ max_length=32,+ ),+ ),+ ("input_snapshot", models.JSONField(default=dict)),+ ("errors", models.JSONField(default=list)),+ ("triggered_by_id", models.BigIntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("completed_at", models.DateTimeField(blank=True, null=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "profile",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="runs",+ to="web_analytics.contentautopilotsiteprofile",+ ),+ ),+ ],+ options={+ "db_table": "posthog_contentautopilotrun",+ },+ ),+ migrations.CreateModel(+ name="ContentAutopilotProposal",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "proposal_type",+ models.CharField(+ choices=[+ ("new_content", "New content"),+ ("page_improvement", "Page improvement"),+ ],+ max_length=32,+ ),+ ),+ (+ "lifecycle_status",+ models.CharField(+ choices=[+ ("generating", "Generating"),+ ("ready_for_review", "Ready for review"),+ ("rejected", "Rejected"),+ ("exported", "Exported"),+ ("failed", "Failed"),+ ],+ default="generating",+ max_length=32,+ ),+ ),+ ("title", models.CharField(max_length=512)),+ (+ "target_query",+ models.CharField(blank=True, default="", max_length=512),+ ),+ (+ "target_url",+ models.URLField(blank=True, default="", max_length=2048),+ ),+ ("evidence", models.JSONField(default=list)),+ (+ "validation_report",+ models.JSONField(+ default=products.web_analytics.backend.models.content_autopilot.default_content_autopilot_validation_report+ ),+ ),+ (+ "content_package",+ models.JSONField(+ default=products.web_analytics.backend.models.content_autopilot.default_content_autopilot_package+ ),+ ),+ ("original_markdown", models.TextField(blank=True, default="")),+ ("proposed_markdown", models.TextField(blank=True, default="")),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "run",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="proposals",+ to="web_analytics.contentautopilotrun",+ ),+ ),+ ],+ options={+ "db_table": "posthog_contentautopilotproposal",+ "indexes": [+ models.Index(+ fields=["team", "lifecycle_status", "-created_at"],+ name="content_auto_prop_status",+ )+ ],+ },+ ),+ migrations.AddConstraint(+ model_name="contentautopilotsiteprofile",+ constraint=models.UniqueConstraint(fields=("team", "domain"), name="content_auto_profile_team_domain"),+ ),+ migrations.AddIndex(+ model_name="contentautopilotrun",+ index=models.Index(fields=["team", "-created_at"], name="content_auto_run_team_created"),+ ),+ ]diff --git a/products/web_analytics/backend/migrations/0010_contentautopilotrun_content_auto_run_active.py b/products/web_analytics/backend/migrations/0010_contentautopilotrun_content_auto_run_active.pynew file mode 100644index 000000000000..bee5de3486e0--- /dev/null+++ b/products/web_analytics/backend/migrations/0010_contentautopilotrun_content_auto_run_active.py@@ -0,0 +1,22 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("web_analytics", "0009_content_autopilot"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="contentautopilotrun",+ index=models.Index(+ condition=models.Q(("run_status__in", ["pending", "generating"])),+ fields=["profile"],+ name="content_auto_run_active",+ ),+ ),+ ]diff --git a/products/web_analytics/backend/migrations/max_migration.txt b/products/web_analytics/backend/migrations/max_migration.txtindex 8fdea0afc02e..a4ad2e2ab165 100644--- a/products/web_analytics/backend/migrations/max_migration.txt+++ b/products/web_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_savedheatmap_source+0010_contentautopilotrun_content_auto_run_activediff --git a/products/web_analytics/backend/models/__init__.py b/products/web_analytics/backend/models/__init__.pyindex 445364343c87..9816a12b9f14 100644--- a/products/web_analytics/backend/models/__init__.py+++ b/products/web_analytics/backend/models/__init__.py@@ -1,3 +1,4 @@+from .content_autopilot import ContentAutopilotProposal, ContentAutopilotRun, ContentAutopilotSiteProfilefrom .heatmap_saved import HeatmapSnapshot, SavedHeatmapfrom .web_analytics_achievement_progress import WebAnalyticsAchievementProgressfrom .web_analytics_filter_preset import WebAnalyticsFilterPreset@@ -8,6 +9,9 @@ from .web_analytics_visit import WebAnalyticsVisit__all__ = ["HeatmapSnapshot","SavedHeatmap",+ "ContentAutopilotProposal",+ "ContentAutopilotRun",+ "ContentAutopilotSiteProfile","WebAnalyticsAchievementProgress","WebAnalyticsFilterPreset","WebAnalyticsInteraction",diff --git a/products/web_analytics/backend/models/content_autopilot.py b/products/web_analytics/backend/models/content_autopilot.pynew file mode 100644index 000000000000..b72f40dbabe9--- /dev/null+++ b/products/web_analytics/backend/models/content_autopilot.py@@ -0,0 +1,153 @@+from collections.abc import Iterable+from typing import Any++from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++def _parent_team_id(child: models.Model, relation: str, update_fields: Iterable[str] | None) -> int | None:+ touched = None if update_fields is None else set(update_fields)+ if not (child._state.adding or touched is None or touched & {relation, f"{relation}_id", "team", "team_id"}):+ return None+ return getattr(child, relation).team_id+++def default_content_autopilot_package() -> dict[str, object]:+ return {+ "file_path": "",+ "title": "",+ "description": "",+ "slug": "",+ "frontmatter": [],+ "internal_links": [],+ "source_notes": [],+ }+++def default_content_autopilot_validation_report() -> dict[str, object]:+ return {"passed": False, "checks": []}+++class ContentAutopilotSiteProfile(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ name = models.CharField(max_length=255, blank=True, default="")+ domain = models.URLField(max_length=2048)+ source_urls = models.JSONField(default=list)+ content_boundaries = models.JSONField(default=list)+ brand_rules = models.JSONField(default=list)+ search_console_enabled = models.BooleanField(default=False)+ created_by_id = models.BigIntegerField(null=True, blank=True)+ updated_by_id = models.BigIntegerField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_contentautopilotsiteprofile"+ constraints = [+ models.UniqueConstraint(fields=["team", "domain"], name="content_auto_profile_team_domain"),+ ]+++class ContentAutopilotRun(TeamScopedRootMixin, UUIDModel):+ class RunStatus(models.TextChoices):+ PENDING = "pending", "Pending"+ GENERATING = "generating", "Generating"+ READY_FOR_REVIEW = "ready_for_review", "Ready for review"+ COMPLETED = "completed", "Completed"+ CANCELED = "canceled", "Canceled"+ FAILED = "failed", "Failed"++ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ profile = models.ForeignKey(ContentAutopilotSiteProfile, on_delete=models.CASCADE, related_name="runs")+ run_status = models.CharField(max_length=32, choices=RunStatus.choices, default=RunStatus.PENDING)+ input_snapshot = models.JSONField(default=dict)+ errors = models.JSONField(default=list)+ triggered_by_id = models.BigIntegerField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ completed_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ db_table = "posthog_contentautopilotrun"+ indexes = [+ models.Index(fields=["team", "-created_at"], name="content_auto_run_team_created"),+ models.Index(+ fields=["profile"],+ condition=models.Q(run_status__in=["pending", "generating"]),+ name="content_auto_run_active",+ ),+ ]++ def save(self, *args: Any, **kwargs: Any) -> None:+ parent_team_id = _parent_team_id(self, "profile", kwargs.get("update_fields"))+ if parent_team_id is not None:+ if self.team_id is not None and self.team_id != parent_team_id:+ raise ValueError("ContentAutopilotRun must belong to the same team as its profile.")+ self.team_id = parent_team_id+ super().save(*args, **kwargs)+++class ContentAutopilotProposal(TeamScopedRootMixin, UUIDModel):+ class ProposalType(models.TextChoices):+ NEW_CONTENT = "new_content", "New content"+ PAGE_IMPROVEMENT = "page_improvement", "Page improvement"++ class LifecycleStatus(models.TextChoices):+ GENERATING = "generating", "Generating"+ READY_FOR_REVIEW = "ready_for_review", "Ready for review"+ REJECTED = "rejected", "Rejected"+ EXPORTED = "exported", "Exported"+ FAILED = "failed", "Failed"++ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ run = models.ForeignKey(ContentAutopilotRun, on_delete=models.CASCADE, related_name="proposals")+ proposal_type = models.CharField(max_length=32, choices=ProposalType.choices)+ lifecycle_status = models.CharField(+ max_length=32,+ choices=LifecycleStatus.choices,+ default=LifecycleStatus.GENERATING,+ )+ title = models.CharField(max_length=512)+ target_query = models.CharField(max_length=512, blank=True, default="")+ target_url = models.URLField(max_length=2048, blank=True, default="")+ evidence = models.JSONField(default=list)+ validation_report = models.JSONField(default=default_content_autopilot_validation_report)+ content_package = models.JSONField(default=default_content_autopilot_package)+ original_markdown = models.TextField(blank=True, default="")+ proposed_markdown = models.TextField(blank=True, default="")+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_contentautopilotproposal"+ indexes = [+ models.Index(fields=["team", "lifecycle_status", "-created_at"], name="content_auto_prop_status"),+ ]++ def save(self, *args: Any, **kwargs: Any) -> None:+ parent_team_id = _parent_team_id(self, "run", kwargs.get("update_fields"))+ if parent_team_id is not None:+ if self.team_id is not None and self.team_id != parent_team_id:+ raise ValueError("ContentAutopilotProposal must belong to the same team as its run.")+ self.team_id = parent_team_id+ super().save(*args, **kwargs)diff --git a/products/web_analytics/backend/test/content_autopilot_test_utils.py b/products/web_analytics/backend/test/content_autopilot_test_utils.pynew file mode 100644index 000000000000..3c7dc1a92b9c--- /dev/null+++ b/products/web_analytics/backend/test/content_autopilot_test_utils.py@@ -0,0 +1,80 @@+from posthog.models.team import Team++from products.web_analytics.backend.models import (+ ContentAutopilotProposal,+ ContentAutopilotRun,+ ContentAutopilotSiteProfile,+)++UNSET_CONTENT_PACKAGE = object()+++def create_content_autopilot_profile(+ team: Team,+ *,+ domain: str = "https://example.com",+ search_console_enabled: bool = False,+) -> ContentAutopilotSiteProfile:+ return ContentAutopilotSiteProfile.objects.for_team(team.id).create(+ team=team,+ name="Example",+ domain=domain,+ source_urls=[f"{domain}/sitemap.xml"],+ content_boundaries=["/"],+ search_console_enabled=search_console_enabled,+ )+++def create_content_autopilot_run(+ team: Team,+ profile: ContentAutopilotSiteProfile,+ *,+ run_status: str = ContentAutopilotRun.RunStatus.PENDING,+) -> ContentAutopilotRun:+ return ContentAutopilotRun.objects.for_team(team.id).create(+ team=team,+ profile=profile,+ run_status=run_status,+ )+++def create_content_autopilot_proposal(+ team: Team,+ run: ContentAutopilotRun,+ *,+ proposal_type: str = ContentAutopilotProposal.ProposalType.PAGE_IMPROVEMENT,+ lifecycle_status: str = ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW,+ file_path: object = "content/guides/example.md",+ validation_passed: bool = True,+ markdown: str = "# Improved guide\n\nUseful content.",+ content_package: object = UNSET_CONTENT_PACKAGE,+) -> ContentAutopilotProposal:+ default_package: dict[str, object] = {+ "file_path": file_path,+ "title": "Improved guide",+ "description": "A clearer guide.",+ "slug": "example",+ "frontmatter": [{"key": "title", "value": "Improved guide"}],+ "internal_links": ["https://example.com/docs"],+ "source_notes": [],+ }+ return ContentAutopilotProposal.objects.for_team(team.id).create(+ team=team,+ run=run,+ proposal_type=proposal_type,+ lifecycle_status=lifecycle_status,+ title="Improve the example guide",+ target_url="https://example.com/guides/example",+ evidence=[+ {+ "opportunity_kind": "poor_ctr",+ "explanation": "The page ranks for this query but is clicked rarely.",+ "page_url": "https://example.com/guides/example",+ "query": "example guide",+ "metrics": {"impressions": 1240, "clicks": 21, "click_through_rate": 0.017},+ }+ ],+ validation_report={"passed": validation_passed, "checks": []},+ content_package=default_package if content_package is UNSET_CONTENT_PACKAGE else content_package,+ proposed_markdown=markdown,+ )diff --git a/products/web_analytics/backend/test/test_content_autopilot_export.py b/products/web_analytics/backend/test/test_content_autopilot_export.pynew file mode 100644index 000000000000..adbeb39d39f9--- /dev/null+++ b/products/web_analytics/backend/test/test_content_autopilot_export.py@@ -0,0 +1,118 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.team import Team++from products.web_analytics.backend.content_autopilot.export import ContentAutopilotExportError, export_proposal+from products.web_analytics.backend.models import ContentAutopilotProposal+from products.web_analytics.backend.models.content_autopilot import default_content_autopilot_package+from products.web_analytics.backend.test.content_autopilot_test_utils import (+ UNSET_CONTENT_PACKAGE,+ create_content_autopilot_profile,+ create_content_autopilot_proposal,+ create_content_autopilot_run,+)+++class TestContentAutopilotExport(BaseTest):+ @parameterized.expand(+ [+ ("nested path", "content/guides/example.md", "example.md"),+ ("windows path", "content\\guides\\example.md", "example.md"),+ ("empty basename", "/", None),+ ("dot basename", ".", None),+ ("parent basename", "..", None),+ ("oversized basename", f"{'x' * 256}.md", None),+ ("control character", "example\nname.md", None),+ ("non-string path", 42, None),+ ("missing path", None, None),+ ]+ )+ def test_export_returns_markdown_and_marks_proposal_exported(+ self, _name: str, file_path: object, expected_filename: str | None+ ) -> None:+ profile = create_content_autopilot_profile(self.team)+ proposal = create_content_autopilot_proposal(+ self.team,+ create_content_autopilot_run(self.team, profile),+ file_path=file_path,+ )++ exported_proposal = export_proposal(team=self.team, proposal_id=str(proposal.id))++ self.assertEqual(exported_proposal.filename, expected_filename or f"{proposal.id}.md")+ self.assertEqual(exported_proposal.markdown, proposal.proposed_markdown)+ self.assertEqual(exported_proposal.content_package, proposal.content_package)+ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.EXPORTED)++ @parameterized.expand(+ [+ (+ "failed validation",+ False,+ "# Valid Markdown",+ UNSET_CONTENT_PACKAGE,+ "Resolve the failed validation checks",+ ),+ ("missing Markdown", True, "", UNSET_CONTENT_PACKAGE, "Add Markdown to this proposal"),+ ("blank Markdown", True, " \n ", UNSET_CONTENT_PACKAGE, "Add Markdown to this proposal"),+ ("list package", True, "# Valid Markdown", ["file_path"], "does not have valid export details"),+ ("string package", True, "# Valid Markdown", "file_path", "does not have valid export details"),+ ]+ )+ def test_export_rejects_invalid_proposals(+ self, _name: str, validation_passed: bool, markdown: str, content_package: object, expected_error: str+ ) -> None:+ profile = create_content_autopilot_profile(self.team)+ proposal = create_content_autopilot_proposal(+ self.team,+ create_content_autopilot_run(self.team, profile),+ validation_passed=validation_passed,+ markdown=markdown,+ content_package=content_package,+ )++ with self.assertRaisesRegex(ContentAutopilotExportError, expected_error):+ export_proposal(team=self.team, proposal_id=str(proposal.id))++ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW)++ def test_export_refuses_a_second_export_of_the_same_proposal(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ proposal = create_content_autopilot_proposal(self.team, create_content_autopilot_run(self.team, profile))++ export_proposal(team=self.team, proposal_id=str(proposal.id))++ with self.assertRaisesRegex(ContentAutopilotExportError, "ready for review can be exported"):+ export_proposal(team=self.team, proposal_id=str(proposal.id))++ def test_export_refuses_a_proposal_belonging_to_another_team(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ proposal = create_content_autopilot_proposal(self.team, create_content_autopilot_run(self.team, profile))+ other_team = Team.objects.create(organization=self.organization, name="Other project")++ with self.assertRaisesRegex(ContentAutopilotExportError, "could not be found"):+ export_proposal(team=other_team, proposal_id=str(proposal.id))++ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW)++ def test_export_falls_back_to_a_safe_filename_for_an_unfilled_package(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ proposal = ContentAutopilotProposal.objects.for_team(self.team.id).create(+ team=self.team,+ run=create_content_autopilot_run(self.team, profile),+ proposal_type=ContentAutopilotProposal.ProposalType.NEW_CONTENT,+ lifecycle_status=ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW,+ title="Draft without a generated package",+ validation_report={"passed": True, "checks": []},+ proposed_markdown="# Draft",+ )++ exported_proposal = export_proposal(team=self.team, proposal_id=str(proposal.id))++ self.assertEqual(exported_proposal.content_package, default_content_autopilot_package())+ self.assertEqual(exported_proposal.filename, f"{proposal.id}.md")diff --git a/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py b/products/web_analytics/backend/test/test_content_autopilot_lifecycle.pynew file mode 100644index 000000000000..1e00cf3c065e--- /dev/null+++ b/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py@@ -0,0 +1,181 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.scoping.manager import TeamScopeError+from posthog.models.team import Team++from products.web_analytics.backend.content_autopilot.lifecycle import (+ MAX_PROPOSAL_MARKDOWN_CHARS,+ ContentAutopilotLifecycleError,+ cancel_run,+ edit_proposal,+ regenerate_proposal,+ reject_proposal,+ start_run,+)+from products.web_analytics.backend.models import (+ ContentAutopilotProposal,+ ContentAutopilotRun,+ ContentAutopilotSiteProfile,+)+from products.web_analytics.backend.test.content_autopilot_test_utils import (+ create_content_autopilot_profile,+ create_content_autopilot_proposal,+ create_content_autopilot_run,+)+++class TestContentAutopilotLifecycle(BaseTest):+ def test_models_fail_closed_and_explicit_scopes_do_not_cross_teams(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ run = create_content_autopilot_run(self.team, profile)+ create_content_autopilot_proposal(self.team, run)++ other_team = Team.objects.create(organization=self.organization, name="Other project")+ create_content_autopilot_profile(other_team, domain="https://other.example")++ for model in [+ ContentAutopilotSiteProfile,+ ContentAutopilotRun,+ ContentAutopilotProposal,+ ]:+ with self.subTest(model=model.__name__), self.assertRaises(TeamScopeError):+ model.objects.count()++ self.assertEqual(ContentAutopilotSiteProfile.objects.for_team(self.team.id).count(), 1)+ self.assertEqual(ContentAutopilotSiteProfile.objects.for_team(other_team.id).count(), 1)++ with self.assertRaisesRegex(ValueError, "same team as its profile"):+ create_content_autopilot_run(other_team, profile)+ with self.assertRaisesRegex(ValueError, "same team as its run"):+ create_content_autopilot_proposal(other_team, run)++ proposal = create_content_autopilot_proposal(self.team, run)+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "could not be found"):+ reject_proposal(team=other_team, proposal_id=str(proposal.id))+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "could not be found"):+ cancel_run(team=other_team, run_id=str(run.id))+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "Select a site"):+ start_run(team=other_team, profile_id=str(profile.id), triggered_by_id=self.user.id)+ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW)++ def test_each_site_has_its_own_active_run_boundary(self) -> None:+ first_profile = create_content_autopilot_profile(self.team, search_console_enabled=True)+ second_profile = create_content_autopilot_profile(self.team, domain="https://docs.example.com")++ first_run = start_run(team=self.team, profile_id=str(first_profile.id), triggered_by_id=self.user.id)++ self.assertEqual(first_run.input_snapshot["domain"], "https://example.com")+ self.assertEqual(first_run.input_snapshot["confidence"], "standard")+ self.assertEqual(first_run.input_snapshot["source_urls"], first_profile.source_urls)+ self.assertEqual(first_run.input_snapshot["content_boundaries"], first_profile.content_boundaries)+ with self.assertRaises(ContentAutopilotLifecycleError, msg="a duplicate run must not be created"):+ start_run(team=self.team, profile_id=str(first_profile.id), triggered_by_id=self.user.id)++ second_run = start_run(team=self.team, profile_id=str(second_profile.id), triggered_by_id=self.user.id)+ self.assertEqual(second_run.profile_id, second_profile.id)++ def test_cancel_and_reject_only_allow_reviewable_states(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ run = create_content_autopilot_run(self.team, profile)+ proposal = create_content_autopilot_proposal(self.team, run)++ canceled = cancel_run(team=self.team, run_id=str(run.id))+ rejected = reject_proposal(team=self.team, proposal_id=str(proposal.id))++ self.assertEqual(canceled.run_status, ContentAutopilotRun.RunStatus.CANCELED)+ self.assertIsNotNone(canceled.completed_at)+ self.assertEqual(rejected.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.REJECTED)+ with self.assertRaises(ContentAutopilotLifecycleError):+ cancel_run(team=self.team, run_id=str(canceled.id))+ with self.assertRaises(ContentAutopilotLifecycleError):+ reject_proposal(team=self.team, proposal_id=str(rejected.id))++ def test_edit_keeps_markdown_single_sourced_and_invalidates_validation(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ proposal = create_content_autopilot_proposal(self.team, create_content_autopilot_run(self.team, profile))++ edited = edit_proposal(+ team=self.team,+ proposal_id=str(proposal.id),+ proposed_markdown="# Reviewed draft",+ content_package={**proposal.content_package, "markdown": "# Stale draft"},+ )++ self.assertNotIn("markdown", edited.content_package)+ self.assertEqual(edited.proposed_markdown, "# Reviewed draft")+ self.assertEqual(edited.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.GENERATING)+ self.assertEqual(edited.validation_report, {"passed": False, "checks": []})++ @parameterized.expand(+ [+ ("ready_for_review", ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW),+ ("failed", ContentAutopilotProposal.LifecycleStatus.FAILED),+ ]+ )+ def test_regeneration_accepts_reviewed_or_failed_drafts(self, _name: str, lifecycle_status: str) -> None:+ regenerated = regenerate_proposal(+ team=self.team, proposal_id=str(self._proposal_with_status(lifecycle_status).id)+ )++ self.assertEqual(regenerated.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.GENERATING)+ self.assertEqual(regenerated.validation_report, {"passed": False, "checks": []})++ @parameterized.expand(+ [+ ("rejected", ContentAutopilotProposal.LifecycleStatus.REJECTED),+ ("generating", ContentAutopilotProposal.LifecycleStatus.GENERATING),+ ]+ )+ def test_regeneration_refuses_other_drafts(self, _name: str, lifecycle_status: str) -> None:+ with self.assertRaises(ContentAutopilotLifecycleError):+ regenerate_proposal(team=self.team, proposal_id=str(self._proposal_with_status(lifecycle_status).id))++ @parameterized.expand(+ [+ (+ "rejected draft",+ ContentAutopilotProposal.LifecycleStatus.REJECTED,+ "# Reviewed draft",+ "ready for review can be edited",+ ),+ (+ "generating draft",+ ContentAutopilotProposal.LifecycleStatus.GENERATING,+ "# Reviewed draft",+ "ready for review can be edited",+ ),+ (+ "oversized Markdown",+ ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW,+ "x" * (MAX_PROPOSAL_MARKDOWN_CHARS + 1),+ "characters or fewer",+ ),+ ]+ )+ def test_edit_refuses_invalid_requests(+ self, _name: str, lifecycle_status: str, proposed_markdown: str, expected_error: str+ ) -> None:+ proposal = self._proposal_with_status(lifecycle_status)++ with self.assertRaisesRegex(ContentAutopilotLifecycleError, expected_error):+ edit_proposal(+ team=self.team,+ proposal_id=str(proposal.id),+ proposed_markdown=proposed_markdown,+ content_package=proposal.content_package,+ )++ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, lifecycle_status)+ self.assertEqual(proposal.proposed_markdown, "# Improved guide\n\nUseful content.")++ def _proposal_with_status(self, lifecycle_status: str) -> ContentAutopilotProposal:+ profile = create_content_autopilot_profile(self.team)+ return create_content_autopilot_proposal(+ self.team,+ create_content_autopilot_run(self.team, profile),+ lifecycle_status=lifecycle_status,+ )