: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 research and validation (#109185)
Jordan Mryyan689c36b6a55d
diff --git a/products/web_analytics/backend/content_autopilot/research.py b/products/web_analytics/backend/content_autopilot/research.pynew file mode 100644index 000000000000..e3cca42a4bb2--- /dev/null+++ b/products/web_analytics/backend/content_autopilot/research.py@@ -0,0 +1,320 @@+import re+import time+from html.parser import HTMLParser+from typing import Any, Literal+from urllib.parse import urlparse++from posthog.dataclasses import frozen+from posthog.egress.firecrawl.client import (+ MAX_SEARCH_QUERY_CHARS,+ FirecrawlNotConfigured,+ FirecrawlScrapeFailed,+ FirecrawlSearchFailed,+ scrape,+ search,+)+from posthog.egress.firecrawl.transport import FirecrawlEgressBudgetExhausted+from posthog.egress.limiter.policies import Priority+from posthog.security.llm_prompt_sanitization import strip_llm_framing_markers+from posthog.security.url_validation import strip_userinfo++from products.web_analytics.backend.content_autopilot.site_discovery import has_same_public_site, site_host+from products.web_analytics.backend.public_url_fetch import PublicUrlFetchError, fetch_public_url++MAX_DOCUMENT_CHARS = 40_000+MAX_DOCUMENT_BYTES = 2 * 1024 * 1024+MAX_COMPETITOR_PAGES = 4+MAX_NAMED_COMPETITOR_PAGES = 3+MAX_LINK_CANDIDATES = 60+FETCH_SECONDS = 20.0+FIRECRAWL_SOURCE = "content_autopilot"+MAX_SITE_SEARCH_RESULTS = 10++DocumentOrigin = Literal["site", "competitor"]+++@frozen+class SourceDocument:+ url: str+ title: str+ text: str+ origin: DocumentOrigin++ def to_dict(self) -> dict[str, str]:+ return {"url": self.url, "title": self.title, "text": self.text, "origin": self.origin}++ @classmethod+ def from_dict(cls, value: dict[str, Any]) -> "SourceDocument":+ origin: DocumentOrigin = "site" if value.get("origin") == "site" else "competitor"+ return cls(url=str(value["url"]), title=str(value.get("title", "")), text=str(value["text"]), origin=origin)+++@frozen+class ResearchBundle:+ prompt: str+ target_url: str+ documents: tuple[SourceDocument, ...]+ link_candidates: tuple[str, ...]+ skipped: tuple[str, ...]++ @property+ def site_documents(self) -> tuple[SourceDocument, ...]:+ return tuple(document for document in self.documents if document.origin == "site")++ @property+ def competitor_documents(self) -> tuple[SourceDocument, ...]:+ return tuple(document for document in self.documents if document.origin == "competitor")++ def to_dict(self) -> dict[str, Any]:+ return {+ "prompt": self.prompt,+ "target_url": self.target_url,+ "documents": [document.to_dict() for document in self.documents],+ "link_candidates": list(self.link_candidates),+ "skipped": list(self.skipped),+ }++ @classmethod+ def from_dict(cls, value: dict[str, Any]) -> "ResearchBundle":+ return cls(+ prompt=str(value.get("prompt", "")),+ target_url=str(value.get("target_url", "")),+ documents=tuple(SourceDocument.from_dict(document) for document in value.get("documents", [])),+ link_candidates=tuple(str(url) for url in value.get("link_candidates", [])),+ skipped=tuple(str(note) for note in value.get("skipped", [])),+ )+++@frozen+class _PageText:+ title: str+ text: str+++@frozen+class _FetchedBody:+ content_type: str+ body: str+++class _TextExtractor(HTMLParser):+ _SKIPPED_TAGS = frozenset({"script", "style", "noscript", "nav", "header", "footer", "aside", "svg", "form"})+ _BLOCK_TAGS = frozenset({"p", "div", "section", "article", "li", "tr", "br", "h1", "h2", "h3", "h4", "h5", "h6"})+ _MAIN_TAGS = frozenset({"main", "article"})++ def __init__(self) -> None:+ super().__init__()+ self.title = ""+ self._parts: list[str] = []+ self._main_parts: list[str] = []+ self._skip_depth = 0+ self._main_depth = 0+ self._inside_title = False++ def _append(self, text: str) -> None:+ self._parts.append(text)+ if self._main_depth:+ self._main_parts.append(text)++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ if tag in self._SKIPPED_TAGS:+ self._skip_depth += 1+ elif tag == "title":+ self._inside_title = True+ elif tag in self._BLOCK_TAGS or tag in self._MAIN_TAGS:+ if tag in self._MAIN_TAGS:+ self._main_depth += 1+ self._append("\n")+ if tag in {"h1", "h2", "h3"}:+ self._append("#" * int(tag[1]) + " ")++ def handle_endtag(self, tag: str) -> None:+ if tag in self._SKIPPED_TAGS and self._skip_depth:+ self._skip_depth -= 1+ elif tag == "title":+ self._inside_title = False+ elif tag in self._MAIN_TAGS and self._main_depth:+ self._main_depth -= 1++ def handle_data(self, data: str) -> None:+ if self._inside_title:+ self.title += data+ elif not self._skip_depth and data.strip():+ self._append(data.strip() + " ")++ @property+ def text(self) -> str:+ parts = self._main_parts if any(part.strip() for part in self._main_parts) else self._parts+ lines = (line.strip() for line in "".join(parts).splitlines())+ return "\n".join(line for line in lines if line)+++def html_to_text(html: str) -> _PageText:+ extractor = _TextExtractor()+ extractor.feed(html)+ return _PageText(title=extractor.title.strip(), text=extractor.text)+++def _fetch(url: str, accept: str) -> _FetchedBody | None:+ try:+ response = fetch_public_url(+ strip_userinfo(url),+ headers={"Accept": accept, "User-Agent": "PostHog content research"},+ max_bytes=MAX_DOCUMENT_BYTES,+ deadline=time.monotonic() + FETCH_SECONDS,+ connect_timeout_seconds=3.0,+ read_timeout_seconds=15.0,+ )+ except PublicUrlFetchError:+ return None+ if not 200 <= response.status_code < 300:+ return None+ return _FetchedBody(+ content_type=response.headers.get("content-type", ""), body=response.body.decode("utf-8", errors="replace")+ )+++def _markdown_twin(url: str) -> str:+ parsed = urlparse(url)+ path = parsed.path.rstrip("/") or "/index"+ return parsed._replace(path=f"{path}.md", query="", fragment="").geturl()+++def _page_path(url: str) -> str:+ return urlparse(url).path.rstrip("/") or "/"+++def _page_key(url: str) -> str:+ return f"{site_host(url)}{_page_path(url)}"+++def _clean(text: str) -> str:+ return strip_llm_framing_markers(text, MAX_DOCUMENT_CHARS)+++def _links_to_page(markdown: str, url: str) -> bool:+ targets = [re.escape(url.rstrip("/"))]+ if (path := _page_path(url)) != "/":+ targets.append(r"(?<![\w.:/-])" + re.escape(path))+ return re.search(f"(?:{'|'.join(targets)})/?(?![\\w/.-])", markdown) is not None+++def _without_preamble(markdown: str) -> str:+ lines = markdown.splitlines()+ h1 = next((index for index, line in enumerate(lines) if line.startswith("# ")), None)+ if h1 is None or not all(not line.strip() or line.startswith(">") for line in lines[:h1]):+ return markdown+ return "\n".join(lines[h1:])+++def _fetch_html_document(url: str, origin: DocumentOrigin) -> SourceDocument | None:+ page = _fetch(url, "text/html,application/xhtml+xml;q=0.9")+ if page is None:+ return None+ extracted = html_to_text(page.body)+ if not extracted.text:+ return None+ return SourceDocument(url=url, title=extracted.title, text=_clean(extracted.text), origin=origin)+++def fetch_site_page(url: str) -> SourceDocument | None:+ twin_document: SourceDocument | None = None+ twin = _fetch(_markdown_twin(url), "text/markdown,text/plain;q=0.9")+ if twin is not None and "html" not in twin.content_type.lower() and twin.body.strip():+ body = _without_preamble(twin.body)+ first_heading = next((line[2:] for line in body.splitlines() if line.startswith("# ")), "")+ twin_document = SourceDocument(url=url, title=first_heading.strip(), text=_clean(body), origin="site")+ if not _links_to_page(twin.body, url):+ return twin_document+ page_document = _fetch_html_document(url, "site")+ if page_document is None or (twin_document is not None and len(twin_document.text) >= len(page_document.text)):+ return twin_document+ return page_document+++def fetch_competitor_page(url: str) -> SourceDocument | None:+ try:+ scraped = scrape(url, source=FIRECRAWL_SOURCE, formats=("markdown",), priority=Priority.BATCH)+ if scraped.markdown:+ return SourceDocument(+ url=url, title=scraped.title or "", text=_clean(scraped.markdown), origin="competitor"+ )+ except (FirecrawlNotConfigured, FirecrawlScrapeFailed, FirecrawlEgressBudgetExhausted):+ pass+ return _fetch_html_document(url, "competitor")+++def search_site_pages(prompt: str, *, site_origin: str, site_urls: list[str]) -> list[str]:+ host = site_host(site_origin)+ if not host:+ return []+ try:+ found = search(+ f"site:{host} {prompt}"[:MAX_SEARCH_QUERY_CHARS],+ source=FIRECRAWL_SOURCE,+ limit=MAX_SITE_SEARCH_RESULTS,+ priority=Priority.BATCH,+ )+ except (FirecrawlNotConfigured, FirecrawlSearchFailed, FirecrawlEgressBudgetExhausted):+ return []+ by_page = {_page_key(url): url for url in reversed(site_urls)}+ pages = [+ by_page.get(_page_key(result.url), result.url)+ for result in found.results+ if has_same_public_site(result.url, site_origin)+ ]+ return list(dict.fromkeys(pages))+++def gather_research(+ *,+ prompt: str,+ target_url: str,+ competitor_urls: list[str],+ site_origin: str,+ link_candidates: list[str],+) -> ResearchBundle:+ skipped: list[str] = []+ documents: list[SourceDocument] = []++ if target_url:+ document = fetch_site_page(target_url)+ if document is None:+ skipped.append(f"Couldn't read the site page {target_url}.")+ else:+ documents.append(document)++ competitors = [url for url in competitor_urls if not has_same_public_site(url, site_origin)]+ for url in competitors[:MAX_COMPETITOR_PAGES]:+ document = fetch_competitor_page(url)+ if document is None:+ skipped.append(f"Couldn't read the cited page {url}.")+ continue+ documents.append(document)++ return ResearchBundle(+ prompt=prompt,+ target_url=target_url,+ documents=tuple(documents),+ link_candidates=tuple(link_candidates[:MAX_LINK_CANDIDATES]),+ skipped=tuple(skipped),+ )+++def fetch_named_competitor_pages(+ urls: list[str], *, site_origin: str, research: ResearchBundle+) -> tuple[list[SourceDocument], list[str]]:+ known_pages = {_page_key(document.url) for document in research.documents}+ documents: list[SourceDocument] = []+ skipped: list[str] = []+ for url in urls[:MAX_NAMED_COMPETITOR_PAGES]:+ page = _page_key(url)+ if not site_host(url) or page in known_pages or has_same_public_site(url, site_origin):+ continue+ document = fetch_competitor_page(url)+ if document is None:+ skipped.append(f"Couldn't read the competitor page {url}.")+ continue+ documents.append(document)+ known_pages.add(page)+ return documents, skippeddiff --git a/products/web_analytics/backend/content_autopilot/validation.py b/products/web_analytics/backend/content_autopilot/validation.pynew file mode 100644index 000000000000..62c87a840641--- /dev/null+++ b/products/web_analytics/backend/content_autopilot/validation.py@@ -0,0 +1,377 @@+import re+import json+from typing import Any+from urllib.parse import ParseResult, urlparse++from posthog.dataclasses import frozen++from products.web_analytics.backend.content_autopilot.research import ResearchBundle+from products.web_analytics.backend.content_autopilot.site_discovery import site_host++MIN_WORDS = 250+LENGTH_TOLERANCE = 1.5+OVERLAP_WINDOW_CHARS = 40+MAX_REPORTED_ITEMS = 5++LINK_RE = re.compile(r"\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")+_WORD_RE = re.compile(r"\S+")+STRUCTURED_DATA_TYPES = frozenset({"Article", "FAQPage"})+++@frozen+class ValidationCheck:+ check_key: str+ label: str+ passed: bool+ message: str+ blocking: bool+ details: tuple[str, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "check_key": self.check_key,+ "label": self.label,+ "passed": self.passed,+ "message": self.message,+ "blocking": self.blocking,+ }+++@frozen+class JudgeVerdict:+ unsupported_claims: tuple[str, ...]+ answers_prompt: bool+ answers_prompt_reason: str+ brand_rule_violations: tuple[str, ...]+++def _normalize_path(path: str) -> str:+ stripped = path.split("#", 1)[0].split("?", 1)[0].removesuffix(".md").rstrip("/")+ return stripped or "/"+++def _parse(url: str) -> ParseResult | None:+ try:+ return urlparse(url)+ except ValueError:+ return None+++def _url_path(url: str) -> str:+ parsed = _parse(url)+ return _normalize_path(parsed.path if parsed else url)+++def _has_host(url: str) -> bool:+ parsed = _parse(url)+ return bool(parsed and parsed.netloc)+++def _summarize(items: list[str]) -> str:+ shown = ", ".join(f"`{item[:120]}`" for item in items[:MAX_REPORTED_ITEMS])+ extra = len(items) - MAX_REPORTED_ITEMS+ return f"{shown} and {extra} more" if extra > 0 else shown+++def word_count(markdown: str) -> int:+ return len(_WORD_RE.findall(markdown))+++@frozen+class _StructureProblem:+ severity: int+ message: str+++def _structure_problems(markdown: str) -> dict[str, _StructureProblem]:+ lines = markdown.splitlines()+ h1_count = sum(1 for line in lines if line.startswith("# "))+ words = word_count(markdown)+ problems: dict[str, _StructureProblem] = {}+ if h1_count != 1:+ problems["h1"] = _StructureProblem(+ severity=abs(h1_count - 1), message=f"it has {h1_count} H1 headings instead of one"+ )+ if not any(line.startswith("## ") for line in lines):+ problems["h2"] = _StructureProblem(severity=1, message="it has no H2 sections")+ if words < MIN_WORDS:+ problems["words"] = _StructureProblem(+ severity=MIN_WORDS - words, message=f"it has {words} words, fewer than {MIN_WORDS}"+ )+ if markdown.lstrip().startswith("---"):+ problems["frontmatter"] = _StructureProblem(+ severity=1, message="it starts with frontmatter, which belongs in the content package"+ )+ return problems+++def check_structure(markdown: str, *, baseline: str | None = None) -> ValidationCheck:+ problems = _structure_problems(markdown)+ if baseline is not None:+ existing = _structure_problems(baseline)+ problems = {+ key: problem+ for key, problem in problems.items()+ if key not in existing or problem.severity > existing[key].severity+ }+ return ValidationCheck(+ check_key="structure",+ label="Page structure",+ passed=not problems,+ message="One H1, question-led sections, and enough depth."+ if not problems+ else f"Fix the page: {'; '.join(problem.message for problem in problems.values())}.",+ blocking=True,+ )+++def check_length(markdown: str, *, budget: int) -> ValidationCheck:+ words = word_count(markdown)+ if words <= budget:+ message = f"{words} new words, within the budget of about {budget}."+ elif words <= budget * LENGTH_TOLERANCE:+ message = f"{words} new words, a little over the budget of about {budget}."+ else:+ message = f"{words} new words, well over the budget of about {budget}. Trim it before publishing."+ return ValidationCheck(+ check_key="length",+ label="Length",+ passed=words <= budget * LENGTH_TOLERANCE,+ message=message,+ blocking=False,+ )+++def check_edit_placement(unplaced: tuple[str, ...]) -> ValidationCheck:+ return ValidationCheck(+ check_key="edit_placement",+ label="Edit placement",+ passed=not unplaced,+ message="Every edit landed where it was meant to."+ if not unplaced+ else f"These headings aren't on the page, so their edits were added at the end: {_summarize(list(unplaced))}.",+ blocking=False,+ )+++def check_internal_links(markdown: str, *, site_origin: str, site_urls: list[str]) -> ValidationCheck:+ if not site_urls:+ return ValidationCheck(+ check_key="internal_links",+ label="Internal links",+ passed=True,+ message="The sitemap couldn't be read, so links weren't checked. Review them by hand.",+ blocking=False,+ )+ host = site_host(site_origin)+ known_paths = {_url_path(url) for url in site_urls}+ broken: list[str] = []+ for target in LINK_RE.findall(markdown):+ parsed = _parse(target)+ if parsed is None:+ broken.append(target)+ continue+ if parsed.netloc:+ absolute = target if parsed.scheme else f"https:{target}"+ if parsed.scheme not in {"", "http", "https"} or site_host(absolute) != host:+ continue+ elif not target.startswith("/"):+ continue+ if _normalize_path(parsed.path) not in known_paths:+ broken.append(target)+ return ValidationCheck(+ check_key="internal_links",+ label="Internal links",+ passed=not broken,+ message="Every internal link points to a page in the sitemap."+ if not broken+ else f"These links don't match a page in the sitemap: {_summarize(broken)}.",+ blocking=True,+ )+++def _normalized_text(text: str) -> str:+ return " ".join(_WORD_RE.findall(text.lower()))+++def _windows(text: str) -> set[str]:+ windows: set[str] = set()+ start = 0+ while start + OVERLAP_WINDOW_CHARS <= len(text):+ windows.add(text[start : start + OVERLAP_WINDOW_CHARS])+ next_space = text.find(" ", start + 1)+ if next_space == -1:+ break+ start = next_space + 1+ return windows+++def check_competitor_overlap(markdown: str, research: ResearchBundle) -> ValidationCheck:+ competitor_windows: set[str] = set()+ for document in research.competitor_documents:+ competitor_windows |= _windows(_normalized_text(document.text))+ copied = sorted(_windows(_normalized_text(markdown)) & competitor_windows)+ return ValidationCheck(+ check_key="originality",+ label="Originality",+ passed=not copied,+ message="No passages match the cited competitor pages."+ if not copied+ else f"Some passages match cited competitor pages word for word: {_summarize(copied)}.",+ blocking=True,+ )+++def _has_expected_json_ld(document: dict[str, Any]) -> bool:+ declared = document.get("@type")+ types = (+ {declared} if isinstance(declared, str) else set(map(str, declared)) if isinstance(declared, list) else set()+ )+ if not document.get("@context") or not types & STRUCTURED_DATA_TYPES:+ return False+ return bool(document.get("mainEntity") if "FAQPage" in types else document.get("headline"))+++def check_structured_data(json_ld: str) -> ValidationCheck:+ label = "Structured data"+ if not json_ld.strip():+ return ValidationCheck(+ check_key="structured_data",+ label=label,+ passed=False,+ message="No JSON-LD was produced. Answer engines use it to understand FAQ content.",+ blocking=False,+ )+ try:+ parsed = json.loads(json_ld)+ except json.JSONDecodeError:+ return ValidationCheck(+ check_key="structured_data",+ label=label,+ passed=False,+ message="The JSON-LD isn't valid JSON.",+ blocking=True,+ )+ valid = isinstance(parsed, dict) and _has_expected_json_ld(parsed)+ return ValidationCheck(+ check_key="structured_data",+ label=label,+ passed=valid,+ message="The JSON-LD is valid."+ if valid+ else "The JSON-LD needs an @context and an @type of FAQPage with questions, or Article with a headline.",+ blocking=True,+ )+++def check_url_available(url_path: str, *, is_new_page: bool, site_urls: list[str]) -> ValidationCheck:+ if not is_new_page:+ return ValidationCheck(+ check_key="url", label="Page URL", passed=True, message="This updates an existing page.", blocking=True+ )+ segments = url_path.split("?", 1)[0].split("#", 1)[0].split("/")+ well_formed = (+ url_path.startswith("/") and not url_path.startswith("//") and "." not in segments and ".." not in segments+ )+ if not well_formed:+ return ValidationCheck(+ check_key="url",+ label="Page URL",+ passed=False,+ message=f"`{url_path[:200]}` isn't a root-relative path. Use a path like `/docs/new-page`.",+ blocking=True,+ )+ if not site_urls:+ return ValidationCheck(+ check_key="url",+ label="Page URL",+ passed=True,+ message=f"The sitemap couldn't be read, so check that `{url_path}` isn't already a page.",+ blocking=True,+ )+ taken = _normalize_path(url_path) in {_url_path(url) for url in site_urls}+ return ValidationCheck(+ check_key="url",+ label="Page URL",+ passed=not taken,+ message=f"`{url_path[:200]}` is already a page on the site." if taken else f"`{url_path}` is free to use.",+ blocking=True,+ )+++def _page_key(url: str) -> str:+ return f"{site_host(url)}{_url_path(url)}"+++def check_ledger_sources(+ source_ledger: list[dict[str, str]],+ research: ResearchBundle,+ *,+ competitor_ledger: list[dict[str, str]] | tuple[dict[str, str], ...] = (),+) -> ValidationCheck:+ site_paths = {_url_path(document.url) for document in research.site_documents}+ site_pages = {_page_key(document.url) for document in research.site_documents}+ researched_pages = {_page_key(document.url) for document in research.documents}+ site_sources = [entry["source_url"] for entry in source_ledger]+ competitor_sources = [entry["source_url"] for entry in competitor_ledger]+ outside = [+ url+ for url in site_sources+ if (_page_key(url) not in site_pages if _has_host(url) else _url_path(url) not in site_paths)+ ]+ outside += [url for url in competitor_sources if _page_key(url) not in researched_pages]+ return ValidationCheck(+ check_key="sources",+ label="Sources",+ passed=not outside,+ message="Every sourced claim cites a page that was part of the research."+ if not outside+ else f"Some claims cite pages that weren't part of the research: {_summarize(outside)}.",+ blocking=True,+ )+++def judge_checks(verdict: JudgeVerdict, *, has_brand_rules: bool) -> list[ValidationCheck]:+ checks = [+ ValidationCheck(+ check_key="grounding",+ label="Sourced facts",+ passed=not verdict.unsupported_claims,+ message="Every claim is backed by the site's pages or by the other company's own pages."+ if not verdict.unsupported_claims+ else f"These claims aren't backed by a source: {_summarize(list(verdict.unsupported_claims))}.",+ blocking=True,+ details=verdict.unsupported_claims,+ ),+ ValidationCheck(+ check_key="intent",+ label="Answers the question",+ passed=verdict.answers_prompt,+ message=verdict.answers_prompt_reason[:500] or "Checked against the question.",+ blocking=True,+ ),+ ]+ if has_brand_rules:+ checks.append(+ ValidationCheck(+ check_key="brand",+ label="Brand rules",+ passed=not verdict.brand_rule_violations,+ message="The draft follows the brand rules."+ if not verdict.brand_rule_violations+ else f"Brand rule issues: {_summarize(list(verdict.brand_rule_violations))}.",+ blocking=True,+ )+ )+ return checks+++def build_report(checks: list[ValidationCheck]) -> dict[str, Any]:+ return {+ "passed": all(check.passed for check in checks if check.blocking),+ "checks": [check.to_dict() for check in checks],+ }+++def blocking_failures(checks: list[ValidationCheck]) -> list[ValidationCheck]:+ return [check for check in checks if check.blocking and not check.passed]diff --git a/products/web_analytics/backend/test/test_content_autopilot_generation.py b/products/web_analytics/backend/test/test_content_autopilot_generation.pyindex 11a9880dc6e1..78da13e49da2 100644--- a/products/web_analytics/backend/test/test_content_autopilot_generation.py+++ b/products/web_analytics/backend/test/test_content_autopilot_generation.py@@ -10,8 +10,48 @@ import httpxfrom anthropic import APIConnectionErrorfrom parameterized import parameterized+from posthog.egress.firecrawl.client import FirecrawlSearch, FirecrawlSearchFailed, FirecrawlSearchResult+from products.web_analytics.backend.content_autopilot.edits import PageEdit, apply_editsfrom products.web_analytics.backend.content_autopilot.llm import ContentAutopilotLLMError, call_json+from products.web_analytics.backend.content_autopilot.research import (+ ResearchBundle,+ SourceDocument,+ fetch_named_competitor_pages,+ fetch_site_page,+ search_site_pages,+)+from products.web_analytics.backend.content_autopilot.validation import (+ check_competitor_overlap,+ check_internal_links,+ check_ledger_sources,+ check_structure,+ check_structured_data,+ check_url_available,+)+from products.web_analytics.backend.public_url_fetch import FetchedPublicUrl++SITE_PAGES = [+ "https://example.com/docs/session-replay",+ "https://example.com/docs/session-replay/privacy-controls",+ "https://example.com/pricing",+]+++REPLAY_DOC = "# Session replay\n\nSession replay records what users do and plays it back with console logs."+++COMPETITOR_SENTENCE = "rival replays every session with pixel perfect fidelity across all browsers"+++GOOD_MARKDOWN = (+ "# How session replay works\n\n"+ + "Session replay records what users do and plays it back so you can see where they struggle. " * 3+ + "\n\n## What does session replay capture?\n\n"+ + "It captures clicks, scrolls, and console logs alongside each recording for debugging. " * 20+ + "\n\nRead more in the [session replay docs](/docs/session-replay).\n\n"+ + "## Frequently asked questions\n\n### Is it private?\n\nYes, see [privacy controls](/docs/session-replay/privacy-controls).\n"+)class _FakeStream:@@ -172,3 +212,205 @@ class TestApplyEdits(SimpleTestCase):assert all(fragment not in applied.markdown for fragment in absent)assert applied.unplaced == unplacedassert "a\n\n\nb" in applied.markdown+++class TestSearchSitePages(SimpleTestCase):+ def test_maps_results_onto_sitemap_pages_and_drops_other_sites(self) -> None:+ results = FirecrawlSearch(+ query="q",+ results=(+ FirecrawlSearchResult(url="https://www.example.com/docs/session-replay/"),+ FirecrawlSearchResult(url="https://rival.example/replay"),+ FirecrawlSearchResult(url="https://example.com/compare/best-replay-tools"),+ FirecrawlSearchResult(url="https://docs.example.com/pricing"),+ ),+ )+ with patch("products.web_analytics.backend.content_autopilot.research.search", return_value=results) as search:+ pages = search_site_pages("best replay tool", site_origin="https://example.com", site_urls=SITE_PAGES)++ assert search.call_args.args[0] == "site:example.com best replay tool"+ assert pages == [+ "https://example.com/docs/session-replay",+ "https://example.com/compare/best-replay-tools",+ "https://docs.example.com/pricing",+ ]++ def test_finds_nothing_when_search_fails(self) -> None:+ with patch(+ "products.web_analytics.backend.content_autopilot.research.search",+ side_effect=FirecrawlSearchFailed("unavailable"),+ ):+ assert search_site_pages("best replay tool", site_origin="https://example.com", site_urls=SITE_PAGES) == []+++class TestFetchSitePage(SimpleTestCase):+ @parameterized.expand(+ [+ ("full_twin", REPLAY_DOC, REPLAY_DOC, None),+ (+ "twin_with_a_notice_for_agents",+ "> AI agents: this is one page from the docs.\n\n" + REPLAY_DOC,+ REPLAY_DOC,+ "AI agents",+ ),+ (+ "stub_twin_linking_to_its_page",+ "# Session replay\n\nFull page: https://example.com/docs/session-replay",+ "Session replay records every click, scroll and console error in the browser.",+ None,+ ),+ (+ "stub_twin_linking_to_its_page_relatively",+ "# Session replay\n\nRead the [full page](/docs/session-replay).",+ "Session replay records every click, scroll and console error in the browser.",+ None,+ ),+ ]+ )+ def test_prefers_the_richer_page_body(self, _name: str, twin: str, expected_text: str, absent: str | None) -> None:+ html = "<html><title>Session replay</title><body><p>Session replay records every click, scroll and console error in the browser.</p></body></html>"++ def fetch(url: str, **kwargs: Any) -> FetchedPublicUrl:+ if url.endswith(".md"):+ return FetchedPublicUrl(status_code=200, headers={"content-type": "text/markdown"}, body=twin.encode())+ return FetchedPublicUrl(status_code=200, headers={"content-type": "text/html"}, body=html.encode())++ with patch("products.web_analytics.backend.content_autopilot.research.fetch_public_url", side_effect=fetch):+ document = fetch_site_page("https://example.com/docs/session-replay")++ assert document is not None+ assert expected_text in document.text+ assert absent is None or absent not in document.text+++class TestValidationChecks(SimpleTestCase):+ @parameterized.expand(+ [+ ("relative_known", "[a](/pricing)", True),+ ("markdown_twin_of_known", "[a](/pricing.md)", True),+ ("absolute_same_site_known", "[a](https://www.example.com/pricing/)", True),+ ("external_is_ignored", "[a](https://rival.example/x)", True),+ ("protocol_relative_external_is_ignored", "[a](//rival.example/x)", True),+ ("protocol_relative_same_site_unknown", "[a](//example.com/nope)", False),+ ("relative_unknown", "[a](/nope)", False),+ ("malformed_authority", "[a](//[)", False),+ ]+ )+ def test_internal_links(self, _name: str, markdown: str, passed: bool) -> None:+ check = check_internal_links(markdown, site_origin="https://example.com", site_urls=SITE_PAGES)+ assert check.passed is passed++ @parameterized.expand(+ [+ ("researched_competitor_page", "competitor", "https://rival.example/replay", True),+ ("unresearched_competitor_page", "competitor", "https://rival.example/pricing", False),+ ("researched_site_page", "site", "https://www.example.com/pricing/", True),+ ("relative_site_page", "site", "/pricing", True),+ ("same_path_on_another_site", "site", "https://rival.example/pricing", False),+ ("malformed_url", "site", "https://[", False),+ ]+ )+ def test_claims_must_cite_a_researched_page(self, _name: str, ledger: str, source_url: str, passed: bool) -> None:+ research = ResearchBundle(+ prompt="p",+ target_url="",+ documents=(+ SourceDocument(url="https://example.com/pricing", title="", text="Free tier.", origin="site"),+ SourceDocument(+ url="https://rival.example/replay", title="", text="Rival costs $10.", origin="competitor"+ ),+ ),+ link_candidates=(),+ skipped=(),+ )+ claim = {"claim": "Costs $10.", "source_url": source_url, "quote": "Costs $10."}++ if ledger == "site":+ check = check_ledger_sources([claim], research)+ else:+ check = check_ledger_sources([], research, competitor_ledger=[claim])++ assert check.passed is passed++ @parameterized.expand(+ [+ ("problem_already_on_the_page", "# A\n\n# B\n\n" + GOOD_MARKDOWN.split("\n", 1)[1], True),+ ("problem_added_by_the_edit", "# A\n\n" + "word " * 300, False),+ ("problem_made_worse_by_the_edit", "# A\n\n# B\n\n# C\n\n## Section\n\n" + "word " * 300, False),+ ]+ )+ def test_structure_of_an_improvement_ignores_what_the_page_already_had(+ self, _name: str, improved: str, passed: bool+ ) -> None:+ original = "# A\n\n# B\n\n## Section\n\n" + "word " * 300++ assert check_structure(improved, baseline=original).passed is passed++ def test_competitor_overlap_detects_copied_passages_regardless_of_case_and_spacing(self) -> None:+ research = ResearchBundle(+ prompt="p",+ target_url="",+ documents=(+ SourceDocument(url="https://rival.example", title="", text=COMPETITOR_SENTENCE, origin="competitor"),+ ),+ link_candidates=(),+ skipped=(),+ )+ copied = "Intro. " + COMPETITOR_SENTENCE.upper().replace(" ", " ") + " outro."+ assert check_competitor_overlap(copied, research).passed is False+ assert check_competitor_overlap("An original sentence about replays and browsers.", research).passed is True++ @parameterized.expand(+ [+ ("free_path", "/docs/new-page", SITE_PAGES, True),+ ("existing_page", "/pricing/", SITE_PAGES, False),+ ("parent_segment_hiding_an_existing_page", "/docs/../pricing", SITE_PAGES, False),+ ("not_root_relative", "docs/new-page", SITE_PAGES, False),+ ("malformed_authority", "//[", SITE_PAGES, False),+ ("unread_sitemap", "/docs/new-page", [], True),+ ]+ )+ def test_new_page_url(self, _name: str, url_path: str, site_urls: list[str], passed: bool) -> None:+ assert check_url_available(url_path, is_new_page=True, site_urls=site_urls).passed is passed++ @parameterized.expand(+ [+ (+ "faq_page_with_questions",+ '{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question"}]}',+ True,+ ),+ ("article_with_headline", '{"@context": "https://schema.org", "@type": "Article", "headline": "A"}', True),+ (+ "article_listed_in_a_type_array",+ '{"@context": "https://schema.org", "@type": ["Article"], "headline": "A"}',+ True,+ ),+ ("unrelated_type", '{"@context": "https://schema.org", "@type": "Recipe", "headline": "A"}', False),+ ("faq_page_without_questions", '{"@context": "https://schema.org", "@type": "FAQPage"}', False),+ ]+ )+ def test_structured_data(self, _name: str, json_ld: str, passed: bool) -> None:+ assert check_structured_data(json_ld).passed is passed++ def test_named_competitor_pages_skip_only_pages_already_researched(self) -> None:+ research = ResearchBundle(+ prompt="p",+ target_url="",+ documents=(SourceDocument(url="https://rival.example/replay", title="", text="t", origin="competitor"),),+ link_candidates=(),+ skipped=(),+ )+ fetched = SourceDocument(url="https://rival.example/pricing", title="", text="t", origin="competitor")++ with patch(+ "products.web_analytics.backend.content_autopilot.research.fetch_competitor_page", return_value=fetched+ ) as fetch:+ documents, _ = fetch_named_competitor_pages(+ ["https://rival.example/replay/", "https://rival.example/pricing"],+ site_origin="https://example.com",+ research=research,+ )++ assert [call.args[0] for call in fetch.call_args_list] == ["https://rival.example/pricing"]+ assert documents == [fetched]