: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(business knowledge): backend (#58094)
Alex V449f5f32df0f
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex a818076c9134..71571097a9dc 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -34,6 +34,7 @@ import products.live_debugger.backend.api as live_debuggerimport products.web_analytics.backend.api as web_analytics_apiimport products.surveys.backend.api.survey as surveyimport products.revenue_analytics.backend.api as revenue_analytics+import products.business_knowledge.backend.api as business_knowledgeimport products.marketing_analytics.backend.api as marketing_analyticsimport products.early_access_features.backend.api as early_access_featureimport products.customer_analytics.backend.api.views as customer_analytics@@ -1150,6 +1151,13 @@ register_grandfathered_environment_nested_viewset(projects_router.register(r"links", link.LinkViewSet, "environment_links", ["team_id"])+projects_router.register(+ r"business_knowledge/sources",+ business_knowledge.KnowledgeSourceViewSet,+ "environment_business_knowledge_sources",+ ["team_id"],+)+projects_router.register(r"conversations/tickets",conversations.TicketViewSet,diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 44f53b88302a..9a543214622e 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -22,6 +22,7 @@ APIScopeObject = Literal["approvals","batch_export","batch_import",+ "business_knowledge","clickhouse_test_cluster_perf","cohort","comment",diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.pyindex 946d5ac03a2e..2f9a39645fd1 100644--- a/posthog/security/url_validation.py+++ b/posthog/security/url_validation.py@@ -111,12 +111,36 @@ def is_url_allowed(raw_url: str) -> tuple[bool, str | None]:- Host must not be localhost, metadata service, or internal domain- Resolved IPs must not be private/internal"""+ allowed, reason, _ips = _validate_url_with_ips(raw_url)+ return allowed, reason+++def validate_url_and_pin_ips(+ raw_url: str,+) -> tuple[bool, str | None, set[ipaddress.IPv4Address | ipaddress.IPv6Address]]:+ """+ Like ``is_url_allowed`` but also returns the validated IP set.++ Callers that subsequently open a connection to the URL MUST use the+ returned IPs (via ``PinnedIPAdapter``) instead of re-resolving DNS.+ This eliminates the TOCTOU window that enables DNS-rebinding SSRF.+ """+ return _validate_url_with_ips(raw_url)+++def _validate_url_with_ips(+ raw_url: str,+) -> tuple[bool, str | None, set[ipaddress.IPv4Address | ipaddress.IPv6Address]]:+ empty: set[ipaddress.IPv4Address | ipaddress.IPv6Address] = set()+if _dev_bypass_enabled():- return True, None+ return True, None, empty- def _blocked(reason: str, **log_kwargs) -> tuple[bool, str]:+ def _blocked(+ reason: str, **log_kwargs: object+ ) -> tuple[bool, str, set[ipaddress.IPv4Address | ipaddress.IPv6Address]]:logger.warning("url_validation.blocked", reason=reason, **log_kwargs)- return False, reason+ return False, reason, emptytry:u = urlparse.urlparse(raw_url)@@ -147,7 +171,7 @@ def is_url_allowed(raw_url: str) -> tuple[bool, str | None]:for ip in ips:if _is_internal_ip(ip):return _blocked(f"Disallowed target IP: {ip}", host=host, ip=str(ip))- return True, None+ return True, None, ipsdef should_block_url(u: str) -> bool:diff --git a/products/business_knowledge/backend/admin.py b/products/business_knowledge/backend/admin.pynew file mode 100644index 000000000000..84df4ad614eb--- /dev/null+++ b/products/business_knowledge/backend/admin.py@@ -0,0 +1,36 @@+from django.contrib import admin++from .models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource++[email protected](KnowledgeSource)+class KnowledgeSourceAdmin(admin.ModelAdmin):+ list_display = ("id", "name", "team", "source_type", "status", "created_at")+ list_filter = ("source_type", "status", "created_at")+ search_fields = ("id", "name", "team__name")+ # Heavy FK to Team — use raw_id to avoid loading every team on change pages.+ raw_id_fields = ("team", "created_by")+ readonly_fields = ("id", "created_at", "updated_at")+ ordering = ("-created_at",)+ show_full_result_count = False++[email protected](KnowledgeDocument)+class KnowledgeDocumentAdmin(admin.ModelAdmin):+ list_display = ("id", "source", "title", "team", "created_at")+ list_filter = ("created_at",)+ search_fields = ("id", "title", "stable_id", "source__name")+ raw_id_fields = ("team", "source")+ readonly_fields = ("id", "stable_id", "created_at", "updated_at")+ ordering = ("-created_at",)+ show_full_result_count = False++[email protected](KnowledgeChunk)+class KnowledgeChunkAdmin(admin.ModelAdmin):+ list_display = ("id", "document", "heading_path", "ordinal", "char_count", "team")+ search_fields = ("id", "document__title", "heading_path")+ raw_id_fields = ("team", "source", "document")+ readonly_fields = ("id", "created_at")+ ordering = ("document_id", "ordinal")+ show_full_result_count = Falsediff --git a/products/business_knowledge/backend/api/__init__.py b/products/business_knowledge/backend/api/__init__.pynew file mode 100644index 000000000000..d3bc05e01030--- /dev/null+++ b/products/business_knowledge/backend/api/__init__.py@@ -0,0 +1,3 @@+from .views import KnowledgeSourceViewSet++__all__ = ["KnowledgeSourceViewSet"]diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.pynew file mode 100644index 000000000000..6e32d4bd0db9--- /dev/null+++ b/products/business_knowledge/backend/api/serializers.py@@ -0,0 +1,312 @@+"""DRF serializers for business_knowledge."""++from django.core.files.uploadedfile import UploadedFile++from rest_framework import serializers++from posthog.security.url_validation import is_url_allowed++from .. import url_fetch+from ..constants import (+ CRAWL_HARD_MAX_DEPTH,+ DEFAULT_CRAWL_MAX_DEPTH,+ DEFAULT_MAX_PAGES,+ MAX_FILE_SIZE_BYTES,+ MAX_TEXT_SIZE_BYTES,+ MAX_URLS_PER_SOURCE,+)+from ..models import CrawlMode, KnowledgeSource, SourceType+++class _GlobListField(serializers.ListField):+ """+ Tiny wrapper so each entry is validated as a non-empty string and the+ total list is bounded. Keeps the glob inputs from being used as a DoS+ vector — fnmatch is cheap but not free per-URL.+ """++ child = serializers.CharField(max_length=256)+ max_length = 32+++class _NameValidationMixin:+ def validate_name(self, value: str) -> str:+ value = value.strip()+ if not value:+ raise serializers.ValidationError("Name cannot be blank.")+ return value+++class _UrlValidationMixin:+ def validate_url(self, value: str) -> str:+ try:+ normalized = url_fetch.normalize_url(value)+ except url_fetch.UrlFetchError:+ raise serializers.ValidationError("Invalid URL.")+ allowed, _reason = is_url_allowed(normalized)+ if not allowed:+ raise serializers.ValidationError("URL is not reachable.")+ return normalized+++class KnowledgeSourceSerializer(serializers.ModelSerializer):+ document_count = serializers.IntegerField(+ source="_document_count",+ read_only=True,+ default=0,+ help_text="Number of documents belonging to this source.",+ )+ chunk_count = serializers.IntegerField(+ source="_chunk_count",+ read_only=True,+ default=0,+ help_text="Number of chunks belonging to this source.",+ )++ class Meta:+ model = KnowledgeSource+ fields = [+ "id",+ "team_id",+ "name",+ "source_type",+ "status",+ "error_message",+ "document_count",+ "chunk_count",+ "created_at",+ "updated_at",+ "source_url",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "crawl_mode",+ "crawl_config",+ "original_filename",+ "file_content_type",+ "file_size_bytes",+ ]+ read_only_fields = fields+++class CreateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):+ name = serializers.CharField(+ max_length=255,+ help_text="Short human label for the source. Shown in the settings list and in agent citations.",+ )+ text = serializers.CharField(+ trim_whitespace=False,+ help_text=(+ "Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources "+ "or wait for URL/file support in Stage 2/3."+ ),+ )++ def validate_text(self, value: str) -> str:+ if not value.strip():+ raise serializers.ValidationError("Text cannot be blank.")+ if len(value.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ raise serializers.ValidationError(+ f"Text exceeds the {MAX_TEXT_SIZE_BYTES:,}-byte cap. Split it into smaller sources."+ )+ return value++ def to_internal_value(self, data: dict) -> dict:+ attrs = super().to_internal_value(data)+ attrs["source_type"] = SourceType.TEXT.value+ return attrs+++class UpdateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):+ """+ PATCH payload for text sources. Both fields optional, at least one+ required. `text` triggers a re-chunk; `name` alone does not.+ """++ name = serializers.CharField(+ max_length=255,+ required=False,+ help_text="New human label for the source.",+ )+ text = serializers.CharField(+ required=False,+ trim_whitespace=False,+ help_text="Replacement text. Omit to keep the existing content.",+ )++ def validate_text(self, value: str) -> str:+ if not value.strip():+ raise serializers.ValidationError("Text cannot be blank.")+ if len(value.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ raise serializers.ValidationError(+ f"Text exceeds the {MAX_TEXT_SIZE_BYTES:,}-byte cap. Split it into smaller sources."+ )+ return value++ def validate(self, attrs: dict) -> dict:+ if "name" not in attrs and "text" not in attrs:+ raise serializers.ValidationError("Provide at least one of `name` or `text`.")+ return attrs+++class UpdateUrlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, serializers.Serializer):+ """+ PATCH payload for URL sources. All fields optional, at least one required.+ Changing `url` or crawl settings triggers a re-crawl.+ """++ name = serializers.CharField(+ max_length=255,+ required=False,+ help_text="New human label for the source.",+ )+ url = serializers.URLField(+ max_length=2048,+ required=False,+ help_text="New URL. Triggers a re-crawl when changed.",+ )+ crawl_mode = serializers.ChoiceField(+ choices=[CrawlMode.SINGLE.value, CrawlMode.SITEMAP.value, CrawlMode.SAME_ORIGIN.value],+ required=False,+ help_text="New crawl mode. Triggers a re-crawl when changed.",+ )+ include_globs = _GlobListField(+ required=False,+ help_text="URL path globs to include.",+ )+ exclude_globs = _GlobListField(+ required=False,+ help_text="URL path globs to exclude.",+ )+ max_pages = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=MAX_URLS_PER_SOURCE,+ help_text=f"Max pages to fetch. Capped at {MAX_URLS_PER_SOURCE}.",+ )+ max_depth = serializers.IntegerField(+ required=False,+ min_value=0,+ max_value=CRAWL_HARD_MAX_DEPTH,+ help_text="BFS depth for same_origin.",+ )++ def validate(self, attrs: dict) -> dict:+ if not attrs:+ raise serializers.ValidationError("Provide at least one field to update.")+ return attrs++ def to_internal_value(self, data: dict) -> dict:+ attrs = super().to_internal_value(data)+ crawl_config_keys = {"include_globs", "exclude_globs", "max_pages", "max_depth"}+ crawl_fields = {k: attrs.pop(k) for k in crawl_config_keys if k in attrs}+ if crawl_fields:+ attrs["crawl_config"] = crawl_fields+ return attrs+++class CreateUrlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, serializers.Serializer):+ """+ POST payload for URL sources. Normalizes + SSRF-validates the URL here+ so the client gets a precise 400 instead of a created-but-errored source.+ The logic layer re-validates on every fetch anyway — this is UX, not+ security.+ """++ name = serializers.CharField(+ max_length=255,+ help_text="Short human label for the source. Shown in the settings list and in agent citations.",+ )+ url = serializers.URLField(+ max_length=2048,+ help_text=(+ "Public HTTP(S) URL to fetch. Private / internal hosts are rejected. "+ "Stage 2a fetches this URL once at create time; Stage 5 will refresh it on a schedule."+ ),+ )++ def to_internal_value(self, data: dict) -> dict:+ attrs = super().to_internal_value(data)+ attrs["source_type"] = SourceType.URL.value+ return attrs+++class CreateCrawlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, serializers.Serializer):+ """+ POST payload for multi-URL crawl sources (Stage 2b).++ The entry URL goes through the same SSRF gate as the single-URL endpoint;+ each URL discovered during the crawl is independently re-validated before+ fetch, so we never trust a discovered URL just because its parent did.+ """++ name = serializers.CharField(+ max_length=255,+ help_text="Short human label for the source. Shown in the settings list and in agent citations.",+ )+ url = serializers.URLField(+ max_length=2048,+ help_text="Entry URL. For sitemap mode, this is sitemap.xml (or a page whose origin has /sitemap.xml).",+ )+ crawl_mode = serializers.ChoiceField(+ choices=[CrawlMode.SITEMAP.value, CrawlMode.SAME_ORIGIN.value],+ help_text="How to expand the entry URL into documents.",+ )+ include_globs = _GlobListField(+ required=False,+ default=list,+ help_text="URL path globs to include (fnmatch, e.g. `/docs/*`). Empty means include everything.",+ )+ exclude_globs = _GlobListField(+ required=False,+ default=list,+ help_text="URL path globs to exclude. Applied after `include_globs`.",+ )+ max_pages = serializers.IntegerField(+ required=False,+ default=DEFAULT_MAX_PAGES,+ min_value=1,+ max_value=MAX_URLS_PER_SOURCE,+ help_text=f"Max pages to fetch. Capped at {MAX_URLS_PER_SOURCE} for inline crawls.",+ )+ max_depth = serializers.IntegerField(+ required=False,+ default=DEFAULT_CRAWL_MAX_DEPTH,+ min_value=0,+ max_value=CRAWL_HARD_MAX_DEPTH,+ help_text="BFS depth for `same_origin`. Ignored by `sitemap`.",+ )++ def to_internal_value(self, data: dict) -> dict:+ attrs = super().to_internal_value(data)+ attrs["source_type"] = SourceType.URL.value+ attrs["crawl_config"] = {+ "include_globs": attrs.pop("include_globs"),+ "exclude_globs": attrs.pop("exclude_globs"),+ "max_pages": attrs.pop("max_pages"),+ "max_depth": attrs.pop("max_depth"),+ }+ return attrs+++class CreateFileSourceSerializer(_NameValidationMixin, serializers.Serializer):+ """+ Multipart upload payload for file sources. The file's content type is+ detected from magic bytes server-side — the client-provided Content-Type+ is ignored for security.+ """++ name = serializers.CharField(+ max_length=255,+ help_text="Short human label for the source.",+ )+ file = serializers.FileField(+ help_text=(+ f"PDF, DOCX, Markdown (.md), CSV, or plain text (.txt) file. Max {MAX_FILE_SIZE_BYTES // (1024 * 1024)} MB."+ ),+ )++ def validate_file(self, value: UploadedFile) -> UploadedFile: # noqa: F821+ if value.size and value.size > MAX_FILE_SIZE_BYTES:+ raise serializers.ValidationError(f"File exceeds the {MAX_FILE_SIZE_BYTES // (1024 * 1024)} MB cap.")+ return valuediff --git a/products/business_knowledge/backend/presentation/urls.py b/products/business_knowledge/backend/api/urls.pysimilarity index 53%rename from products/business_knowledge/backend/presentation/urls.pyrename to products/business_knowledge/backend/api/urls.pyindex e3585425f412..80b83062b51b 100644--- a/products/business_knowledge/backend/presentation/urls.py+++ b/products/business_knowledge/backend/api/urls.py@@ -2,7 +2,8 @@from rest_framework.routers import DefaultRouter-# from .views import ...+from .views import KnowledgeSourceViewSetrouter = DefaultRouter()+router.register(r"sources", KnowledgeSourceViewSet, basename="knowledge_source")urlpatterns = router.urlsdiff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.pynew file mode 100644index 000000000000..4ac990c539b7--- /dev/null+++ b/products/business_knowledge/backend/api/views.py@@ -0,0 +1,297 @@+"""DRF views for business_knowledge."""++from typing import cast+from uuid import UUID++from django.core.exceptions import ValidationError as DjangoValidationError+from django.db.models import QuerySet++from drf_spectacular.utils import extend_schema+from rest_framework import exceptions, status, viewsets+from rest_framework.decorators import action+from rest_framework.parsers import FormParser, JSONParser, MultiPartParser+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models.user import User+from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission+from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottle++from .. import logic+from ..file_parse import FileParseError+from ..models import KnowledgeSource, SourceType+from ..models.constants import CrawlMode+from .serializers import (+ CreateCrawlSourceSerializer,+ CreateFileSourceSerializer,+ CreateTextSourceSerializer,+ CreateUrlSourceSerializer,+ KnowledgeSourceSerializer,+ UpdateTextSourceSerializer,+ UpdateUrlSourceSerializer,+)+++class _ConflictError(exceptions.APIException):+ # 409 is the right semantics for "resource is currently busy / in a+ # state that conflicts with the request". DRF has no first-class helper+ # for it, hence the tiny subclass.+ status_code = status.HTTP_409_CONFLICT+ default_detail = "Resource is busy."+ default_code = "conflict"+++@extend_schema(tags=["business_knowledge"])+class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ scope_object = "business_knowledge"+ queryset = KnowledgeSource.objects.unscoped()+ serializer_class = KnowledgeSourceSerializer+ permission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]+ parser_classes = [JSONParser, MultiPartParser, FormParser]+ posthog_feature_flag = "product-business-knowledge"+ throttle_classes = [BurstRateThrottle, SustainedRateThrottle]++ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:+ return queryset.filter(team_id=self.team_id)++ @extend_schema(responses={200: KnowledgeSourceSerializer(many=True)})+ def list(self, request: Request, **kwargs) -> Response:+ sources = logic.list_for_team(self.team_id)+ page = self.paginate_queryset(sources)+ if page is not None:+ return self.get_paginated_response(KnowledgeSourceSerializer(instance=page, many=True).data)+ return Response(KnowledgeSourceSerializer(instance=sources, many=True).data)++ @extend_schema(+ request=CreateTextSourceSerializer,+ responses={201: KnowledgeSourceSerializer},+ )+ def create(self, request: Request, **kwargs) -> Response:+ source_type = request.data.get("source_type", SourceType.TEXT.value)+ if source_type == SourceType.FILE.value:+ return self._create_file_source(request)+ if source_type == SourceType.URL.value:+ crawl_mode = request.data.get("crawl_mode")+ if crawl_mode and crawl_mode != CrawlMode.SINGLE.value:+ return self._create_crawl_source(request)+ return self._create_url_source(request)+ return self._create_text_source(request)++ def _create_text_source(self, request: Request) -> Response:+ serializer = CreateTextSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ user = cast(User, request.user)+ try:+ source = logic.create_text_source(+ team_id=self.team_id,+ created_by_id=user.id,+ name=serializer.validated_data["name"],+ text=serializer.validated_data["text"],+ )+ except logic.TextTooLargeError:+ raise exceptions.ValidationError({"text": "Text exceeds the maximum allowed size."})+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ return Response(KnowledgeSourceSerializer(instance=source).data, status=status.HTTP_201_CREATED)++ def _create_url_source(self, request: Request) -> Response:+ serializer = CreateUrlSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ user = cast(User, request.user)+ try:+ source = logic.create_url_source(+ team_id=self.team_id,+ created_by_id=user.id,+ name=serializer.validated_data["name"],+ url=serializer.validated_data["url"],+ )+ except logic.SourceBusyError:+ raise _ConflictError("Another source is already being processed. Please wait and try again.")+ except logic.InvalidUrlError:+ raise exceptions.ValidationError({"url": "URL is not reachable."})+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ return Response(KnowledgeSourceSerializer(instance=source).data, status=status.HTTP_201_CREATED)++ def _create_crawl_source(self, request: Request) -> Response:+ serializer = CreateCrawlSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ user = cast(User, request.user)+ try:+ source = logic.create_crawl_source(+ team_id=self.team_id,+ created_by_id=user.id,+ name=serializer.validated_data["name"],+ url=serializer.validated_data["url"],+ crawl_mode=serializer.validated_data["crawl_mode"],+ crawl_config=serializer.validated_data["crawl_config"],+ )+ except logic.SourceBusyError:+ raise _ConflictError("Another source is already being processed. Please wait and try again.")+ except logic.InvalidUrlError:+ raise exceptions.ValidationError({"url": "URL is not reachable."})+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ return Response(KnowledgeSourceSerializer(instance=source).data, status=status.HTTP_201_CREATED)++ def _create_file_source(self, request: Request) -> Response:+ serializer = CreateFileSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ user = cast(User, request.user)++ uploaded = serializer.validated_data["file"]+ file_data = uploaded.read()++ try:+ source = logic.create_file_source(+ team_id=self.team_id,+ created_by_id=user.id,+ name=serializer.validated_data["name"],+ file_data=file_data,+ original_filename=uploaded.name or "unnamed",+ )+ except FileParseError as exc:+ raise exceptions.ValidationError({"file": str(exc) or "Unable to parse the uploaded file."})+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ return Response(KnowledgeSourceSerializer(instance=source).data, status=status.HTTP_201_CREATED)++ @extend_schema(responses={200: KnowledgeSourceSerializer})+ def retrieve(self, request: Request, pk: str, **kwargs) -> Response:+ try:+ source_id = UUID(pk)+ except (ValueError, DjangoValidationError):+ raise exceptions.NotFound()+ source = logic.get_for_team(source_id, self.team_id)+ if source is None:+ raise exceptions.NotFound()+ return Response(KnowledgeSourceSerializer(instance=source).data)++ @extend_schema(+ request=UpdateTextSourceSerializer,+ responses={200: KnowledgeSourceSerializer},+ )+ def partial_update(self, request: Request, pk: str, **kwargs) -> Response:+ try:+ source_id = UUID(pk)+ except (ValueError, DjangoValidationError):+ raise exceptions.NotFound()++ try:+ source = KnowledgeSource.objects.get(id=source_id, team_id=self.team_id)+ except KnowledgeSource.DoesNotExist:+ raise exceptions.NotFound()++ if source.source_type == SourceType.URL.value:+ return self._update_url_source(source, request)+ if source.source_type == SourceType.FILE.value:+ return self._update_file_source(source, request)+ return self._update_text_or_file_source(source, request)++ def _update_file_source(self, source: KnowledgeSource, request: Request) -> Response:+ """FILE sources only allow name changes — content comes from the original upload."""+ serializer = UpdateTextSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ if "text" in serializer.validated_data:+ raise exceptions.ValidationError(+ {"text": "File sources cannot have their text replaced. Re-upload instead."}+ )+ try:+ updated = logic.update_text_source(+ source_id=source.id,+ team_id=self.team_id,+ name=serializer.validated_data.get("name"),+ text=None,+ )+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ if updated is None:+ raise exceptions.NotFound()+ return Response(KnowledgeSourceSerializer(instance=updated).data)++ def _update_text_or_file_source(self, source: KnowledgeSource, request: Request) -> Response:+ serializer = UpdateTextSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ try:+ updated = logic.update_text_source(+ source_id=source.id,+ team_id=self.team_id,+ name=serializer.validated_data.get("name"),+ text=serializer.validated_data.get("text"),+ )+ except logic.TextTooLargeError:+ raise exceptions.ValidationError({"text": "Text exceeds the maximum allowed size."})+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ if updated is None:+ raise exceptions.NotFound()+ return Response(KnowledgeSourceSerializer(instance=updated).data)++ def _update_url_source(self, source: KnowledgeSource, request: Request) -> Response:+ serializer = UpdateUrlSourceSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ try:+ updated = logic.update_url_source(+ source_id=source.id,+ team_id=self.team_id,+ name=serializer.validated_data.get("name"),+ url=serializer.validated_data.get("url"),+ crawl_mode=serializer.validated_data.get("crawl_mode"),+ crawl_config=serializer.validated_data.get("crawl_config"),+ )+ except logic.InvalidUrlError:+ raise exceptions.ValidationError({"url": "URL is not reachable."})+ except (logic.UrlFetchFailedError, logic.EmptyContentError):+ raise exceptions.ValidationError({"url": "Could not fetch the URL."})+ except logic.SourceBusyError:+ raise _ConflictError("A refresh is already in progress for this source.")+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ if updated is None:+ raise exceptions.NotFound()+ return Response(KnowledgeSourceSerializer(instance=updated).data)++ @extend_schema(responses={200: {"type": "object", "properties": {"text": {"type": "string"}}}})+ @action(detail=True, methods=["get"], url_path="text")+ def text(self, request: Request, pk: str, **kwargs) -> Response:+ try:+ source_id = UUID(pk)+ except (ValueError, DjangoValidationError):+ raise exceptions.NotFound()+ content = logic.get_source_text_for_team(source_id, self.team_id)+ if content is None:+ raise exceptions.NotFound()+ return Response({"text": content})++ @extend_schema(responses={200: KnowledgeSourceSerializer})+ @action(detail=True, methods=["post"], url_path="refresh")+ def refresh(self, request: Request, pk: str, **kwargs) -> Response:+ try:+ source_id = UUID(pk)+ except (ValueError, DjangoValidationError):+ raise exceptions.NotFound()+ try:+ source = logic.refresh_source(source_id=source_id, team_id=self.team_id)+ except logic.SourceBusyError:+ raise _ConflictError("A refresh is already in progress for this source.")+ except logic.InvalidUrlError:+ raise exceptions.ValidationError({"url": "URL is not reachable."})+ except (logic.UrlFetchFailedError, logic.EmptyContentError):+ raise exceptions.ValidationError({"url": "Could not fetch the URL."})+ except logic.QuotaExceededError:+ raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ if source is None:+ raise exceptions.NotFound()+ return Response(KnowledgeSourceSerializer(instance=source).data)++ @extend_schema(responses={204: None})+ def destroy(self, request: Request, pk: str, **kwargs) -> Response:+ try:+ source_id = UUID(pk)+ except (ValueError, DjangoValidationError):+ raise exceptions.NotFound()+ if not logic.delete_source(source_id, self.team_id):+ raise exceptions.NotFound()+ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/business_knowledge/backend/apps.py b/products/business_knowledge/backend/apps.pyindex fc7952564b5b..8445ab24d444 100644--- a/products/business_knowledge/backend/apps.py+++ b/products/business_knowledge/backend/apps.py@@ -6,3 +6,7 @@ from django.apps import AppConfigclass BusinessKnowledgeConfig(AppConfig):name = "products.business_knowledge.backend"label = "business_knowledge"+ verbose_name = "Business knowledge"++ def ready(self) -> None:+ from . import signals # noqa: F401diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.pynew file mode 100644index 000000000000..f219041e7ab8--- /dev/null+++ b/products/business_knowledge/backend/constants.py@@ -0,0 +1,63 @@+"""+Constants and tunables for business_knowledge.+"""++# Per-team caps. Enforced in the create endpoint, not at the DB layer — easier+# to relax for a single paying customer without a migration.+MAX_SOURCES_PER_TEAM = 500+MAX_CHUNKS_PER_TEAM = 100_000+# 1 MB of raw text. Above this Stage 1 refuses the create; for longer docs the+# customer is expected to split them or wait for Stage 2/3.+MAX_TEXT_SIZE_BYTES = 1_000_000++# Chunker tunables. Kept here (not in logic.py) so the retrieval eval harness+# can import them without pulling Django.+CHUNK_TARGET_CHARS = 1200+CHUNK_HARD_MAX_CHARS = 1600++# --- Stage 2a: URL fetch tunables ---+# Hard cap on remote response bodies. Above this we abort mid-stream rather+# than ever materializing the full payload — protects memory and makes a+# zip-bomb attempt cheap to reject.+URL_MAX_BYTES = 10 * 1024 * 1024+# Connect + read timeouts (seconds). Short because fetch happens inline on+# the request thread; Stage 5 moves it to Temporal and can be generous.+URL_CONNECT_TIMEOUT = 5+URL_READ_TIMEOUT = 10+# Max redirect hops. We handle redirects manually so we can re-validate SSRF+# on every Location header.+URL_MAX_REDIRECTS = 5+# Self-identifying User-Agent — gives site operators something searchable+# and a contact point if we hammer their site by accident. URL_BOT_NAME is+# the short token site operators target in robots.txt; it MUST appear at the+# start of URL_USER_AGENT so urllib.robotparser's prefix match lines up.+URL_BOT_NAME = "PostHog-BusinessKnowledge"+URL_USER_AGENT = f"{URL_BOT_NAME}/1.0 (+https://posthog.com)"++# --- Stage 2b: crawl tunables ---+# Discover step cap — sitemap / same-origin BFS stops emitting after this+# many candidate URLs (BEFORE glob filtering). Purely defensive: a pathological+# sitemap.xml can list 100k URLs.+HARD_DISCOVER_CAP = 10_000+# Fetch step default cap. Settable per-source via `crawl_config.max_pages`,+# but users can never exceed MAX_URLS_PER_SOURCE. Deliberately low because+# Stage 2b is inline — every fetch blocks a request worker. Stage 5 moves+# this to Temporal and can raise the cap.+DEFAULT_MAX_PAGES = 50+MAX_URLS_PER_SOURCE = 500+# Default recursion depth for `same_origin` BFS.+DEFAULT_CRAWL_MAX_DEPTH = 2+CRAWL_HARD_MAX_DEPTH = 5+# Per-hostname concurrency during a single crawl — prevents us from+# hammering an origin. In-process (threading.Semaphore), not cross-worker;+# cross-worker rate limiting is Stage 5 Temporal work.+PER_HOST_CONCURRENCY = 2++# --- Stage 3: file upload tunables ---+# Hard cap on uploaded file size (compressed). Above this the serializer+# rejects immediately — the file never hits the parser.+MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024+# Decompressed size cap for ZIP-based formats (DOCX, XLSX, ODT). A 1 MB+# docx can decompress to 10 GB — 100 MB is generous for any legitimate+# knowledge document while keeping per-request memory bounded.+MAX_FILE_DECOMPRESSED_BYTES = 100 * 1024 * 1024diff --git a/products/business_knowledge/backend/crawl.py b/products/business_knowledge/backend/crawl.pynew file mode 100644index 000000000000..7b200ca81787--- /dev/null+++ b/products/business_knowledge/backend/crawl.py@@ -0,0 +1,186 @@+"""+Multi-URL fetch orchestration for Stage 2b.++Wraps `url_fetch.fetch_url` with:++- A bounded ThreadPoolExecutor so a large crawl saturates network IO.+- A per-hostname `threading.Semaphore` so we never hit an origin with more+ than `PER_HOST_CONCURRENCY` concurrent requests even if the thread pool+ is bigger.+- HTML parse hand-off (same `html_parse` used by Stage 2a).+- Per-URL outcome records so the caller can upsert / tombstone cleanly.++Errors per URL are *isolated*: one broken page doesn't tank the batch.+"""++from __future__ import annotations++import threading+import urllib.parse as urlparse+from collections.abc import Callable+from concurrent.futures import ALL_COMPLETED, ThreadPoolExecutor, wait+from dataclasses import dataclass++import structlog++from . import html_parse, url_fetch+from .constants import MAX_TEXT_SIZE_BYTES, PER_HOST_CONCURRENCY+from .url_fetch import sha256_of++CRAWL_TOTAL_TIMEOUT_SECONDS = 120++logger = structlog.get_logger(__name__)+++@dataclass(frozen=True)+class CrawlOutcome:+ """+ Result for a single URL in the crawl batch.++ `status`:+ - "ok": we got usable HTML/text. `title`, `text`, `etag`, `content_hash`+ are populated.+ - "not_modified": conditional GET returned 304. No body re-parsed.+ - "error": fetch or parse failed. `error` is a user-safe message.+ """++ url: str+ final_url: str+ status: str+ title: str = ""+ text: str = ""+ etag: str = ""+ content_hash: str = ""+ error: str = ""+++def _host_of(url: str) -> str:+ parsed = urlparse.urlparse(url)+ return (parsed.hostname or "").lower()+++class _PerHostSemaphoreRegistry:+ """+ Lazily-created `threading.Semaphore` per hostname. Cheap enough to keep+ in a dict since a single crawl rarely spans >5 hostnames.+ """++ def __init__(self, per_host: int) -> None:+ self._per_host = per_host+ self._lock = threading.Lock()+ self._map: dict[str, threading.Semaphore] = {}++ def get(self, host: str) -> threading.Semaphore:+ with self._lock:+ sem = self._map.get(host)+ if sem is None:+ sem = threading.Semaphore(self._per_host)+ self._map[host] = sem+ return sem+++def _fetch_one(url: str, *, etag: str | None, registry: _PerHostSemaphoreRegistry) -> CrawlOutcome:+ """+ Fetch + parse a single URL. Never raises — all failures return a+ CrawlOutcome(status="error", error=...). Matches the `url_fetch.fetch_url`+ contract for SSRF re-validation per-hop.+ """++ sem = registry.get(_host_of(url))+ sem.acquire()+ try:+ try:+ result = url_fetch.fetch_url(url, etag=etag)+ except url_fetch.UrlFetchError as exc:+ return CrawlOutcome(url=url, final_url=url, status="error", error=str(exc))++ if result.status == 304:+ return CrawlOutcome(+ url=url,+ final_url=result.final_url,+ status="not_modified",+ etag=result.etag or (etag or ""),+ )++ if not result.body:+ return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Remote response was empty.")++ if not url_fetch.is_html_content_type(result.content_type):+ return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Unsupported content type.")++ title, text = html_parse.parse_html(result.body, result.final_url)+ if not text.strip():+ return CrawlOutcome(+ url=url, final_url=result.final_url, status="error", error="Could not extract any text."+ )+ # Per-page byte cap — trimming beats rejecting a huge wiki page.+ if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ return CrawlOutcome(+ url=url,+ final_url=result.final_url,+ status="error",+ error="Page content exceeds the maximum allowed size.",+ )+ return CrawlOutcome(+ url=url,+ final_url=result.final_url,+ status="ok",+ title=title,+ text=text,+ etag=result.etag or "",+ content_hash=sha256_of(text),+ )+ finally:+ sem.release()+++def fetch_many(+ urls: list[str],+ *,+ etag_for: Callable[[str], str | None] | None = None,+ per_host: int = PER_HOST_CONCURRENCY,+ max_workers: int | None = None,+) -> list[CrawlOutcome]:+ """+ Fetch all `urls` in parallel, capped per-host by a threading semaphore.++ `etag_for(url)` — optional; called once per URL to pull a stored ETag+ for conditional GET. Returns None when we don't have one yet.++ `max_workers` — defaults to `max(PER_HOST_CONCURRENCY * 4, 8)`. We want+ enough threads to saturate the per-host semaphore without going wild;+ the semaphore is the real throttle.+ """++ if not urls:+ return []++ registry = _PerHostSemaphoreRegistry(per_host)+ workers = max_workers if max_workers is not None else max(per_host * 4, 8)++ results: list[CrawlOutcome] = []+ pool = ThreadPoolExecutor(max_workers=workers)+ try:+ futures = {+ pool.submit(_fetch_one, url, etag=(etag_for(url) if etag_for else None), registry=registry): url+ for url in urls+ }+ done, not_done = wait(futures, timeout=CRAWL_TOTAL_TIMEOUT_SECONDS, return_when=ALL_COMPLETED)+ for future in done:+ try:+ outcome = future.result()+ except Exception as exc: # defense in depth — _fetch_one shouldn't raise+ url = futures[future]+ logger.exception("business_knowledge.crawl.unexpected_error", url=url)+ outcome = CrawlOutcome(url=url, final_url=url, status="error", error=str(exc))+ results.append(outcome)+ for future in not_done:+ future.cancel()+ url = futures[future]+ logger.warning("business_knowledge.crawl.timeout", url=url)+ results.append(CrawlOutcome(url=url, final_url=url, status="error", error="Crawl total timeout exceeded"))+ finally:+ # Don't block on still-running threads — let them drain in the+ # background. cancel_futures=True drops queued-but-not-started work.+ pool.shutdown(wait=False, cancel_futures=True)+ return resultsdiff --git a/products/business_knowledge/backend/discover.py b/products/business_knowledge/backend/discover.pynew file mode 100644index 000000000000..fcd746a347c0--- /dev/null+++ b/products/business_knowledge/backend/discover.py@@ -0,0 +1,300 @@+"""+URL discovery for Stage 2b crawl modes.++Three strategies, all returning a deduped, glob-filtered, capped list of+absolute URLs:++- `sitemap`: parse sitemap.xml (+ sitemap indexes) anchored at the entry URL.+- `same_origin`: BFS from the entry URL, staying on the same scheme/host/port,+ honoring robots.txt.+- `github_repo`: Reserved — raises NotImplementedError so we fail cleanly if+ someone sets the enum without having built the discovery path.++Only `logic.py` is allowed to import this module. Errors bubble as+`DiscoverError` with user-safe messages.+"""++from __future__ import annotations++import fnmatch+import urllib.parse as urlparse+import urllib.robotparser+from collections import deque+from collections.abc import Iterable+from dataclasses import dataclass++import structlog+import defusedxml.ElementTree as ET+from bs4 import BeautifulSoup+from defusedxml.ElementTree import ParseError as DefusedParseError++from .constants import CRAWL_HARD_MAX_DEPTH, DEFAULT_CRAWL_MAX_DEPTH, HARD_DISCOVER_CAP, URL_BOT_NAME, URL_MAX_BYTES+from .url_fetch import UrlFetchError, fetch_text++logger = structlog.get_logger(__name__)+++class DiscoverError(Exception):+ """User-safe discover failure. No server detail in the message."""+++@dataclass(frozen=True)+class CrawlConfig:+ """+ Validated crawl knobs. The serializer is the single layer responsible+ for constructing one of these — logic/discover never accepts a raw dict.+ """++ include_globs: tuple[str, ...] = ()+ exclude_globs: tuple[str, ...] = ()+ max_depth: int = DEFAULT_CRAWL_MAX_DEPTH+ max_pages: int = 50+++# --- Sitemap discovery -------------------------------------------------------+++_SITEMAP_NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}+++def _http_get_text(url: str, *, max_bytes: int = URL_MAX_BYTES) -> str:+ """+ Thin wrapper around `url_fetch.fetch_text` that translates+ `UrlFetchError` into `DiscoverError` for callers in this module.+ """++ try:+ return fetch_text(url, max_bytes=max_bytes)+ except UrlFetchError as exc:+ raise DiscoverError(str(exc)) from exc+++def _parse_sitemap_xml(xml_text: str) -> tuple[list[str], list[str]]:+ """+ Parse one sitemap document. Returns (urls, sub_sitemaps).++ Supports both `<urlset>` (URLs) and `<sitemapindex>` (indexes) per the+ sitemaps.org schema. Malformed XML is a user-safe error — we never+ reveal parser internals.+ """++ try:+ root = ET.fromstring(xml_text)+ except DefusedParseError as exc:+ # defusedxml rejects billion-laughs / external-entity attacks here —+ # treat everything the parser refuses as "not a sitemap".+ raise DiscoverError("Sitemap is not valid XML.") from exc++ # Strip namespace so we don't care about prefix variations.+ tag = root.tag.split("}", 1)[-1] if "}" in root.tag else root.tag++ urls: list[str] = []+ subs: list[str] = []+ if tag == "urlset":+ for loc in root.iterfind(".//sm:url/sm:loc", _SITEMAP_NS) or []:+ if loc.text:+ urls.append(loc.text.strip())+ elif tag == "sitemapindex":+ for loc in root.iterfind(".//sm:sitemap/sm:loc", _SITEMAP_NS) or []:+ if loc.text:+ subs.append(loc.text.strip())+ else:+ # Some sites serve sitemap.xml without xmlns. Fall back to a tag scan.+ for loc in root.iter():+ local = loc.tag.split("}", 1)[-1] if "}" in loc.tag else loc.tag+ if local == "loc" and loc.text:+ urls.append(loc.text.strip())+ return urls, subs+++def _discover_sitemap(entry_url: str, *, config: CrawlConfig) -> list[str]:+ """+ Fetch the sitemap at `entry_url` (or `<origin>/sitemap.xml` if the user+ gave us an HTML page), follow one level of sitemap-index children, and+ return the flat URL list (unfiltered, uncapped — filter/cap happens in+ `discover()`).+ """++ # If the user gave us a page URL, try sitemap.xml at the origin root.+ parsed = urlparse.urlparse(entry_url)+ if not parsed.path.lower().endswith((".xml", ".xml.gz")):+ origin = f"{parsed.scheme}://{parsed.netloc}"+ candidate = urlparse.urljoin(origin + "/", "sitemap.xml")+ else:+ candidate = entry_url++ xml_text = _http_get_text(candidate)+ urls, subs = _parse_sitemap_xml(xml_text)++ # One level of sitemap-index unfurling. A huge site usually has nested+ # indexes (products, docs, blog). Deeper nesting is rare; we cap at 1 to+ # keep the total network IO bounded on discover.+ for sub in subs[: min(config.max_pages, HARD_DISCOVER_CAP)]:+ if len(urls) >= HARD_DISCOVER_CAP:+ break+ try:+ child = _http_get_text(sub)+ child_urls, _ = _parse_sitemap_xml(child)+ urls.extend(child_urls)+ except DiscoverError:+ # A broken child sitemap shouldn't tank the whole discover.+ # Log and move on.+ logger.info("business_knowledge.discover.sitemap_child_failed", sub=sub)+ continue+ return urls+++# --- Same-origin BFS ---------------------------------------------------------+++def _origin_of(url: str) -> tuple[str, str, int | None]:+ parsed = urlparse.urlparse(url)+ return (parsed.scheme.lower(), (parsed.hostname or "").lower(), parsed.port)+++def _extract_links(html: str, base_url: str, same_origin: tuple[str, str, int | None]) -> list[str]:+ """+ Pull all `<a href>` links from `html`, resolve relative hrefs against+ `base_url`, drop anything not on the same origin. Fragments are stripped+ so `/foo` and `/foo#bar` collapse to one URL.+ """++ try:+ soup = BeautifulSoup(html, "html.parser")+ except Exception:+ return []++ out: list[str] = []+ for tag in soup.find_all("a", href=True):+ href = tag["href"].strip()+ if not href or href.startswith(("mailto:", "javascript:", "tel:")):+ continue+ joined = urlparse.urljoin(base_url, href)+ # Strip fragment.+ joined = joined.split("#", 1)[0]+ if _origin_of(joined) != same_origin:+ continue+ if urlparse.urlparse(joined).scheme not in ("http", "https"):+ continue+ out.append(joined)+ return out+++def _load_robots(origin: str) -> urllib.robotparser.RobotFileParser | None:+ """+ Best-effort robots.txt load. Missing / broken robots.txt is treated as+ allow-all (RFC-consistent for malformed robots). We keep the parser+ cached per-origin in the caller.+ """++ parser = urllib.robotparser.RobotFileParser()+ try:+ text = _http_get_text(f"{origin}/robots.txt", max_bytes=256 * 1024)+ except DiscoverError:+ return None+ parser.parse(text.splitlines())+ return parser+++def _discover_same_origin(entry_url: str, *, config: CrawlConfig) -> list[str]:+ """+ BFS crawler scoped to the entry URL's (scheme, host, port). Respects+ robots.txt when available. Stops at `config.max_depth` or when we hit+ `HARD_DISCOVER_CAP` — whichever comes first.+ """++ origin_tuple = _origin_of(entry_url)+ origin = f"{origin_tuple[0]}://{urlparse.urlparse(entry_url).netloc}"+ robots = _load_robots(origin)++ max_depth = max(0, min(config.max_depth, CRAWL_HARD_MAX_DEPTH))++ seen: set[str] = set()+ out: list[str] = []+ queue: deque[tuple[str, int]] = deque([(entry_url, 0)])+ seen.add(entry_url)+ while queue and len(out) < min(config.max_pages, HARD_DISCOVER_CAP):+ url, depth = queue.popleft()+ # Use the short bot token (not the full UA string) — urllib.robotparser+ # prefix-matches this against `User-agent:` lines in robots.txt.+ if robots is not None and not robots.can_fetch(URL_BOT_NAME, url):+ continue+ out.append(url)+ if depth >= max_depth:+ continue+ try:+ html = _http_get_text(url)+ except DiscoverError:+ # One bad page shouldn't tank the crawl.+ continue+ for link in _extract_links(html, url, origin_tuple):+ if link in seen:+ continue+ seen.add(link)+ queue.append((link, depth + 1))+ return out+++# --- Glob filter + public entry point ---------------------------------------+++def _matches_any(path: str, globs: Iterable[str]) -> bool:+ return any(fnmatch.fnmatchcase(path, g) for g in globs)+++def _apply_globs(urls: list[str], config: CrawlConfig) -> list[str]:+ """+ Include/exclude globs run against the URL *path* (not the full URL), so+ users don't have to care about protocol/host when filtering.++ - `include_globs=()` means "include everything".+ - `exclude_globs=()` means "exclude nothing".+ - Exclude wins over include when both match.+ """++ if not config.include_globs and not config.exclude_globs:+ return urls++ filtered: list[str] = []+ for url in urls:+ path = urlparse.urlparse(url).path or "/"+ if config.include_globs and not _matches_any(path, config.include_globs):+ continue+ if config.exclude_globs and _matches_any(path, config.exclude_globs):+ continue+ filtered.append(url)+ return filtered+++def _dedupe_preserving_order(urls: list[str]) -> list[str]:+ seen: set[str] = set()+ out: list[str] = []+ for u in urls:+ if u in seen:+ continue+ seen.add(u)+ out.append(u)+ return out+++def discover(mode: str, entry_url: str, config: CrawlConfig) -> list[str]:+ """+ Entry point for `logic.py`. Dispatches on `mode`, dedupes, applies+ include/exclude globs, truncates to `max_pages`, and returns a list of+ absolute URLs ready for the fetch loop.++ Never returns more than `min(max_pages, MAX_URLS_PER_SOURCE)` URLs.+ """++ if mode == "sitemap":+ raw = _discover_sitemap(entry_url, config=config)+ elif mode == "same_origin":+ raw = _discover_same_origin(entry_url, config=config)+ elif mode == "github_repo":+ raise NotImplementedError("github_repo crawl mode is not yet supported")+ else:+ raise DiscoverError(f"Unsupported crawl mode: {mode}")++ deduped = _dedupe_preserving_order(raw)+ filtered = _apply_globs(deduped, config)+ return filtered[: config.max_pages]diff --git a/products/business_knowledge/backend/facade/__init__.py b/products/business_knowledge/backend/facade/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/business_knowledge/backend/facade/api.py b/products/business_knowledge/backend/facade/api.pydeleted file mode 100644index cf48a1d38c88..000000000000--- a/products/business_knowledge/backend/facade/api.py+++ /dev/null@@ -1,24 +0,0 @@-"""-Facade for business_knowledge.--This is the ONLY module other products are allowed to import.--Responsibilities:-- Accept frozen dataclasses as input parameters-- Call business logic (logic.py)-- Convert Django models to frozen dataclasses before returning-- Enforce transactions where needed-- Remain thin and stable--Do NOT:-- Implement business logic here (use logic.py)-- Import DRF, serializers, or HTTP concerns-- Return ORM instances or QuerySets-"""---# --- Converters (model -> frozen dataclass) ----#-# These look repetitive when fields align 1:1. The value is having ONE place-# where "internal" becomes "external contract". When models and contracts drift,-# the mapper absorbs the change instead of it leaking everywhere.diff --git a/products/business_knowledge/backend/facade/contracts.py b/products/business_knowledge/backend/facade/contracts.pydeleted file mode 100644index 973272ba47a3..000000000000--- a/products/business_knowledge/backend/facade/contracts.py+++ /dev/null@@ -1,13 +0,0 @@-"""-Contract types for business_knowledge.--Stable, framework-free frozen dataclasses that define what this-product exposes to the rest of the codebase.--Characteristics:-- No Django imports-- Immutable (frozen=True)-- Used by facade as inputs/outputs--Do NOT depend on Django models, DRF serializers, or request objects.-"""diff --git a/products/business_knowledge/backend/facade/enums.py b/products/business_knowledge/backend/facade/enums.pydeleted file mode 100644index ce461d0a2967..000000000000--- a/products/business_knowledge/backend/facade/enums.py+++ /dev/null@@ -1,13 +0,0 @@-"""-Exported enums and constants for business_knowledge.--Small products can keep enums in contracts.py instead. Split-into this file when contracts.py gets crowded.--Rule: if an enum appears in a contract dataclass field, it-belongs here (or in contracts.py). Shared types that other-products need to interpret contract objects also belong here.--Internal-only constants (DB magic values, feature flags, etc.)-should stay in the implementation (logic.py, models.py).-"""diff --git a/products/business_knowledge/backend/file_parse.py b/products/business_knowledge/backend/file_parse.pynew file mode 100644index 000000000000..81751ac67190--- /dev/null+++ b/products/business_knowledge/backend/file_parse.py@@ -0,0 +1,319 @@+"""+File parsing for business_knowledge Stage 3.++Detects file types from content (magic bytes), not from HTTP headers or file+extensions alone. Enforces compressed + decompressed size caps. Delegates to+type-specific parsers that produce plain text suitable for the shared chunker.++Security notes:+- Compressed size is checked at the serializer layer before data reaches here.+- Magic-bytes detection prevents content-type spoofing (renaming a .exe to .pdf).+- ZIP-based formats (DOCX) are checked for decompressed size before parsing+ to guard against zip bombs.+- Encrypted PDFs are rejected with a clear error.+"""++from __future__ import annotations++import io+import os+import csv+import zipfile+from collections.abc import Callable+from dataclasses import dataclass, field++import structlog+from docx import Document+from docx.opc.exceptions import PackageNotFoundError+from pypdf import PdfReader+from pypdf.errors import PdfReadError++from .constants import MAX_FILE_DECOMPRESSED_BYTES, MAX_FILE_SIZE_BYTES++logger = structlog.get_logger(__name__)+++class FileParseError(Exception):+ """User-safe error from file parsing."""+++class UnsupportedFileTypeError(FileParseError):+ pass+++class EncryptedPDFError(FileParseError):+ pass+++class ZipBombError(FileParseError):+ pass+++class FileTooLargeError(FileParseError):+ pass+++ALLOWED_TYPES: dict[str, str] = {+ "application/pdf": "PDF",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "DOCX",+ "text/markdown": "Markdown",+ "text/plain": "Plain text",+ "text/csv": "CSV",+}++MAX_CSV_ROWS = 10_000+MAX_PDF_PAGES = 2_000+++@dataclass(frozen=True)+class ParsedFile:+ title: str+ content: str+ content_type: str+ metadata: dict = field(default_factory=dict)+++# ---------------------------------------------------------------------------+# Detection+# ---------------------------------------------------------------------------+++def detect_content_type(data: bytes, filename: str) -> str:+ """+ Detect content type from magic bytes first, then fall back to extension+ for text-based formats that lack distinctive magic bytes.+ """+ if data[:5] == b"%PDF-":+ return "application/pdf"++ if data[:2] == b"PK":+ _check_zip_bomb(data)+ try:+ with zipfile.ZipFile(io.BytesIO(data)) as zf:+ if "[Content_Types].xml" in zf.namelist():+ with zf.open("[Content_Types].xml") as ct_file:+ ct = ct_file.read(4096).decode("utf-8", errors="replace")+ if "wordprocessingml" in ct:+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ except (zipfile.BadZipFile, KeyError, OSError):+ pass++ lower = os.path.basename(filename).lower()+ if lower.endswith((".md", ".markdown")):+ return "text/markdown"+ if lower.endswith(".csv"):+ return "text/csv"+ if lower.endswith(".txt"):+ return "text/plain"++ # Last resort: if it decodes as UTF-8, treat as plain text.+ try:+ data[:8192].decode("utf-8")+ return "text/plain"+ except UnicodeDecodeError:+ pass++ raise UnsupportedFileTypeError("Unsupported file type. Allowed: PDF, DOCX, Markdown (.md), CSV, plain text (.txt).")+++# ---------------------------------------------------------------------------+# Security guards+# ---------------------------------------------------------------------------+++def _check_zip_bomb(data: bytes) -> None:+ try:+ with zipfile.ZipFile(io.BytesIO(data)) as zf:+ total = 0+ for info in zf.infolist():+ with zf.open(info) as f:+ while chunk := f.read(65536):+ total += len(chunk)+ if total > MAX_FILE_DECOMPRESSED_BYTES:+ raise ZipBombError(+ f"Decompressed size exceeds the {MAX_FILE_DECOMPRESSED_BYTES // (1024 * 1024)} MB cap."+ )+ except zipfile.BadZipFile:+ raise FileParseError("File appears corrupt — cannot read as ZIP.")+ except (RuntimeError, NotImplementedError):+ raise FileParseError("File is encrypted or uses an unsupported compression method.")+++def sanitize_filename(filename: str) -> str:+ """Strip path components, null bytes; cap length."""+ name = filename.replace("\\", "/")+ name = os.path.basename(name)+ name = name.replace("\x00", "")+ return name[:255] if name else "unnamed"+++def _title_from_filename(filename: str) -> str:+ return filename.rsplit(".", 1)[0] if "." in filename else filename+++# ---------------------------------------------------------------------------+# Parsers+# ---------------------------------------------------------------------------+++def _parse_pdf(data: bytes, filename: str) -> ParsedFile:+ try:+ reader = PdfReader(io.BytesIO(data))+ except PdfReadError as exc:+ raise FileParseError(f"Could not read PDF: {exc}")++ if reader.is_encrypted:+ raise EncryptedPDFError("Encrypted PDFs are not supported. Remove the password and re-upload.")++ if len(reader.pages) > MAX_PDF_PAGES:+ raise FileTooLargeError(+ f"PDF has {len(reader.pages):,} pages (cap is {MAX_PDF_PAGES:,}). Split it into smaller files."+ )++ pages: list[str] = []+ for i, page in enumerate(reader.pages):+ text = page.extract_text() or ""+ if text.strip():+ pages.append(f"[Page {i + 1}]\n{text.strip()}")++ content = "\n\n".join(pages)+ if not content.strip():+ raise FileParseError("PDF contains no extractable text (it may be scanned/image-only).")++ return ParsedFile(+ title=_title_from_filename(filename),+ content=content,+ content_type="application/pdf",+ metadata={"source_type": "file", "file_type": "pdf", "page_count": len(reader.pages)},+ )+++def _parse_docx(data: bytes, filename: str) -> ParsedFile:+ try:+ doc = Document(io.BytesIO(data))+ except PackageNotFoundError as exc:+ raise FileParseError(f"Could not read DOCX: {exc}")+ except (KeyError, ValueError, zipfile.BadZipFile) as exc:+ raise FileParseError(f"Could not read DOCX: {exc}")++ parts: list[str] = []+ for para in doc.paragraphs:+ text = para.text.strip()+ if not text:+ continue+ style_name = (para.style.name or "").lower() if para.style else ""+ if "heading" in style_name:+ level = 1+ for ch in style_name:+ if ch.isdigit():+ level = int(ch)+ break+ parts.append(f"{'#' * level} {text}")+ else:+ parts.append(text)++ content = "\n\n".join(parts)+ if not content.strip():+ raise FileParseError("DOCX contains no extractable text.")++ return ParsedFile(+ title=_title_from_filename(filename),+ content=content,+ content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ metadata={"source_type": "file", "file_type": "docx"},+ )+++def _parse_markdown(data: bytes, filename: str) -> ParsedFile:+ text = data.decode("utf-8", errors="replace")+ if not text.strip():+ raise FileParseError("Markdown file is empty.")++ return ParsedFile(+ title=_title_from_filename(filename),+ content=text,+ content_type="text/markdown",+ metadata={"source_type": "file", "file_type": "markdown"},+ )+++def _parse_txt(data: bytes, filename: str) -> ParsedFile:+ text = data.decode("utf-8", errors="replace")+ if not text.strip():+ raise FileParseError("Text file is empty.")++ return ParsedFile(+ title=_title_from_filename(filename),+ content=text,+ content_type="text/plain",+ metadata={"source_type": "file", "file_type": "txt"},+ )+++def _parse_csv(data: bytes, filename: str) -> ParsedFile:+ text = data.decode("utf-8", errors="replace")+ if not text.strip():+ raise FileParseError("CSV file is empty.")++ try:+ reader = csv.DictReader(io.StringIO(text))+ if reader.fieldnames is None:+ raise FileParseError("CSV has no header row.")++ rows: list[str] = []+ for i, row in enumerate(reader):+ if i >= MAX_CSV_ROWS:+ rows.append(f"[Truncated at {MAX_CSV_ROWS:,} rows]")+ break+ line_parts = [f"{k}: {v}" for k, v in row.items() if v]+ if line_parts:+ rows.append("\n".join(line_parts))+ except csv.Error as exc:+ raise FileParseError(f"Could not parse CSV: {exc}")++ content = "\n\n".join(rows)+ if not content.strip():+ raise FileParseError("CSV contains no data rows.")++ return ParsedFile(+ title=_title_from_filename(filename),+ content=content,+ content_type="text/csv",+ metadata={"source_type": "file", "file_type": "csv", "row_count": len(rows)},+ )+++_PARSERS: dict[str, Callable[[bytes, str], ParsedFile]] = {+ "application/pdf": _parse_pdf,+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": _parse_docx,+ "text/markdown": _parse_markdown,+ "text/plain": _parse_txt,+ "text/csv": _parse_csv,+}+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def parse_file(data: bytes, filename: str) -> ParsedFile:+ """+ Detect file type and parse. Entry point for Stage 3 file ingestion.++ The caller (serializer) must enforce the compressed size cap before+ calling this function. This function enforces:+ - Content-type detection from magic bytes+ - Allowlist check+ - Decompressed size cap for ZIP-based formats+ - Type-specific parse errors (encrypted PDF, empty content)+ """+ if len(data) > MAX_FILE_SIZE_BYTES:+ raise FileTooLargeError(f"File exceeds the {MAX_FILE_SIZE_BYTES // (1024 * 1024)} MB cap.")++ content_type = detect_content_type(data, filename)+ if content_type not in ALLOWED_TYPES:+ raise UnsupportedFileTypeError(f"Unsupported file type. Allowed: {', '.join(ALLOWED_TYPES.values())}.")++ parser = _PARSERS[content_type]+ return parser(data, filename)diff --git a/products/business_knowledge/backend/html_parse.py b/products/business_knowledge/backend/html_parse.pynew file mode 100644index 000000000000..a1bdc6a5a160--- /dev/null+++ b/products/business_knowledge/backend/html_parse.py@@ -0,0 +1,95 @@+"""+HTML -> plain text normalization for URL-backed knowledge sources.++Primary extractor is trafilatura — it's specifically designed to strip+boilerplate (nav, footer, cookie banners) from article-style pages while+preserving semantic structure. Falls back to BeautifulSoup for pages where+trafilatura returns nothing (error pages, SPA shells, very minimal HTML).++Only `logic.py` is allowed to import this module.+"""++from __future__ import annotations++import structlog+import trafilatura+from bs4 import BeautifulSoup++logger = structlog.get_logger(__name__)+++def _decode(body: bytes) -> str:+ # trafilatura handles encoding detection internally, but the bs4 fallback+ # needs us to pick something. utf-8 with errors='replace' is a sensible+ # floor — we'd rather get partial garbled text than drop the whole page.+ try:+ return body.decode("utf-8")+ except UnicodeDecodeError:+ return body.decode("utf-8", errors="replace")+++def _bs4_fallback(html: str) -> str:+ """+ Last-resort extractor. Strips script/style/template nodes, then collapses+ runs of whitespace. We never return raw attributes or inline event+ handlers — those are prompt-injection vectors when shown to the LLM.+ """++ soup = BeautifulSoup(html, "html.parser")+ for node in soup(["script", "style", "template", "noscript", "iframe"]):+ node.decompose()+ text = soup.get_text(separator="\n")+ # Collapse whitespace runs without losing paragraph breaks.+ lines = [line.strip() for line in text.splitlines()]+ joined = "\n".join(line for line in lines if line)+ return joined+++def parse_html(body: bytes, url: str) -> tuple[str, str]:+ """+ Extract (title, text) from an HTML response body.++ Returns empty strings if extraction produced nothing usable — callers+ should treat that as a soft failure and store an error on the source.+ """++ html = _decode(body)++ # trafilatura.extract returns the main-content text only. We ask for+ # plain output (not XML/JSON) to keep downstream chunking dead simple.+ extracted = trafilatura.extract(+ html,+ url=url,+ include_comments=False,+ include_tables=True,+ favor_precision=True,+ output_format="txt",+ )++ title = ""+ try:+ metadata = trafilatura.extract_metadata(html)+ if metadata and metadata.title:+ title = metadata.title.strip()[:512]+ except Exception: # noqa: BLE001 — trafilatura metadata parsing can crash on malformed HTML+ logger.info("business_knowledge.html_parse.metadata_failed", url=url)++ text = (extracted or "").strip()+ if not text:+ try:+ text = _bs4_fallback(html)+ except Exception: # noqa: BLE001 — bs4 is a best-effort fallback+ logger.info("business_knowledge.html_parse.bs4_failed", url=url)+ text = ""++ if not title:+ # Extract a title from <title> as a secondary fallback — some pages+ # have no og:title / articleTitle but do have <title>.+ try:+ soup = BeautifulSoup(html, "html.parser")+ if soup.title and soup.title.string:+ title = soup.title.string.strip()[:512]+ except Exception: # noqa: BLE001+ pass++ return title, textdiff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pynew file mode 100644index 000000000000..c9d07190cf4a--- /dev/null+++ b/products/business_knowledge/backend/logic.py@@ -0,0 +1,1382 @@+"""+Business logic for business_knowledge.++All ORM access, chunking, quota enforcement, and search queries.+"""++import re+import uuid+import datetime+from dataclasses import dataclass+from functools import reduce+from operator import or_+from uuid import UUID++from django.db import (+ connection as db_connection,+ transaction,+)+from django.db.models import Count, Q+from django.utils import timezone++import structlog++from posthog.models.scoping import with_team_scope+from posthog.security.url_validation import is_url_allowed++from . import crawl, discover, file_parse, html_parse, url_fetch+from .constants import (+ CHUNK_HARD_MAX_CHARS,+ CHUNK_TARGET_CHARS,+ CRAWL_HARD_MAX_DEPTH,+ DEFAULT_CRAWL_MAX_DEPTH,+ DEFAULT_MAX_PAGES,+ MAX_CHUNKS_PER_TEAM,+ MAX_SOURCES_PER_TEAM,+ MAX_TEXT_SIZE_BYTES,+ MAX_URLS_PER_SOURCE,+)+from .models import CrawlMode, KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SourceStatus, SourceType+from .models.constants import RefreshStatus+from .url_fetch import sha256_of++logger = structlog.get_logger(__name__)++# Deterministic namespace for chunk uuid5. Rolling this breaks id stability+# across Stage 1 data — so don't. Generated once via uuid.uuid4() and frozen.+_CHUNK_NAMESPACE = UUID("4b7b0b50-5e2f-4a9f-8a8b-8b8d5f6f4a3e")+++class QuotaExceededError(Exception):+ """Raised when creating the source would exceed a per-team cap."""+++class TextTooLargeError(Exception):+ """Raw text exceeds MAX_TEXT_SIZE_BYTES."""+++class InvalidUrlError(Exception):+ """URL failed SSRF or basic validation. Message is user-safe."""+++class UrlFetchFailedError(Exception):+ """Fetch or parse failed. Message is user-safe (never includes server detail)."""+++class SourceBusyError(Exception):+ """A refresh is already running for this source."""+++class EmptyContentError(Exception):+ """Remote returned nothing usable after parsing."""+++@dataclass(frozen=True)+class _Chunk:+ heading_path: str+ ordinal: int+ content: str+++# --- Chunker -----------------------------------------------------------------+++def chunk_text(text: str) -> list[_Chunk]:+ """+ Paragraph-aware chunker for Stage 1 plain text.++ Strategy:+ - Split on blank lines (paragraph boundary).+ - Greedily pack paragraphs into buckets up to CHUNK_TARGET_CHARS.+ - If a single paragraph blows past CHUNK_HARD_MAX_CHARS, split it on+ whitespace near the boundary (best-effort, no sentence tokenizer —+ we stay dependency-free on purpose).++ No overlap between chunks. Agent search reads neighbors via ordinal+ ± 1 when it wants wider context; overlap would just bloat storage.+ """++ paragraphs = [p.strip() for p in text.replace("\r\n", "\n").split("\n\n") if p.strip()]+ buckets: list[str] = []+ current = ""++ def flush() -> None:+ nonlocal current+ if current:+ buckets.append(current)+ current = ""++ for paragraph in paragraphs:+ # Hard-split any mega paragraph before we try to pack it.+ while len(paragraph) > CHUNK_HARD_MAX_CHARS:+ cut = paragraph.rfind(" ", 0, CHUNK_HARD_MAX_CHARS)+ if cut <= 0:+ cut = CHUNK_HARD_MAX_CHARS+ head, paragraph = paragraph[:cut].rstrip(), paragraph[cut:].lstrip()+ if current:+ flush()+ buckets.append(head)++ if not current:+ current = paragraph+ elif len(current) + len(paragraph) + 2 <= CHUNK_TARGET_CHARS:+ current = f"{current}\n\n{paragraph}"+ else:+ flush()+ current = paragraph++ flush()++ return [_Chunk(heading_path="", ordinal=i, content=c) for i, c in enumerate(buckets)]+++def _chunk_id(source_id: UUID, document_stable_id: str, heading_path: str, ordinal: int) -> UUID:+ # `source_id` is in the namespace so two URL-backed sources that happen to+ # crawl the same URL don't collide on chunk UUIDs (document.stable_id == url+ # for URL sources). Text sources already have a uuid4 `stable_id`, but+ # including source_id here keeps the rule uniform.+ return uuid.uuid5(_CHUNK_NAMESPACE, f"{source_id}|{document_stable_id}|{heading_path}|{ordinal}")+++def _bulk_create_chunks(+ *,+ source: KnowledgeSource,+ document: KnowledgeDocument,+ team_id: int,+ chunks: list[_Chunk],+) -> None:+ KnowledgeChunk.objects.bulk_create(+ [+ KnowledgeChunk(+ id=_chunk_id(source.id, document.stable_id, c.heading_path, c.ordinal),+ team_id=team_id,+ source=source,+ document=document,+ heading_path=c.heading_path,+ ordinal=c.ordinal,+ content=c.content,+ char_count=len(c.content),+ )+ for c in chunks+ ]+ )+++# --- Quota enforcement -------------------------------------------------------+++def _count_sources(team_id: int) -> int:+ return KnowledgeSource.objects.filter(team_id=team_id).count()+++# Advisory-lock namespace so we don't collide with other lock users.+# pg_advisory_xact_lock takes a bigint; we combine a fixed namespace+# with team_id to get a unique key per team.+_ADVISORY_LOCK_NAMESPACE = 0x424B # "BK" for business_knowledge+++def _acquire_source_quota_lock(team_id: int) -> None:+ """+ Acquire a transaction-scoped Postgres advisory lock keyed on team_id.++ Must be called inside ``transaction.atomic()``. The lock is released+ automatically when the transaction commits or rolls back.++ This serializes concurrent source-create transactions for the same+ team, closing the READ COMMITTED phantom-read window that lets two+ concurrent creates both see ``count=499`` and both insert.+ """+ lock_id = (_ADVISORY_LOCK_NAMESPACE << 32) | (team_id & 0xFFFFFFFF)+ with db_connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s)", [lock_id])+++def _check_source_quota_locked(team_id: int, *, reject_if_processing: bool = False) -> None:+ """+ Acquire the advisory lock, then check the source count.+ Must be inside a transaction.++ When *reject_if_processing* is True, also enforces the per-team+ concurrency invariant (at most one PROCESSING source) under the+ same lock — closing the TOCTOU window between concurrent creates.++ Stale PROCESSING rows (older than ``_PROCESSING_STALENESS_MINUTES``)+ are auto-recovered to ERROR before the check so a crashed request+ doesn't permanently block new creates.+ """+ _acquire_source_quota_lock(team_id)+ if reject_if_processing:+ stale_cutoff = timezone.now() - datetime.timedelta(minutes=_PROCESSING_STALENESS_MINUTES)+ KnowledgeSource.objects.filter(+ team_id=team_id,+ status=SourceStatus.PROCESSING,+ updated_at__lt=stale_cutoff,+ ).update(+ status=SourceStatus.ERROR,+ error_message="Processing timed out. You can retry via refresh.",+ )+ if KnowledgeSource.objects.filter(team_id=team_id, status=SourceStatus.PROCESSING).exists():+ raise SourceBusyError("Another knowledge source is already being processed for this project.")+ if _count_sources(team_id) >= MAX_SOURCES_PER_TEAM:+ raise QuotaExceededError(f"Team already has {MAX_SOURCES_PER_TEAM} knowledge sources.")+++def _count_chunks(team_id: int) -> int:+ return KnowledgeChunk.objects.filter(team_id=team_id).count()+++@with_team_scope(canonical=True)+def check_text_source_quota(team_id: int, text: str) -> None:+ if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ raise TextTooLargeError(f"Text exceeds {MAX_TEXT_SIZE_BYTES} bytes. Split it into multiple sources.")+ if _count_sources(team_id) >= MAX_SOURCES_PER_TEAM:+ raise QuotaExceededError(f"Team already has {MAX_SOURCES_PER_TEAM} knowledge sources.")+ # We can't know exact chunk count before chunking, but we can cheaply+ # estimate and fail fast. The strict check happens post-chunk inside the+ # transaction.+ estimated_chunks = max(1, len(text) // CHUNK_TARGET_CHARS)+ if _count_chunks(team_id) + estimated_chunks > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Team already near the {MAX_CHUNKS_PER_TEAM} chunk cap.")+++# --- Queries -----------------------------------------------------------------+++@with_team_scope(canonical=True)+def list_for_team(team_id: int) -> list[KnowledgeSource]:+ # Annotate counts in one round-trip so the serializer doesn't N+1.+ return list(+ KnowledgeSource.objects.filter(team_id=team_id)+ .annotate(+ _document_count=Count("documents", distinct=True),+ _chunk_count=Count("chunks", distinct=True),+ )+ .order_by("-created_at")+ )+++@with_team_scope(canonical=True)+def get_for_team(source_id: UUID, team_id: int) -> KnowledgeSource | None:+ try:+ return KnowledgeSource.objects.annotate(+ _document_count=Count("documents", distinct=True),+ _chunk_count=Count("chunks", distinct=True),+ ).get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ return None+++@with_team_scope(canonical=True)+def get_source_text_for_team(source_id: UUID, team_id: int) -> str | None:+ """+ Returns the raw text of a text-type source. Stage 1 has exactly one+ document per source, so this is a single row fetch. For future URL/file+ sources with many documents, this concatenates in stable order — not a+ real "view" affordance but good enough to round-trip into the edit modal.+ """++ if not KnowledgeSource.objects.filter(id=source_id, team_id=team_id).exists():+ return None+ documents = KnowledgeDocument.objects.filter(team_id=team_id, source_id=source_id).order_by("created_at")+ return "\n\n".join(d.content for d in documents)+++# --- Mutations ---------------------------------------------------------------+++@with_team_scope(canonical=True)+def create_text_source(+ *,+ team_id: int,+ created_by_id: int | None,+ name: str,+ text: str,+) -> KnowledgeSource:+ """+ Stage 1 happy path: create source + 1 document + N chunks synchronously.++ Inline, not Temporal. Text parsing is pure CPU and quick; adding a+ workflow for every text paste burns latency for zero gain.+ """++ check_text_source_quota(team_id, text)++ _check_source_quota_locked(team_id)+ source = KnowledgeSource.objects.create(+ team_id=team_id,+ created_by_id=created_by_id,+ name=name,+ source_type=SourceType.TEXT,+ status=SourceStatus.PROCESSING,+ )++ # One text source == one document. Stable_id is the document's own UUID,+ # which means re-saving the same text to a new source gets a fresh stable_id+ # (that's intentional — two sources with identical text are two logical+ # entries, not a dedup target).+ document_id = uuid.uuid4()+ document = KnowledgeDocument.objects.create(+ id=document_id,+ team_id=team_id,+ source=source,+ stable_id=str(document_id),+ title=name,+ content=text,+ metadata={"source_type": SourceType.TEXT},+ )++ chunks = chunk_text(text)+ if _count_chunks(team_id) + len(chunks) > MAX_CHUNKS_PER_TEAM:+ # Roll back — transaction will undo source + document.+ raise QuotaExceededError(f"Text produces more chunks than the remaining team budget.")++ _bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)++ source.status = SourceStatus.READY+ source.save(update_fields=["status", "updated_at"])+ # Refresh annotations so the returned instance has accurate counts.+ return get_for_team(source.id, team_id) or source+++@with_team_scope(canonical=True)+def update_text_source(+ *,+ source_id: UUID,+ team_id: int,+ name: str | None,+ text: str | None,+) -> KnowledgeSource | None:+ """+ Stage 1 edit path.++ - name-only edit: single UPDATE, no re-chunk.+ - text edit: delete documents+chunks for this source and rebuild from the+ new content. We keep the source row (and its id) so agents' in-flight+ prompts don't go stale on re-lookup. Same byte/chunk quota rules apply+ to the new text.++ Returns the refreshed source (with annotated counts) or None if the+ source doesn't belong to this team.+ """++ try:+ source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ return None++ if text is not None:+ if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ raise TextTooLargeError(f"Text exceeds {MAX_TEXT_SIZE_BYTES} bytes.")+ chunks = chunk_text(text)+ # Post-chunk budget check. Existing chunks for this source are about to+ # be deleted, so subtract them before comparing to the cap.+ existing_chunks_for_source = KnowledgeChunk.objects.filter(team_id=team_id, source_id=source_id).count()+ if _count_chunks(team_id) - existing_chunks_for_source + len(chunks) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Team already near the {MAX_CHUNKS_PER_TEAM} chunk cap.")++ source.status = SourceStatus.PROCESSING+ update_fields = ["status", "updated_at"]+ if name is not None:+ source.name = name+ update_fields.append("name")+ source.save(update_fields=update_fields)++ KnowledgeChunk.objects.filter(team_id=team_id, source_id=source_id).delete()+ KnowledgeDocument.objects.filter(team_id=team_id, source_id=source_id).delete()++ document_id = uuid.uuid4()+ document = KnowledgeDocument.objects.create(+ id=document_id,+ team_id=team_id,+ source=source,+ stable_id=str(document_id),+ title=name if name is not None else source.name,+ content=text,+ metadata={"source_type": SourceType.TEXT},+ )+ _bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)+ source.status = SourceStatus.READY+ source.save(update_fields=["status", "updated_at"])+ elif name is not None:+ source.name = name+ source.save(update_fields=["name", "updated_at"])++ return get_for_team(source.id, team_id) or source+++@with_team_scope(canonical=True)+def update_url_source(+ *,+ source_id: UUID,+ team_id: int,+ name: str | None = None,+ url: str | None = None,+ crawl_mode: str | None = None,+ crawl_config: dict | None = None,+) -> KnowledgeSource | None:+ """+ Update a URL source's metadata and optionally re-crawl.++ - name-only: single UPDATE, no network.+ - url/crawl_mode/crawl_config change: update the fields, then trigger a+ full refresh so the content matches the new config.+ """+ try:+ source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ return None+ if source.source_type != SourceType.URL:+ raise InvalidUrlError("Can only update URL sources with this endpoint.")++ needs_recrawl = False+ update_fields: list[str] = ["updated_at"]+ old_values: dict[str, object] = {}++ if name is not None and name != source.name:+ source.name = name+ update_fields.append("name")++ if url is not None and url != source.source_url:+ normalized = _validate_url(url)+ old_values["source_url"] = source.source_url+ source.source_url = normalized+ update_fields.append("source_url")+ needs_recrawl = True++ if crawl_mode is not None and crawl_mode != source.crawl_mode:+ old_values["crawl_mode"] = source.crawl_mode+ source.crawl_mode = crawl_mode+ update_fields.append("crawl_mode")+ needs_recrawl = True++ if crawl_config is not None:+ merged = {**(source.crawl_config or {}), **crawl_config}+ if merged != source.crawl_config:+ old_values["crawl_config"] = source.crawl_config+ source.crawl_config = merged+ update_fields.append("crawl_config")+ needs_recrawl = True++ if len(update_fields) > 1:+ source.save(update_fields=update_fields)++ if needs_recrawl:+ try:+ return refresh_source(source_id=source.id, team_id=team_id)+ except SourceBusyError:+ # Refresh never started — revert config so the source doesn't+ # end up with a new URL but old content and no error signal.+ for field, value in old_values.items():+ setattr(source, field, value)+ source.save(update_fields=[*list(old_values.keys()), "updated_at"])+ raise++ return get_for_team(source.id, team_id) or source+++@with_team_scope(canonical=True)+def delete_source(source_id: UUID, team_id: int) -> bool:+ try:+ source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ return False+ source.delete()+ return True+++# --- Stage 3: file sources ----------------------------------------------------+++@with_team_scope(canonical=True)+def create_file_source(+ *,+ team_id: int,+ created_by_id: int | None,+ name: str,+ file_data: bytes,+ original_filename: str,+) -> KnowledgeSource:+ """+ Stage 3 file ingestion: detect type → parse → chunk. Inline, not Temporal.++ The caller (serializer) already enforced the compressed size cap. This+ function detects the content type from magic bytes, parses the file into+ plain text, chunks it, and persists source + doc + chunks atomically.+ """++ if _count_sources(team_id) >= MAX_SOURCES_PER_TEAM:+ raise QuotaExceededError(f"Team already has {MAX_SOURCES_PER_TEAM} knowledge sources.")++ parsed = file_parse.parse_file(file_data, original_filename)+ text = parsed.content++ if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ raise file_parse.FileTooLargeError(+ f"Parsed content exceeds the {MAX_TEXT_SIZE_BYTES // (1024 * 1024)} MB text cap. "+ "Try a shorter document or split it into multiple sources."+ )++ chunks = chunk_text(text)+ content_hash = sha256_of(text)++ with transaction.atomic():+ _check_source_quota_locked(team_id)+ source = KnowledgeSource.objects.create(+ team_id=team_id,+ created_by_id=created_by_id,+ name=name,+ source_type=SourceType.FILE,+ status=SourceStatus.PROCESSING,+ original_filename=file_parse.sanitize_filename(original_filename),+ file_content_type=parsed.content_type,+ file_size_bytes=len(file_data),+ )++ if _count_chunks(team_id) + len(chunks) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError("File produces more chunks than the remaining team budget.")++ document_id = uuid.uuid4()+ document = KnowledgeDocument.objects.create(+ id=document_id,+ team_id=team_id,+ source=source,+ stable_id=str(document_id),+ title=parsed.title,+ content=text,+ metadata=parsed.metadata,+ content_hash=content_hash,+ )++ _bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)++ source.status = SourceStatus.READY+ source.save(update_fields=["status", "updated_at"])++ return get_for_team(source.id, team_id) or source+++# --- Stage 2a: URL sources ---------------------------------------------------+++def _validate_url(url: str) -> str:+ """Normalize + SSRF check. Raises InvalidUrlError on failure."""++ try:+ normalized = url_fetch.normalize_url(url)+ except url_fetch.UrlFetchError:+ raise InvalidUrlError("Invalid URL.")+ allowed, _reason = is_url_allowed(normalized)+ if not allowed:+ raise InvalidUrlError("URL is not reachable from this environment.")+ return normalized+++_PROCESSING_STALENESS_MINUTES = 10+++def _resolve_crawl_config(raw: dict | None) -> discover.CrawlConfig:+ """+ Turn a stored/user-supplied dict into a validated ``CrawlConfig``. Applies+ hard caps defensively — we don't trust stored values not to drift past+ caps when the caps get lowered.++ All conversions are wrapped in try/except so corrupt JSON (e.g. from+ a manual admin edit) falls back to safe defaults instead of 500-ing.+ """++ if not isinstance(raw, dict):+ raw = {}+ else:+ raw = raw or {}+ try:+ max_pages = int(raw.get("max_pages", DEFAULT_MAX_PAGES))+ except (TypeError, ValueError):+ max_pages = DEFAULT_MAX_PAGES+ max_pages = max(1, min(max_pages, MAX_URLS_PER_SOURCE))++ try:+ max_depth = int(raw.get("max_depth", DEFAULT_CRAWL_MAX_DEPTH))+ except (TypeError, ValueError):+ max_depth = DEFAULT_CRAWL_MAX_DEPTH+ max_depth = max(0, min(max_depth, CRAWL_HARD_MAX_DEPTH))++ include_raw = raw.get("include_globs") or []+ exclude_raw = raw.get("exclude_globs") or []+ include_globs = tuple(str(g) for g in include_raw if isinstance(g, str))+ exclude_globs = tuple(str(g) for g in exclude_raw if isinstance(g, str))++ return discover.CrawlConfig(+ include_globs=include_globs,+ exclude_globs=exclude_globs,+ max_depth=max_depth,+ max_pages=max_pages,+ )+++def _fetch_and_parse(url: str, *, etag: str | None) -> tuple[url_fetch.FetchResult, str, str]:+ """+ Fetch + parse for create/refresh paths. Returns (fetch_result, title, text).+ Raises UrlFetchFailedError / EmptyContentError on bad input.++ On 304 returns empty (title, text) — caller must check fetch.status first.+ """++ try:+ result = url_fetch.fetch_url(url, etag=etag)+ except url_fetch.UrlFetchError as exc:+ raise UrlFetchFailedError(str(exc))++ if result.status == 304:+ return result, "", ""++ if not result.body:+ raise EmptyContentError("Remote response was empty.")++ if not url_fetch.is_html_content_type(result.content_type):+ raise UrlFetchFailedError("Unsupported content type.")++ title, text = html_parse.parse_html(result.body, result.final_url)+ if not text.strip():+ raise EmptyContentError("Could not extract any text from the URL.")+ if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ # Trim rather than refuse — a 2MB Wikipedia page is still useful.+ # Cut on a character boundary within the byte budget.+ raise UrlFetchFailedError("URL content exceeds the maximum allowed size.")+ return result, title, text+++def _replace_source_content(+ *,+ source: KnowledgeSource,+ team_id: int,+ title: str,+ text: str,+ url: str,+ etag: str,+ content_hash: str,+) -> None:+ """+ Delete existing documents+chunks for `source` and create a fresh 1-doc/+ N-chunk set from the given text. Must be called inside a transaction.++ The chunk count budget is enforced here (after we already know the exact+ count). Existing chunks for this source are subtracted before comparison.+ """++ chunks = chunk_text(text)+ existing_chunks_for_source = KnowledgeChunk.objects.filter(team_id=team_id, source_id=source.id).count()+ if _count_chunks(team_id) - existing_chunks_for_source + len(chunks) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Team already near the {MAX_CHUNKS_PER_TEAM} chunk cap.")++ KnowledgeChunk.objects.filter(team_id=team_id, source_id=source.id).delete()+ KnowledgeDocument.objects.filter(team_id=team_id, source_id=source.id).delete()++ document_id = uuid.uuid4()+ # stable_id = normalized URL so Stage 2b crawls can upsert by (source, url)+ # and a re-fetch of the same URL keeps the same identity — helps agents+ # that cache by document id across refreshes.+ document = KnowledgeDocument.objects.create(+ id=document_id,+ team_id=team_id,+ source=source,+ stable_id=url,+ title=title or source.name,+ content=text,+ metadata={"source_type": SourceType.URL, "url": url},+ url=url,+ etag=etag,+ content_hash=content_hash,+ )+ _bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)+++@with_team_scope(canonical=True)+def create_url_source(+ *,+ team_id: int,+ created_by_id: int | None,+ name: str,+ url: str,+) -> KnowledgeSource:+ """+ Stage 2a URL ingestion: claim → fetch → parse → chunk.++ A PROCESSING claim row is created *before* the network fetch so+ concurrent requests for the same team are serialized by the advisory+ lock + PROCESSING-state check. The fetch runs outside any transaction+ so a slow remote doesn't hold row-level locks.+ """++ normalized = _validate_url(url)++ with transaction.atomic():+ _check_source_quota_locked(team_id, reject_if_processing=True)+ source = KnowledgeSource.objects.create(+ team_id=team_id,+ created_by_id=created_by_id,+ name=name,+ source_type=SourceType.URL,+ status=SourceStatus.PROCESSING,+ source_url=normalized,+ )++ try:+ result, title, text = _fetch_and_parse(normalized, etag=None)+ except (UrlFetchFailedError, EmptyContentError) as exc:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ now = timezone.now()+ fresh.status = SourceStatus.ERROR+ fresh.error_message = str(exc)+ fresh.last_refresh_at = now+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = str(exc)+ fresh.save(+ update_fields=[+ "status",+ "error_message",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )+ return get_for_team(source.id, team_id) or source++ content_hash = sha256_of(text)+ try:+ with transaction.atomic():+ _replace_source_content(+ source=source,+ team_id=team_id,+ title=title,+ text=text,+ url=result.final_url,+ etag=result.etag or "",+ content_hash=content_hash,+ )+ source.status = SourceStatus.READY+ source.last_refresh_at = timezone.now()+ source.last_refresh_status = RefreshStatus.SUCCESS+ source.last_refresh_error = ""+ source.last_etag = result.etag or ""+ source.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "last_etag",+ "updated_at",+ ]+ )+ except QuotaExceededError:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh.status = SourceStatus.ERROR+ fresh.error_message = "Quota exceeded"+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = "Quota exceeded"+ fresh.save(+ update_fields=[+ "status",+ "error_message",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )+ raise++ return get_for_team(source.id, team_id) or source+++@with_team_scope(canonical=True)+def refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSource | None:+ """+ Re-fetch a URL source and rebuild its content if it changed.++ Dispatches on `crawl_mode`:+ - `single` (Stage 2a): single-URL conditional GET + full doc rebuild.+ - `sitemap` / `same_origin` (Stage 2b): re-discover + per-URL upsert.+ """++ # Acquire the per-team advisory lock and enforce the single-PROCESSING+ # invariant before claiming this source. This prevents concurrent refreshes+ # of different sources on the same team from each tying up a Django worker.+ with transaction.atomic():+ _check_source_quota_locked(team_id, reject_if_processing=True)+ try:+ source = KnowledgeSource.objects.select_for_update().get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ return None+ if source.source_type != SourceType.URL or not source.source_url:+ raise InvalidUrlError("Only URL sources can be refreshed.")+ if source.status == SourceStatus.PROCESSING:+ raise SourceBusyError("This source is already refreshing.")+ source.status = SourceStatus.PROCESSING+ source.save(update_fields=["status", "updated_at"])++ try:+ if source.crawl_mode and source.crawl_mode != CrawlMode.SINGLE:+ return _refresh_crawl_source(source=source, team_id=team_id)+ return _refresh_single_source(source=source, team_id=team_id)+ except QuotaExceededError:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh.status = SourceStatus.READY if fresh.documents.exists() else SourceStatus.ERROR+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = "Quota exceeded"+ if fresh.status == SourceStatus.ERROR:+ fresh.error_message = "Quota exceeded"+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "error_message",+ "updated_at",+ ]+ )+ raise+++def _refresh_single_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSource | None:+ try:+ # Re-validate the URL before every fetch — we don't assume stored URLs+ # are still safe (DNS may have been rebound since create time).+ normalized = _validate_url(source.source_url)+ result, title, text = _fetch_and_parse(normalized, etag=source.last_etag or None)+ except (InvalidUrlError, UrlFetchFailedError, EmptyContentError) as exc:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ # Leave existing chunks intact so queries keep working even while+ # refresh is broken — that's why last_refresh_status is separate.+ fresh.status = SourceStatus.READY if fresh.documents.exists() else SourceStatus.ERROR+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = str(exc)+ if fresh.status == SourceStatus.ERROR:+ fresh.error_message = str(exc)+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "error_message",+ "updated_at",+ ]+ )+ raise++ if result.status == 304:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh.status = SourceStatus.READY+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.NOT_MODIFIED+ fresh.last_refresh_error = ""+ # ETag occasionally rotates without content changes; store whatever+ # the server sent (or keep the previous one if absent).+ if result.etag:+ fresh.last_etag = result.etag+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "last_etag",+ "updated_at",+ ]+ )+ return get_for_team(source.id, team_id) or fresh++ new_hash = sha256_of(text)+ with transaction.atomic():+ fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ existing_doc = (+ KnowledgeDocument.objects.filter(team_id=team_id, source_id=fresh.id).order_by("created_at").first()+ )+ content_changed = existing_doc is None or existing_doc.content_hash != new_hash+ if content_changed:+ _replace_source_content(+ source=fresh,+ team_id=team_id,+ title=title,+ text=text,+ url=result.final_url,+ etag=result.etag or "",+ content_hash=new_hash,+ )+ fresh.status = SourceStatus.READY+ fresh.last_refresh_at = timezone.now()+ # Distinct status from "no content change" — NOT_MODIFIED means+ # "server told us 304". If content hash matches despite a 200, we still+ # classify as SUCCESS (a refresh happened; it just produced no diff).+ fresh.last_refresh_status = RefreshStatus.SUCCESS+ fresh.last_refresh_error = ""+ fresh.last_etag = result.etag or ""+ fresh.error_message = ""+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "last_etag",+ "error_message",+ "updated_at",+ ]+ )++ return get_for_team(source.id, team_id) or fresh+++# --- Stage 2b: crawl sources -------------------------------------------------+++def _insert_document_and_chunks(+ *,+ source: KnowledgeSource,+ team_id: int,+ title: str,+ text: str,+ url: str,+ etag: str,+ content_hash: str,+ existing_doc: KnowledgeDocument | None,+) -> int:+ """+ Upsert a single document (and its chunks) under a crawl source.++ `existing_doc` is the doc for this URL on the source, if any. When+ present, we preserve its `id` so agent citations stay stable across+ refreshes — the chunks get wiped and regenerated.++ Returns the number of chunks written.+ """++ chunks = chunk_text(text)++ if existing_doc is None:+ document = KnowledgeDocument.objects.create(+ team_id=team_id,+ source=source,+ stable_id=url,+ title=title or source.name,+ content=text,+ metadata={"source_type": SourceType.URL, "url": url},+ url=url,+ etag=etag,+ content_hash=content_hash,+ )+ else:+ document = existing_doc+ document.title = title or document.title or source.name+ document.content = text+ document.metadata = {**(document.metadata or {}), "source_type": SourceType.URL, "url": url}+ document.url = url+ document.etag = etag+ document.content_hash = content_hash+ document.tombstoned_at = None+ document.save(+ update_fields=[+ "title",+ "content",+ "metadata",+ "url",+ "etag",+ "content_hash",+ "tombstoned_at",+ "updated_at",+ ]+ )+ # Wipe stale chunks before re-inserting — simpler than diffing+ # chunk-by-chunk and the chunker is deterministic for stable text.+ KnowledgeChunk.objects.filter(team_id=team_id, document_id=document.id).delete()++ _bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)+ return len(chunks)+++@with_team_scope(canonical=True)+def create_crawl_source(+ *,+ team_id: int,+ created_by_id: int | None,+ name: str,+ url: str,+ crawl_mode: str,+ crawl_config: dict | None,+) -> KnowledgeSource:+ """+ Stage 2b multi-URL ingestion.++ Happy path:+ 1. Validate + normalize the entry URL (same SSRF plumbing as Stage 2a).+ 2. Claim a PROCESSING row under advisory lock so concurrent creates+ for the same team are serialized.+ 3. Discover candidate URLs via sitemap / same-origin BFS.+ 4. Fetch all candidates in parallel with a per-host semaphore.+ 5. In a transaction, bulk-insert documents + chunks and mark READY.++ Failures at any stage update the claim row to ERROR so the user can+ see the failure, adjust globs, or retry.+ """++ if crawl_mode == CrawlMode.SINGLE:+ return create_url_source(team_id=team_id, created_by_id=created_by_id, name=name, url=url)++ normalized = _validate_url(url)+ config = _resolve_crawl_config(crawl_config)++ with transaction.atomic():+ _check_source_quota_locked(team_id, reject_if_processing=True)+ source = KnowledgeSource.objects.create(+ team_id=team_id,+ created_by_id=created_by_id,+ name=name,+ source_type=SourceType.URL,+ status=SourceStatus.PROCESSING,+ source_url=normalized,+ crawl_mode=crawl_mode,+ crawl_config=crawl_config or {},+ )++ def _mark_error(error_msg: str) -> KnowledgeSource:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ now = timezone.now()+ fresh.status = SourceStatus.ERROR+ fresh.error_message = error_msg+ fresh.last_refresh_at = now+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = error_msg+ fresh.save(+ update_fields=[+ "status",+ "error_message",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )+ return get_for_team(source.id, team_id) or source++ try:+ candidate_urls = discover.discover(crawl_mode, normalized, config)+ except discover.DiscoverError as exc:+ return _mark_error(str(exc))++ if not candidate_urls:+ return _mark_error("Crawl discovered no URLs. Check the entry URL and globs.")++ safe_urls: list[str] = []+ for u in candidate_urls:+ try:+ safe_urls.append(_validate_url(u))+ except InvalidUrlError:+ logger.info("business_knowledge.crawl.ssrf_skipped", source_url=normalized, skipped=u)+ continue++ if not safe_urls:+ return _mark_error("Crawl discovered no safe URLs to fetch.")++ outcomes = crawl.fetch_many(safe_urls)+ ok_outcomes = [o for o in outcomes if o.status == "ok"]++ if not ok_outcomes:+ first_error = next((o.error for o in outcomes if o.status == "error"), "All pages failed to fetch.")+ return _mark_error(first_error)++ estimated_total = sum(max(1, len(o.text) // CHUNK_TARGET_CHARS) for o in ok_outcomes)+ if _count_chunks(team_id) + estimated_total > MAX_CHUNKS_PER_TEAM:+ return _mark_error(f"Crawl would exceed the {MAX_CHUNKS_PER_TEAM} chunk cap.")++ try:+ with transaction.atomic():+ total_chunks_written = 0+ for outcome in ok_outcomes:+ written = _insert_document_and_chunks(+ source=source,+ team_id=team_id,+ title=outcome.title,+ text=outcome.text,+ url=outcome.url,+ etag=outcome.etag,+ content_hash=outcome.content_hash,+ existing_doc=None,+ )+ total_chunks_written += written++ if _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Crawl exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")++ source.status = SourceStatus.READY+ source.last_refresh_at = timezone.now()+ source.last_refresh_status = RefreshStatus.SUCCESS+ source.last_refresh_error = ""+ source.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )+ except QuotaExceededError:+ _mark_error(f"Crawl exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")+ raise++ return get_for_team(source.id, team_id) or source+++def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSource | None:+ """+ Stage 2b crawl refresh: re-discover + per-URL upsert-diff.++ - New URL → insert document + chunks.+ - Existing URL with changed `content_hash` → rebuild that doc's chunks+ (document row id preserved for citation stability).+ - Existing URL with unchanged hash → no DB writes.+ - Existing URL that vanished from discovery → mark tombstoned_at,+ delete chunks (keep the doc row so a later re-appearance can reuse+ the id). Stage 5 adds a sweep that hard-deletes after 7 days.+ """++ try:+ config = _resolve_crawl_config(source.crawl_config)+ normalized = _validate_url(source.source_url)+ try:+ discovered = discover.discover(source.crawl_mode, normalized, config)+ except discover.DiscoverError as exc:+ raise UrlFetchFailedError(str(exc)) from exc+ except (InvalidUrlError, UrlFetchFailedError) as exc:+ with transaction.atomic():+ fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh.status = SourceStatus.READY if fresh.documents.exists() else SourceStatus.ERROR+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = str(exc)+ if fresh.status == SourceStatus.ERROR:+ fresh.error_message = str(exc)+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "error_message",+ "updated_at",+ ]+ )+ raise++ # Load existing docs keyed by stable_id (== url). Pulling all of them up+ # front is cheap (we're capped at MAX_URLS_PER_SOURCE) and avoids a+ # per-URL query inside the fetch loop.+ existing_by_url: dict[str, KnowledgeDocument] = {+ d.stable_id: d for d in KnowledgeDocument.objects.filter(team_id=team_id, source_id=source.id)+ }++ # Pre-SSRF the discovered list and preserve ETags per URL for conditional GETs.+ safe_urls: list[str] = []+ for u in discovered:+ try:+ safe_urls.append(_validate_url(u))+ except InvalidUrlError:+ continue++ def _etag_for(u: str) -> str | None:+ existing = existing_by_url.get(u)+ return existing.etag if existing and existing.etag else None++ outcomes = crawl.fetch_many(safe_urls, etag_for=_etag_for)+ # `discovered_set` is built by normalizing the raw discovered URLs (lowercased+ # scheme+host, no fragment) so keys match `existing_by_url` (which uses the+ # normalized stable_id). We do NOT use `safe_urls` here — that would tombstone+ # URLs that transiently fail SSRF re-validation even though the sitemap still+ # lists them.+ discovered_set: set[str] = set()+ for u in discovered:+ try:+ discovered_set.add(url_fetch.normalize_url(u))+ except url_fetch.UrlFetchError:+ pass++ with transaction.atomic():+ fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)++ # Upsert per-outcome.+ any_changes = False+ for outcome in outcomes:+ existing = existing_by_url.get(outcome.url)+ if outcome.status == "not_modified":+ # Still touch the etag so a rotation stays fresh.+ if existing and outcome.etag and existing.etag != outcome.etag:+ existing.etag = outcome.etag+ existing.save(update_fields=["etag", "updated_at"])+ continue+ if outcome.status == "error":+ # Keep the old doc intact — partial failures shouldn't+ # knock out a previously-working page.+ logger.info(+ "business_knowledge.crawl.refresh_page_error",+ source_id=str(source.id),+ url=outcome.url,+ error=outcome.error,+ )+ continue+ assert outcome.status == "ok"+ if existing is not None and existing.content_hash == outcome.content_hash:+ # No re-chunk needed. Still bump etag if we got a new one.+ if outcome.etag and existing.etag != outcome.etag:+ existing.etag = outcome.etag+ existing.save(update_fields=["etag", "updated_at"])+ continue+ _insert_document_and_chunks(+ source=fresh,+ team_id=team_id,+ title=outcome.title,+ text=outcome.text,+ url=outcome.url,+ etag=outcome.etag,+ content_hash=outcome.content_hash,+ existing_doc=existing,+ )+ any_changes = True++ # Tombstone docs whose URL vanished from discovery. Chunks go away+ # now; the sweep in Stage 5 hard-deletes the doc row after a grace+ # period (preserves the id in case the page comes back soon).+ vanished = [d for url, d in existing_by_url.items() if url not in discovered_set]+ if vanished:+ now = timezone.now()+ vanished_ids = [d.id for d in vanished]+ KnowledgeChunk.objects.filter(team_id=team_id, document_id__in=vanished_ids).delete()+ KnowledgeDocument.objects.filter(team_id=team_id, id__in=vanished_ids, tombstoned_at__isnull=True).update(+ tombstoned_at=now, updated_at=now+ )+ any_changes = True++ # Exact post-diff quota check.+ if _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Refresh exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")++ fresh.status = SourceStatus.READY+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.SUCCESS if any_changes else RefreshStatus.NOT_MODIFIED+ fresh.last_refresh_error = ""+ fresh.error_message = ""+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "error_message",+ "updated_at",+ ]+ )++ return get_for_team(source.id, team_id) or fresh+++# ---------------------------------------------------------------------------+# AI agent read-path+# ---------------------------------------------------------------------------+++@with_team_scope(canonical=True)+def has_ready_sources(team_id: int) -> bool:+ """True when the team has at least one READY source (READY implies chunks exist)."""+ return KnowledgeSource.objects.filter(team_id=team_id, status=SourceStatus.READY).exists()+++_SEARCH_LIMIT_CAP = 20++_WORD_RE = re.compile(r"\w{2,}", re.UNICODE)+++@dataclass(frozen=True)+class KnowledgeSearchResult:+ """A single chunk returned by a knowledge search, with source context."""++ chunk_id: UUID+ source_id: UUID+ source_name: str+ source_type: str+ document_title: str+ heading_path: str+ ordinal: int+ content: str+++@with_team_scope(canonical=True)+def search_knowledge(+ team_id: int,+ query: str,+ *,+ limit: int = 10,+) -> list[KnowledgeSearchResult]:+ """+ Word-level ILIKE search over chunks belonging to READY sources.++ Splits the query into words (>=2 chars) and matches chunks containing+ ANY of them (OR). Uses the GIN trigram index for performance. Results+ are ordered by char_count ascending (shorter, more focused chunks first).+ """+ limit = max(1, min(limit, _SEARCH_LIMIT_CAP))++ words = _WORD_RE.findall(query)+ if not words:+ return []++ word_filters = reduce(or_, (Q(content__icontains=w) for w in words))++ chunks = (+ KnowledgeChunk.objects.filter(+ word_filters,+ team_id=team_id,+ source__status=SourceStatus.READY,+ document__tombstoned_at__isnull=True,+ )+ .select_related("source", "document")+ .only(+ "id",+ "source_id",+ "document_id",+ "heading_path",+ "ordinal",+ "content",+ "source__name",+ "source__source_type",+ "document__title",+ )+ .order_by("char_count")[:limit]+ )++ return [+ KnowledgeSearchResult(+ chunk_id=c.id,+ source_id=c.source_id,+ source_name=c.source.name,+ source_type=c.source.source_type,+ document_title=c.document.title,+ heading_path=c.heading_path,+ ordinal=c.ordinal,+ content=c.content,+ )+ for c in chunks+ ]diff --git a/products/business_knowledge/backend/logic/__init__.py b/products/business_knowledge/backend/logic/__init__.pydeleted file mode 100644index 68b61faa6b63..000000000000--- a/products/business_knowledge/backend/logic/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""-Business logic for business_knowledge.--Validation, calculations, business rules, ORM queries.-Called by facade/api.py.--Split into submodules (e.g. logic/queries.py, logic/rules.py)-as this grows.-"""diff --git a/products/business_knowledge/backend/migrations/0002_knowledgedocument_stable_id_max_length.py b/products/business_knowledge/backend/migrations/0002_knowledgedocument_stable_id_max_length.pynew file mode 100644index 000000000000..5603c1d2734b--- /dev/null+++ b/products/business_knowledge/backend/migrations/0002_knowledgedocument_stable_id_max_length.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("business_knowledge", "0001_initial"),+ ]++ operations = [+ migrations.AlterField(+ model_name="knowledgedocument",+ name="stable_id",+ field=models.CharField(max_length=2048),+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtindex cbab66dde92a..c0c55f0f7747 100644--- a/products/business_knowledge/backend/migrations/max_migration.txt+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_initial+0002_knowledgedocument_stable_id_max_lengthdiff --git a/products/business_knowledge/backend/models/knowledge_chunk.py b/products/business_knowledge/backend/models/knowledge_chunk.pyindex 2284b5c62e4c..39d71b732cec 100644--- a/products/business_knowledge/backend/models/knowledge_chunk.py+++ b/products/business_knowledge/backend/models/knowledge_chunk.py@@ -54,6 +54,9 @@ class KnowledgeChunk(models.Model):),]+ def __str__(self) -> str:+ return f"Chunk {self.ordinal} of {self.document_id}"+def save(self, *args: Any, **kwargs: Any) -> None:if self.pk is None:raise ValueError(diff --git a/products/business_knowledge/backend/models/knowledge_document.py b/products/business_knowledge/backend/models/knowledge_document.pyindex 25dfecb05038..a4a63b86676c 100644--- a/products/business_knowledge/backend/models/knowledge_document.py+++ b/products/business_knowledge/backend/models/knowledge_document.py@@ -19,7 +19,7 @@ class KnowledgeDocument(UUIDModel):# Stable identity across refreshes. For Stage 1 text it's the document's# own UUID. For Stage 2+ URLs it will be set to the normalized URL so a# re-crawl replaces rather than duplicates.- stable_id = models.CharField(max_length=512)+ stable_id = models.CharField(max_length=2048)title = models.CharField(max_length=512, blank=True, default="")# The raw parsed text. Kept so we can re-chunk without re-parsing the# source. Bounded by MAX_TEXT_SIZE_BYTES at the API layer.@@ -55,3 +55,6 @@ class KnowledgeDocument(UUIDModel):constraints = [models.UniqueConstraint(fields=["source", "stable_id"], name="bk_doc_unique_per_source"),]++ def __str__(self) -> str:+ return self.title or self.stable_iddiff --git a/products/business_knowledge/backend/models/knowledge_source.py b/products/business_knowledge/backend/models/knowledge_source.pyindex 06fde12d8237..501f65f4e5de 100644--- a/products/business_knowledge/backend/models/knowledge_source.py+++ b/products/business_knowledge/backend/models/knowledge_source.py@@ -68,3 +68,6 @@ class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields,models.Index(fields=["team", "status"], name="bk_source_team_status"),models.Index(fields=["team", "source_type"], name="bk_source_team_type"),]++ def __str__(self) -> str:+ return f"{self.name} ({self.source_type})"diff --git a/products/business_knowledge/backend/presentation/__init__.py b/products/business_knowledge/backend/presentation/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/business_knowledge/backend/presentation/serializers.py b/products/business_knowledge/backend/presentation/serializers.pydeleted file mode 100644index d41e7c2d5044..000000000000--- a/products/business_knowledge/backend/presentation/serializers.py+++ /dev/null@@ -1,8 +0,0 @@-"""-DRF serializers for business_knowledge.--Converts frozen dataclasses to/from JSON. Can be auto-generated from-dataclasses using DataclassSerializer.-"""--# from ..facade.contracts import ...diff --git a/products/business_knowledge/backend/presentation/views.py b/products/business_knowledge/backend/presentation/views.pydeleted file mode 100644index 166422ce5b68..000000000000--- a/products/business_knowledge/backend/presentation/views.py+++ /dev/null@@ -1,14 +0,0 @@-"""-DRF views for business_knowledge.--Responsibilities:-- Validate incoming JSON (via serializers)-- Convert JSON to frozen dataclasses-- Call facade methods (facade/api.py)-- Convert frozen dataclasses to JSON responses--No business logic here - that belongs in logic.py via the facade.-"""---# from ..facade import apidiff --git a/products/business_knowledge/backend/signals.py b/products/business_knowledge/backend/signals.pynew file mode 100644index 000000000000..553263c3fa81--- /dev/null+++ b/products/business_knowledge/backend/signals.py@@ -0,0 +1,71 @@+"""Activity-log hook for KnowledgeSource create/update/delete."""++import dataclasses+from typing import Any++import structlog++from posthog.models.activity_logging.activity_log import (+ ActivityContextBase,+ ActivityScope,+ Detail,+ changes_between,+ log_activity,+)+from posthog.models.signals import model_activity_signal, mutable_receiver+from posthog.models.user import User++from .models import KnowledgeSource++logger = structlog.get_logger(__name__)++[email protected](frozen=True)+class KnowledgeSourceContext(ActivityContextBase):+ team_id: int+ source_type: str+ name: str+++@mutable_receiver(model_activity_signal, sender=KnowledgeSource)+def handle_knowledge_source_change(+ sender: type[KnowledgeSource],+ scope: ActivityScope,+ before_update: KnowledgeSource | None,+ after_update: KnowledgeSource | None,+ activity: str,+ user: User | None,+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance: KnowledgeSource | None = after_update or before_update+ if instance is None:+ return++ context = KnowledgeSourceContext(+ team_id=instance.team_id,+ source_type=instance.source_type,+ name=instance.name,+ )++ if activity == "created":+ detail_name = f"Knowledge source '{instance.name}' added"+ elif activity == "deleted":+ detail_name = f"Knowledge source '{instance.name}' deleted"+ else:+ detail_name = f"Knowledge source '{instance.name}' updated"++ log_activity(+ organization_id=None,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )diff --git a/products/business_knowledge/backend/tasks/tasks.py b/products/business_knowledge/backend/tasks/tasks.pyindex ad0091474294..371ffe5e8f27 100644--- a/products/business_knowledge/backend/tasks/tasks.py+++ b/products/business_knowledge/backend/tasks/tasks.py@@ -1,8 +1,7 @@"""Celery tasks for business_knowledge.-Async entrypoints that call the facade (facade/api.py).-Keep task functions thin - only call facade methods.+Async entrypoints that call the logic layer."""# from celery import shared_task-# from ..facade import api+# from .. import logicdiff --git a/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yaml b/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yamlnew file mode 100644index 000000000000..ff6baab4bdf3--- /dev/null+++ b/products/business_knowledge/backend/tests/fixtures/retrieval_eval.yaml@@ -0,0 +1,39 @@+# Each entry defines a source, its content, and queries with expected matches.+# The test creates the source, runs search_knowledge for each query, and+# asserts the expected source name appears in the results.+- source_name: "Refund Policy"+ text: |+ Our refund policy allows customers to request a full refund within 30 days+ of purchase. After 30 days, only store credit is available. Refunds are+ processed within 5 business days.++ For subscription products, cancellation stops future billing but does not+ retroactively refund the current billing period.+ queries:+ - query: "refund policy"+ expect_found: true+ - query: "store credit"+ expect_found: true+ - query: "30 days"+ expect_found: true+ - query: "quantum physics research"+ expect_found: false++- source_name: "Onboarding Guide"+ text: |+ New customers should complete the following onboarding steps:+ 1. Create their workspace+ 2. Invite team members+ 3. Install the tracking snippet+ 4. Configure their first dashboard++ The onboarding wizard guides users through each step automatically.+ queries:+ - query: "onboarding steps"+ expect_found: true+ - query: "invite team members"+ expect_found: true+ - query: "tracking snippet"+ expect_found: true+ - query: "cryptocurrency blockchain"+ expect_found: false\ No newline at end of filediff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.pyindex e69de29bb2d1..03bc94fcc5ae 100644--- a/products/business_knowledge/backend/tests/test_api.py+++ b/products/business_knowledge/backend/tests/test_api.py@@ -0,0 +1,110 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import status++from posthog.models.activity_logging.activity_log import ActivityLog++from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource+++@patch("posthoganalytics.feature_enabled", return_value=True)+class TestKnowledgeSourceAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/business_knowledge/sources/"++ def test_create_text_source_and_chunks(self, _ff) -> None:+ response = self.client.post(+ self.url,+ {"name": "Docs", "text": "Intro paragraph.\n\nSecond paragraph covers pricing."},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content+ body = response.json()+ assert body["name"] == "Docs"+ assert body["source_type"] == "text"+ assert body["status"] == "ready"+ assert body["document_count"] == 1+ assert body["chunk_count"] >= 1+ # Denormalized team_id landed on child rows.+ source = KnowledgeSource.objects.unscoped().get(id=body["id"])+ assert KnowledgeDocument.objects.unscoped().filter(source=source, team=self.team).count() == 1+ assert KnowledgeChunk.objects.unscoped().filter(source=source, team=self.team).count() >= 1++ def test_list_only_returns_own_team(self, _ff) -> None:+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ # Create in THIS team via API.+ self.client.post(self.url, {"name": "Mine", "text": "hello"}, format="json")+ # Create directly in the other team — unscoped to bypass TeamScopedManager.+ KnowledgeSource.objects.unscoped().create(team=other_team, name="Theirs", source_type="text", status="ready")++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ names = [row["name"] for row in response.json()["results"]]+ assert names == ["Mine"]++ def test_cannot_read_other_team_source_via_id(self, _ff) -> None:+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ theirs = KnowledgeSource.objects.unscoped().create(+ team=other_team, name="Theirs", source_type="text", status="ready"+ )+ response = self.client.get(f"{self.url}{theirs.id}/")+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_cannot_delete_other_team_source(self, _ff) -> None:+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ theirs = KnowledgeSource.objects.unscoped().create(+ team=other_team, name="Theirs", source_type="text", status="ready"+ )+ response = self.client.delete(f"{self.url}{theirs.id}/")+ assert response.status_code == status.HTTP_404_NOT_FOUND+ # Untouched.+ assert KnowledgeSource.objects.unscoped().filter(id=theirs.id).exists()++ def test_delete_cascades_and_fires_activity_log(self, _ff) -> None:+ create = self.client.post(self.url, {"name": "Docs", "text": "body"}, format="json").json()+ source_id = create["id"]+ assert KnowledgeDocument.objects.unscoped().filter(source_id=source_id).exists()+ assert KnowledgeChunk.objects.unscoped().filter(source_id=source_id).exists()++ response = self.client.delete(f"{self.url}{source_id}/")+ assert response.status_code == status.HTTP_204_NO_CONTENT+ assert not KnowledgeSource.objects.unscoped().filter(id=source_id).exists()+ assert not KnowledgeDocument.objects.unscoped().filter(source_id=source_id).exists()+ assert not KnowledgeChunk.objects.unscoped().filter(source_id=source_id).exists()+ # Activity logging hook ran.+ assert ActivityLog.objects.filter(scope="KnowledgeSource", item_id=source_id, activity="deleted").exists()++ def test_rejects_empty_text(self, _ff) -> None:+ response = self.client.post(self.url, {"name": "Docs", "text": " "}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ body = response.json()+ # drf-exceptions-hog normalizes single-field errors into a flat+ # {type, code, detail, attr} shape; we assert the offending field+ # lands in `attr` so UX code can still target it.+ assert body.get("attr") == "text"++ def test_rejects_oversized_text(self, _ff) -> None:+ response = self.client.post(self.url, {"name": "Docs", "text": "x" * 1_000_001}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json().get("attr") == "text"++ def test_create_defaults_source_type_to_text(self, _ff) -> None:+ # Stage 2a dispatches on `source_type`. Omitting it must still land+ # on the text path so Stage 1 clients keep working unchanged.+ response = self.client.post(self.url, {"name": "Docs", "text": "hello"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["source_type"] == "text"diff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.pynew file mode 100644index 000000000000..ca6ddebef3b5--- /dev/null+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py@@ -0,0 +1,494 @@+"""+Tests for Stage 2b crawl ingestion.++Scope:+- Discover (sitemap parsing + index unfurl, same-origin BFS).+- Glob include/exclude.+- `max_pages` enforcement.+- Happy-path create_crawl_source.+- Refresh upsert-diff: new URL inserted, changed URL rebuilt (doc id+ preserved), unchanged URL untouched, vanished URL tombstoned.+- SSRF on a URL that appears in a sitemap but points at a blocked host.++Design notes:+- We patch `discover._http_get_text` for discover tests — exercising real+ XML parsing without needing HTTP. For fetch tests we patch+ `url_fetch.fetch_url` so the crawl module's parallel ThreadPoolExecutor+ is exercised end-to-end but with deterministic content.+- `requests.Session.get` is intentionally NOT patched globally — each+ test patches the narrowest layer it needs.+"""++from collections.abc import Mapping++from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import patch++from products.business_knowledge.backend import crawl, discover, url_fetch+from products.business_knowledge.backend.logic import create_crawl_source, refresh_source+from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SourceStatus+++def _sitemap_xml(urls: list[str]) -> str:+ entries = "\n".join(f"<url><loc>{u}</loc></url>" for u in urls)+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'+ f"{entries}"+ "</urlset>"+ )+++def _sitemap_index_xml(children: list[str]) -> str:+ entries = "\n".join(f"<sitemap><loc>{c}</loc></sitemap>" for c in children)+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'+ f"{entries}"+ "</sitemapindex>"+ )+++class TestDiscoverSitemap(BaseTest):+ def test_parses_flat_sitemap(self) -> None:+ sitemap = _sitemap_xml(+ [+ "https://example.com/a",+ "https://example.com/b",+ "https://example.com/c",+ ]+ )+ with patch.object(discover, "_http_get_text", return_value=sitemap):+ urls = discover.discover(+ "sitemap",+ "https://example.com/sitemap.xml",+ discover.CrawlConfig(max_pages=10),+ )+ assert urls == ["https://example.com/a", "https://example.com/b", "https://example.com/c"]++ def test_unfurls_sitemap_index(self) -> None:+ index = _sitemap_index_xml(["https://example.com/a.xml", "https://example.com/b.xml"])+ child_a = _sitemap_xml(["https://example.com/1"])+ child_b = _sitemap_xml(["https://example.com/2", "https://example.com/3"])++ def _fake_fetch(url: str, max_bytes: int = 0) -> str:+ if url == "https://example.com/sitemap.xml":+ return index+ if url == "https://example.com/a.xml":+ return child_a+ if url == "https://example.com/b.xml":+ return child_b+ raise AssertionError(f"unexpected discover fetch: {url}")++ with patch.object(discover, "_http_get_text", side_effect=_fake_fetch):+ urls = discover.discover(+ "sitemap",+ "https://example.com/sitemap.xml",+ discover.CrawlConfig(max_pages=10),+ )+ assert urls == [+ "https://example.com/1",+ "https://example.com/2",+ "https://example.com/3",+ ]++ def test_applies_glob_filters(self) -> None:+ sitemap = _sitemap_xml(+ [+ "https://example.com/docs/one",+ "https://example.com/docs/two",+ "https://example.com/blog/post",+ "https://example.com/docs/private/secret",+ ]+ )+ with patch.object(discover, "_http_get_text", return_value=sitemap):+ urls = discover.discover(+ "sitemap",+ "https://example.com/sitemap.xml",+ discover.CrawlConfig(+ include_globs=("/docs/*",),+ exclude_globs=("/docs/private/*",),+ max_pages=10,+ ),+ )+ assert urls == ["https://example.com/docs/one", "https://example.com/docs/two"]++ def test_max_pages_caps_output(self) -> None:+ sitemap = _sitemap_xml([f"https://example.com/p{i}" for i in range(100)])+ with patch.object(discover, "_http_get_text", return_value=sitemap):+ urls = discover.discover(+ "sitemap",+ "https://example.com/sitemap.xml",+ discover.CrawlConfig(max_pages=5),+ )+ assert len(urls) == 5++ def test_rejects_malformed_xml(self) -> None:+ with patch.object(discover, "_http_get_text", return_value="<not-xml>"):+ try:+ discover.discover(+ "sitemap",+ "https://example.com/sitemap.xml",+ discover.CrawlConfig(),+ )+ except discover.DiscoverError as exc:+ assert "XML" in str(exc) or "valid" in str(exc)+ else:+ raise AssertionError("expected DiscoverError")+++class TestDiscoverSameOrigin(BaseTest):+ def test_stays_on_origin_and_respects_depth(self) -> None:+ pages = {+ "https://ex.com/a": '<a href="/b">b</a><a href="https://other.com/x">external</a>',+ "https://ex.com/b": '<a href="/c">c</a>',+ "https://ex.com/c": "",+ }++ def _fake(url: str, max_bytes: int = 0) -> str:+ if url == "https://ex.com/robots.txt":+ raise discover.DiscoverError("not found")+ return pages.get(url, "")++ with patch.object(discover, "_http_get_text", side_effect=_fake):+ urls = discover.discover(+ "same_origin",+ "https://ex.com/a",+ discover.CrawlConfig(max_depth=1, max_pages=10),+ )+ assert urls == ["https://ex.com/a", "https://ex.com/b"]+++class _FakeFetch:+ """+ Stand-in for `url_fetch.fetch_url`, driven by a dict of url -> behaviour.+ Each value is either a FetchResult or an exception instance.+ """++ def __init__(self, behaviours: Mapping[str, url_fetch.FetchResult | Exception]) -> None:+ self.behaviours = behaviours+ self.etags_seen: dict[str, str | None] = {}++ def __call__(self, url: str, *, etag: str | None = None) -> url_fetch.FetchResult:+ self.etags_seen[url] = etag+ b = self.behaviours.get(url)+ if isinstance(b, Exception):+ raise b+ if isinstance(b, url_fetch.FetchResult):+ return b+ raise AssertionError(f"no behaviour for {url}")+++def _ok(url: str, body: bytes) -> url_fetch.FetchResult:+ return url_fetch.FetchResult(+ status=200, body=body, content_type="text/html", etag=f'W/"{hash(body)}"', final_url=url+ )+++class TestCreateCrawlSource(APIBaseTest):+ def test_happy_path_indexes_all_discovered_pages(self) -> None:+ sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/b", "https://example.com/c"])+ behaviours: dict[str, url_fetch.FetchResult | Exception] = {+ "https://example.com/a": _ok("https://example.com/a", b"<html><body>Alpha paragraph.</body></html>"),+ "https://example.com/b": _ok("https://example.com/b", b"<html><body>Beta paragraph.</body></html>"),+ "https://example.com/c": _ok("https://example.com/c", b"<html><body>Gamma paragraph.</body></html>"),+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ source = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Handbook",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ assert source.status == SourceStatus.READY+ assert KnowledgeDocument.objects.unscoped().filter(source=source).count() == 3+ # Every doc has chunks and a content_hash.+ docs = KnowledgeDocument.objects.unscoped().filter(source=source)+ assert all(d.content_hash for d in docs)+ assert KnowledgeChunk.objects.unscoped().filter(source=source).count() >= 3++ def test_zero_safe_urls_returns_error_source(self) -> None:+ sitemap = _sitemap_xml(["http://127.0.0.1/secret"])+ with patch.object(discover, "_http_get_text", return_value=sitemap):+ source = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Hack",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ assert source.status == SourceStatus.ERROR+ assert "no safe URLs" in source.error_message++ def test_concurrent_crawl_create_blocked_by_processing_claim(self) -> None:+ from products.business_knowledge.backend.logic import SourceBusyError+ from products.business_knowledge.backend.models import SourceType++ KnowledgeSource.objects.unscoped().create(+ team_id=self.team.id,+ name="In-flight",+ source_type=SourceType.URL,+ status=SourceStatus.PROCESSING,+ source_url="https://other.example.com/",+ )+ with self.assertRaises(SourceBusyError):+ create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Second",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )++ def test_stale_processing_row_auto_recovered(self) -> None:+ import datetime++ from django.utils import timezone++ from products.business_knowledge.backend.models import SourceType++ stale = KnowledgeSource.objects.unscoped().create(+ team_id=self.team.id,+ name="Stale",+ source_type=SourceType.URL,+ status=SourceStatus.PROCESSING,+ source_url="https://stale.example.com/",+ )+ KnowledgeSource.objects.unscoped().filter(id=stale.id).update(+ updated_at=timezone.now() - datetime.timedelta(minutes=15),+ )+ sitemap = _sitemap_xml(["https://example.com/a"])+ behaviours = {+ "https://example.com/a": _ok("https://example.com/a", b"<html><body>Alpha.</body></html>"),+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ source = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Fresh",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ assert source.status == SourceStatus.READY+ stale.refresh_from_db()+ assert stale.status == SourceStatus.ERROR+++class TestRefreshCrawlSource(APIBaseTest):+ def _seed(self, sitemap_urls: list[str]) -> KnowledgeSource:+ sitemap = _sitemap_xml(sitemap_urls)+ behaviours: dict[str, url_fetch.FetchResult | Exception] = {+ url: _ok(url, f"<html><body>body of {url}</body></html>".encode()) for url in sitemap_urls+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ return create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Handbook",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )++ def test_changed_page_rebuilds_only_that_doc(self) -> None:+ source = self._seed(["https://example.com/a", "https://example.com/b"])+ doc_a = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")+ doc_b = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/b")+ b_hash_before = doc_b.content_hash++ # Re-discover same sitemap; change content of /a only.+ sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/b"])+ behaviours = {+ "https://example.com/a": _ok(+ "https://example.com/a", b"<html><body>Alpha content has been updated.</body></html>"+ ),+ "https://example.com/b": _ok(+ "https://example.com/b", b"<html><body>body of https://example.com/b</body></html>"+ ),+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ refresh_source(source_id=source.id, team_id=self.team.id)++ doc_a.refresh_from_db()+ doc_b.refresh_from_db()+ # doc id preserved for both — critical for citation stability.+ assert KnowledgeDocument.objects.unscoped().filter(source=source, id=doc_a.id).exists()+ assert KnowledgeDocument.objects.unscoped().filter(source=source, id=doc_b.id).exists()+ # /a rebuilt; /b unchanged.+ assert "updated" in doc_a.content+ assert doc_b.content_hash == b_hash_before++ def test_vanished_url_is_tombstoned(self) -> None:+ source = self._seed(["https://example.com/a", "https://example.com/b"])+ doc_b = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/b")+ assert KnowledgeChunk.objects.unscoped().filter(document_id=doc_b.id).exists()++ # Re-discover without /b.+ sitemap = _sitemap_xml(["https://example.com/a"])+ behaviours = {+ "https://example.com/a": _ok(+ "https://example.com/a", b"<html><body>body of https://example.com/a</body></html>"+ ),+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ refresh_source(source_id=source.id, team_id=self.team.id)++ doc_b.refresh_from_db()+ assert doc_b.tombstoned_at is not None+ # Chunks for the vanished doc are gone, but the doc row is preserved.+ assert KnowledgeChunk.objects.unscoped().filter(document_id=doc_b.id).count() == 0+ assert KnowledgeDocument.objects.unscoped().filter(id=doc_b.id).exists()++ def test_unchanged_source_reports_not_modified(self) -> None:+ source = self._seed(["https://example.com/a"])+ doc_a = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")++ sitemap = _sitemap_xml(["https://example.com/a"])++ # Return 304 so the doc isn't re-parsed.+ def _fetch_304(url: str, *, etag: str | None = None) -> url_fetch.FetchResult:+ assert etag == doc_a.etag+ return url_fetch.FetchResult(status=304, body=None, content_type=None, etag=etag, final_url=url)++ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_fetch_304),+ ):+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)++ assert refreshed is not None+ assert refreshed.last_refresh_status == "not_modified"+ # Hash + chunk count untouched.+ doc_a.refresh_from_db()+ assert doc_a.content_hash != ""++ def test_ssrf_block_during_refresh_does_not_tombstone(self) -> None:+ """+ Regression: `discovered_set` was previously built from `outcomes`,+ meaning any URL that transiently failed SSRF re-validation between+ discover and fetch would be tombstoned. That wipes chunks the user+ thought were healthy. `discovered_set` must be built from the raw+ discover() output so only URLs genuinely gone from the sitemap get+ tombstoned.+ """++ source = self._seed(["https://example.com/a", "https://example.com/b"])+ doc_b = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/b")+ b_chunks_before = KnowledgeChunk.objects.unscoped().filter(document_id=doc_b.id).count()+ assert b_chunks_before > 0++ # Sitemap still lists both URLs. But `is_url_allowed` flips to False+ # for /b on this refresh (simulate a DNS rebinding / outage flap).+ sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/b"])+ behaviours = {+ "https://example.com/a": _ok(+ "https://example.com/a", b"<html><body>body of https://example.com/a</body></html>"+ ),+ }++ real_is_url_allowed = __import__("posthog.security.url_validation", fromlist=["is_url_allowed"]).is_url_allowed++ def _flaky_is_url_allowed(u: str) -> tuple[bool, str]:+ if u.rstrip("/") == "https://example.com/b":+ return (False, "transient_block")+ return real_is_url_allowed(u)++ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ # Patch `is_url_allowed` at BOTH import sites — logic._validate_url+ # and url_fetch.fetch_url read it independently.+ patch("products.business_knowledge.backend.logic.is_url_allowed", side_effect=_flaky_is_url_allowed),+ ):+ refresh_source(source_id=source.id, team_id=self.team.id)++ doc_b.refresh_from_db()+ # /b is still in discovery so it must NOT be tombstoned, even though+ # it was filtered out before fetch.+ assert doc_b.tombstoned_at is None+ # Chunks are left intact — the whole point of preserving /b is that+ # the user still has citations for the previously-indexed content.+ assert KnowledgeChunk.objects.unscoped().filter(document_id=doc_b.id).count() == b_chunks_before+++class TestChunkIdIsolation(APIBaseTest):+ """+ Regression: two URL sources crawling an overlapping URL used to collide+ on chunk UUIDs (uuid5 of stable_id only, where stable_id == url for URL+ sources). `_chunk_id` now includes `source_id` to isolate namespaces.+ """++ def test_two_sources_same_url_do_not_collide(self) -> None:+ sitemap_a = _sitemap_xml(["https://example.com/shared"])+ sitemap_b = _sitemap_xml(["https://example.com/shared"])+ # Same URL, same body → same chunker output. Pre-fix: PRIMARY KEY+ # collision on the second source's bulk_create.+ body = b"<html><body>Shared paragraph content.</body></html>"+ behaviours_a = {"https://example.com/shared": _ok("https://example.com/shared", body)}+ behaviours_b = {"https://example.com/shared": _ok("https://example.com/shared", body)}++ with (+ patch.object(discover, "_http_get_text", return_value=sitemap_a),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours_a)),+ ):+ source_a = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Source A",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap_b),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours_b)),+ ):+ source_b = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Source B",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )++ a_chunks = set(KnowledgeChunk.objects.unscoped().filter(source=source_a).values_list("id", flat=True))+ b_chunks = set(KnowledgeChunk.objects.unscoped().filter(source=source_b).values_list("id", flat=True))+ assert a_chunks and b_chunks+ assert a_chunks.isdisjoint(b_chunks), "chunk UUIDs must not collide across sources"+++class TestDiscoverSSRF(BaseTest):+ """+ Regression: `discover._http_get_text` used to auto-follow redirects+ (`allow_redirects=True`), so a sitemap or link page could 302 to+ `127.0.0.1` and bypass SSRF. Now each hop is SSRF-re-validated.+ """++ def test_redirect_to_blocked_host_is_refused(self) -> None:+ with patch(+ "products.business_knowledge.backend.discover.fetch_text",+ side_effect=url_fetch.UrlFetchError("127.0.0.1 is not reachable (SSRF blocked)"),+ ):+ with self.assertRaises(discover.DiscoverError):+ discover._http_get_text("https://example.com/sitemap.xml")diff --git a/products/business_knowledge/backend/tests/test_cross_team_isolation.py b/products/business_knowledge/backend/tests/test_cross_team_isolation.pynew file mode 100644index 000000000000..47ab4a1d9006--- /dev/null+++ b/products/business_knowledge/backend/tests/test_cross_team_isolation.py@@ -0,0 +1,53 @@+from posthog.test.base import BaseTest++from posthog.models.organization import Organization+from posthog.models.project import Project+from posthog.models.team import Team++from products.business_knowledge.backend import logic+from products.business_knowledge.backend.logic import create_text_source+from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource+++class TestCrossTeamIsolation(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ other_org = Organization.objects.create(name="other_org")+ other_project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=other_org)+ self.other_team = Team.objects.create(id=other_project.id, project=other_project, organization=other_org)++ create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Team A Docs",+ text="Our secret pricing model is tiered with enterprise discounts.",+ )+ create_text_source(+ team_id=self.other_team.id,+ created_by_id=None,+ name="Team B Docs",+ text="Team B has a completely different pricing approach.",+ )++ def test_search_only_returns_own_team_chunks(self) -> None:+ results_a = logic.search_knowledge(self.team.id, "pricing")+ results_b = logic.search_knowledge(self.other_team.id, "pricing")++ source_names_a = {r.source_name for r in results_a}+ source_names_b = {r.source_name for r in results_b}++ assert "Team A Docs" in source_names_a+ assert "Team B Docs" not in source_names_a+ assert "Team B Docs" in source_names_b+ assert "Team A Docs" not in source_names_b++ def test_has_ready_sources_scoped_to_team(self) -> None:+ assert logic.has_ready_sources(self.team.id) is True+ assert logic.has_ready_sources(self.other_team.id) is True++ KnowledgeChunk.objects.unscoped().filter(team=self.other_team).delete()+ KnowledgeDocument.objects.unscoped().filter(team=self.other_team).delete()+ KnowledgeSource.objects.unscoped().filter(team=self.other_team).delete()++ assert logic.has_ready_sources(self.team.id) is True+ assert logic.has_ready_sources(self.other_team.id) is Falsediff --git a/products/business_knowledge/backend/tests/test_file_ingest.py b/products/business_knowledge/backend/tests/test_file_ingest.pynew file mode 100644index 000000000000..d10c8d17d368--- /dev/null+++ b/products/business_knowledge/backend/tests/test_file_ingest.py@@ -0,0 +1,363 @@+import io+import zipfile++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework import status as http_status++from products.business_knowledge.backend.constants import MAX_FILE_SIZE_BYTES+from products.business_knowledge.backend.file_parse import (+ EncryptedPDFError,+ FileParseError,+ FileTooLargeError,+ UnsupportedFileTypeError,+ ZipBombError,+ detect_content_type,+ parse_file,+ sanitize_filename,+)+from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_minimal_pdf(text: str = "Hello from page 1", encrypted: bool = False) -> bytes:+ from pypdf import PdfWriter++ writer = PdfWriter()+ writer.add_blank_page(width=612, height=792)+ # pypdf doesn't expose a nice text-write API for new pages, so we write a+ # second page with annotation-style text via the low-level API. For tests+ # it's simpler to create a real PDF via reportlab, but we avoid that dep.+ # Instead just test with the blank page — extract_text returns "".+ # We'll test content extraction separately.++ buf = io.BytesIO()+ if encrypted:+ writer.encrypt("secret")+ writer.write(buf)+ return buf.getvalue()+++def _make_minimal_docx(text: str = "Hello World") -> bytes:+ from docx import Document++ doc = Document()+ doc.add_heading("Test Heading", level=1)+ doc.add_paragraph(text)+ buf = io.BytesIO()+ doc.save(buf)+ return buf.getvalue()+++# ---------------------------------------------------------------------------+# detect_content_type+# ---------------------------------------------------------------------------+++class TestDetectContentType:+ def test_pdf_from_magic_bytes(self) -> None:+ assert detect_content_type(b"%PDF-1.4 ...", "mystery.bin") == "application/pdf"++ def test_docx_from_zip_structure(self) -> None:+ data = _make_minimal_docx()+ assert detect_content_type(data, "doc.docx") == (+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ )++ @parameterized.expand(+ [+ ("readme.md", "text/markdown"),+ ("README.MARKDOWN", "text/markdown"),+ ("data.csv", "text/csv"),+ ("notes.txt", "text/plain"),+ ]+ )+ def test_text_formats_from_extension(self, filename: str, expected: str) -> None:+ assert detect_content_type(b"some text content", filename) == expected++ def test_unknown_utf8_falls_back_to_plain_text(self) -> None:+ assert detect_content_type(b"just utf8", "noext") == "text/plain"++ def test_binary_garbage_rejected(self) -> None:+ with pytest.raises(UnsupportedFileTypeError):+ detect_content_type(b"\x89PNG\r\n\x1a\n", "image.png")++ def test_mimetype_spoof_pdf_extension_but_text_content(self) -> None:+ # A .pdf extension with text content should be detected as text/plain+ # from magic bytes (no %PDF- prefix), falling through to extension+ # check. Since .pdf isn't in the text extension list, it falls to+ # UTF-8 check and becomes text/plain.+ result = detect_content_type(b"This is not a PDF", "fake.pdf")+ assert result == "text/plain"++ def test_mimetype_spoof_txt_extension_but_pdf_content(self) -> None:+ pdf_data = _make_minimal_pdf()+ result = detect_content_type(pdf_data, "sneaky.txt")+ assert result == "application/pdf"+++# ---------------------------------------------------------------------------+# sanitize_filename+# ---------------------------------------------------------------------------+++class TestSanitizeFilename:+ def test_strips_path_components(self) -> None:+ assert sanitize_filename("/etc/passwd") == "passwd"+ assert sanitize_filename("..\\..\\secret.txt") == "secret.txt"++ def test_removes_null_bytes(self) -> None:+ assert sanitize_filename("file\x00name.txt") == "filename.txt"++ def test_caps_length(self) -> None:+ long_name = "a" * 300 + ".pdf"+ assert len(sanitize_filename(long_name)) <= 255++ def test_empty_becomes_unnamed(self) -> None:+ assert sanitize_filename("") == "unnamed"+++# ---------------------------------------------------------------------------+# parse_file — happy paths+# ---------------------------------------------------------------------------+++class TestParseFileHappyPaths:+ def test_parse_txt(self) -> None:+ result = parse_file(b"Hello, world!\n\nSecond paragraph.", "notes.txt")+ assert result.content_type == "text/plain"+ assert "Hello, world!" in result.content+ assert result.title == "notes"+ assert result.metadata["file_type"] == "txt"++ def test_parse_markdown(self) -> None:+ md = b"# Heading\n\nSome text\n\n## Sub\n\nMore text"+ result = parse_file(md, "readme.md")+ assert result.content_type == "text/markdown"+ assert "# Heading" in result.content+ assert result.metadata["file_type"] == "markdown"++ def test_parse_csv(self) -> None:+ csv_data = b"name,age\nAlice,30\nBob,25"+ result = parse_file(csv_data, "people.csv")+ assert result.content_type == "text/csv"+ assert "name: Alice" in result.content+ assert "age: 30" in result.content+ assert result.metadata["row_count"] == 2++ def test_parse_docx(self) -> None:+ data = _make_minimal_docx("Test paragraph")+ result = parse_file(data, "doc.docx")+ assert result.content_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ assert "Test paragraph" in result.content+ assert "# Test Heading" in result.content+ assert result.metadata["file_type"] == "docx"+++# ---------------------------------------------------------------------------+# parse_file — security rejections+# ---------------------------------------------------------------------------+++class TestParseFileSecurity:+ def test_oversized_file_rejected(self) -> None:+ data = b"x" * (MAX_FILE_SIZE_BYTES + 1)+ with pytest.raises(FileTooLargeError):+ parse_file(data, "huge.txt")++ def test_encrypted_pdf_rejected(self) -> None:+ data = _make_minimal_pdf(encrypted=True)+ with pytest.raises(EncryptedPDFError, match="Encrypted"):+ parse_file(data, "secret.pdf")++ def test_zip_bomb_docx_rejected(self) -> None:+ content_types_xml = (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'+ '<Override PartName="/word/document.xml"'+ ' ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'+ "</Types>"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as zf:+ zf.writestr("[Content_Types].xml", content_types_xml)+ zf.writestr("word/document.xml", "A" * 200)+ data = buf.getvalue()+ with patch("products.business_knowledge.backend.file_parse.MAX_FILE_DECOMPRESSED_BYTES", 50):+ with pytest.raises(ZipBombError):+ parse_file(data, "bomb.docx")++ def test_unsupported_binary_rejected(self) -> None:+ with pytest.raises(UnsupportedFileTypeError):+ parse_file(b"\x89PNG\r\n\x1a\n" + b"\x00" * 100, "image.png")++ def test_empty_txt_rejected(self) -> None:+ with pytest.raises(FileParseError, match="empty"):+ parse_file(b" \n ", "empty.txt")++ def test_empty_csv_rejected(self) -> None:+ with pytest.raises(FileParseError, match="empty"):+ parse_file(b"", "empty.csv")++ def test_csv_max_rows_truncated(self) -> None:+ header = "col1,col2\n"+ rows = "".join(f"val{i},data{i}\n" for i in range(15_000))+ data = (header + rows).encode()+ result = parse_file(data, "big.csv")+ assert "Truncated" in result.content+++# ---------------------------------------------------------------------------+# API integration+# ---------------------------------------------------------------------------+++@patch("posthoganalytics.feature_enabled", return_value=True)+class TestFileSourceAPIIntegration(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/business_knowledge/sources/"++ def test_upload_txt_file(self, _ff: MagicMock) -> None:+ content = b"Hello world\n\nSecond paragraph about pricing."+ uploaded = io.BytesIO(content)+ uploaded.name = "notes.txt"+ response = self.client.post(+ self.url,+ {"name": "My notes", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_201_CREATED, response.content+ body = response.json()+ assert body["source_type"] == "file"+ assert body["status"] == "ready"+ assert body["original_filename"] == "notes.txt"+ assert body["file_content_type"] == "text/plain"+ assert body["chunk_count"] >= 1++ source = KnowledgeSource.objects.unscoped().get(id=body["id"])+ assert KnowledgeDocument.objects.unscoped().filter(source=source, team=self.team).count() == 1+ assert KnowledgeChunk.objects.unscoped().filter(source=source, team=self.team).count() >= 1++ def test_upload_csv_file(self, _ff: MagicMock) -> None:+ content = b"name,role\nAlice,Engineer\nBob,Designer"+ uploaded = io.BytesIO(content)+ uploaded.name = "team.csv"+ response = self.client.post(+ self.url,+ {"name": "Team roster", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_201_CREATED+ body = response.json()+ assert body["file_content_type"] == "text/csv"+ assert body["chunk_count"] >= 1++ def test_upload_markdown_file(self, _ff: MagicMock) -> None:+ content = b"# FAQ\n\n## What is PostHog?\n\nPostHog is a product analytics platform."+ uploaded = io.BytesIO(content)+ uploaded.name = "faq.md"+ response = self.client.post(+ self.url,+ {"name": "FAQ", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_201_CREATED+ body = response.json()+ assert body["file_content_type"] == "text/markdown"++ def test_upload_docx_file(self, _ff: MagicMock) -> None:+ data = _make_minimal_docx("DOCX test content")+ uploaded = io.BytesIO(data)+ uploaded.name = "document.docx"+ response = self.client.post(+ self.url,+ {"name": "Word doc", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_201_CREATED+ body = response.json()+ assert body["file_content_type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ assert body["chunk_count"] >= 1++ def test_upload_rejects_unsupported_type(self, _ff: MagicMock) -> None:+ uploaded = io.BytesIO(b"\x89PNG\r\n\x1a\n" + b"\x00" * 100)+ uploaded.name = "image.png"+ response = self.client.post(+ self.url,+ {"name": "Image", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_400_BAD_REQUEST++ def test_upload_rejects_oversized_file(self, _ff: MagicMock) -> None:+ # The serializer checks UploadedFile.size which Django sets from the+ # actual content length. We can't send 50 MB in a unit test, but the+ # parse_file size guard is tested separately in TestParseFileSecurity.+ # Here we verify the parse_file guard fires at the API layer by+ # monkey-patching the cap to a tiny value.+ with patch("products.business_knowledge.backend.file_parse.MAX_FILE_SIZE_BYTES", 10):+ uploaded = io.BytesIO(b"x" * 100)+ uploaded.name = "big.txt"+ response = self.client.post(+ self.url,+ {"name": "Too big", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_400_BAD_REQUEST++ def test_upload_missing_file_field(self, _ff: MagicMock) -> None:+ response = self.client.post(+ self.url,+ {"name": "No file", "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_400_BAD_REQUEST++ def test_upload_missing_name(self, _ff: MagicMock) -> None:+ uploaded = io.BytesIO(b"content")+ uploaded.name = "data.txt"+ response = self.client.post(+ self.url,+ {"file": uploaded, "source_type": "file"},+ format="multipart",+ )+ assert response.status_code == http_status.HTTP_400_BAD_REQUEST++ def test_file_source_appears_in_list(self, _ff: MagicMock) -> None:+ uploaded = io.BytesIO(b"test content")+ uploaded.name = "test.txt"+ self.client.post(+ self.url,+ {"name": "Listed file", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ response = self.client.get(self.url)+ names = [r["name"] for r in response.json()["results"]]+ assert "Listed file" in names++ def test_file_source_cross_team_isolation(self, _ff: MagicMock) -> None:+ from posthog.models.team import Team++ uploaded = io.BytesIO(b"secret data")+ uploaded.name = "secret.txt"+ self.client.post(+ self.url,+ {"name": "Secret", "file": uploaded, "source_type": "file"},+ format="multipart",+ )+ source = KnowledgeSource.objects.unscoped().filter(team=self.team).first()+ assert source is not None++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ other_url = f"/api/projects/{other_team.id}/business_knowledge/sources/"+ response = self.client.get(f"{other_url}{source.id}/")+ assert response.status_code == http_status.HTTP_404_NOT_FOUNDdiff --git a/products/business_knowledge/backend/tests/test_logic.py b/products/business_knowledge/backend/tests/test_logic.pyindex e69de29bb2d1..f986d0c6a3ab 100644--- a/products/business_knowledge/backend/tests/test_logic.py+++ b/products/business_knowledge/backend/tests/test_logic.py@@ -0,0 +1,134 @@+import uuid++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from products.business_knowledge.backend.constants import CHUNK_HARD_MAX_CHARS+from products.business_knowledge.backend.logic import (+ QuotaExceededError,+ TextTooLargeError,+ _chunk_id,+ chunk_text,+ create_text_source,+)+from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, SourceStatus+++class TestChunker(BaseTest):+ @parameterized.expand(+ [+ ("empty", "", 0),+ ("single_short", "hello", 1),+ ("two_paragraphs", "a\n\nb", 1),+ ("crlf_paragraphs", "a\r\n\r\nb", 1),+ ("whitespace_only", " \n\n \t\n", 0),+ ]+ )+ def test_basic_chunking(self, _name: str, text: str, expected_count: int) -> None:+ assert len(chunk_text(text)) == expected_count++ def test_chunks_respect_target_size(self) -> None:+ paragraph = ("word " * 100).strip()+ text = "\n\n".join([paragraph] * 20)+ chunks = chunk_text(text)+ assert len(chunks) >= 2+ for c in chunks:+ assert len(c.content) <= CHUNK_HARD_MAX_CHARS++ def test_hard_splits_oversized_paragraph(self) -> None:+ # One paragraph larger than the hard cap should be broken up rather+ # than emitted as a single chunk.+ oversized = "x " * (CHUNK_HARD_MAX_CHARS)+ chunks = chunk_text(oversized)+ assert len(chunks) >= 2+ for c in chunks:+ assert len(c.content) <= CHUNK_HARD_MAX_CHARS++ def test_ordinals_are_zero_indexed_and_contiguous(self) -> None:+ text = "\n\n".join(f"para-{i}" * 200 for i in range(5))+ chunks = chunk_text(text)+ assert [c.ordinal for c in chunks] == list(range(len(chunks)))++ def test_chunk_ids_are_deterministic(self) -> None:+ source_a = uuid.uuid4()+ source_b = uuid.uuid4()+ a = _chunk_id(source_a, "doc-stable-123", "", 0)+ b = _chunk_id(source_a, "doc-stable-123", "", 0)+ c = _chunk_id(source_a, "doc-stable-123", "", 1)+ d = _chunk_id(source_a, "doc-stable-456", "", 0)+ e = _chunk_id(source_b, "doc-stable-123", "", 0)+ assert a == b+ assert a != c+ assert a != d+ # Different sources with identical document/heading/ordinal → different+ # chunk UUIDs. This is what protects us from IntegrityError when two+ # URL-backed sources crawl the same URL (stable_id == url).+ assert a != e+++class TestCreateTextSource(BaseTest):+ def _count_for(self, model, team):+ return model.objects.unscoped().filter(team=team).count()++ def test_create_text_source_happy_path(self) -> None:+ source = create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Product docs",+ text="Paragraph one.\n\nParagraph two has more detail here.",+ )+ assert source.status == SourceStatus.READY+ assert self._count_for(KnowledgeDocument, self.team) == 1+ assert self._count_for(KnowledgeChunk, self.team) >= 1+ # team_id must land on child rows too.+ assert (+ KnowledgeChunk.objects.unscoped().filter(team=self.team).count()+ == KnowledgeChunk.objects.unscoped().count()+ )+ assert (+ KnowledgeDocument.objects.unscoped().filter(team=self.team).count()+ == KnowledgeDocument.objects.unscoped().count()+ )++ def test_chunks_carry_source_and_document_fks(self) -> None:+ source = create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Docs",+ text="a" * 300 + "\n\n" + "b" * 300,+ )+ chunks = KnowledgeChunk.objects.unscoped().filter(source=source)+ assert chunks.count() >= 1+ for c in chunks:+ assert c.source_id == source.id+ assert c.document_id is not None+ assert c.char_count == len(c.content)++ def test_text_too_large_rejected(self) -> None:+ # 1 MB + 1 byte over the limit.+ huge = "x" * 1_000_001+ with self.assertRaises(TextTooLargeError):+ create_text_source(team_id=self.team.id, created_by_id=self.user.id, name="Huge", text=huge)++ def test_quota_on_source_count(self) -> None:+ # Patch the cap so the test finishes in one source instead of 500.+ with patch("products.business_knowledge.backend.logic.MAX_SOURCES_PER_TEAM", 1):+ create_text_source(team_id=self.team.id, created_by_id=self.user.id, name="First", text="hello")+ with self.assertRaises(QuotaExceededError):+ create_text_source(team_id=self.team.id, created_by_id=self.user.id, name="Second", text="hello")++ def test_cross_team_isolation(self) -> None:+ # Another team in the same org should not be able to read or list+ # rows we create.+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ create_text_source(team_id=self.team.id, created_by_id=self.user.id, name="Mine", text="secret content")+ from products.business_knowledge.backend import logic++ assert len(logic.list_for_team(self.team.id)) == 1+ assert len(logic.list_for_team(other_team.id)) == 0diff --git a/products/business_knowledge/backend/tests/test_models.py b/products/business_knowledge/backend/tests/test_models.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/business_knowledge/backend/tests/test_presentation.py b/products/business_knowledge/backend/tests/test_presentation.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/business_knowledge/backend/tests/test_retrieval_eval.py b/products/business_knowledge/backend/tests/test_retrieval_eval.pynew file mode 100644index 000000000000..164cfe85a391--- /dev/null+++ b/products/business_knowledge/backend/tests/test_retrieval_eval.py@@ -0,0 +1,65 @@+from pathlib import Path++from posthog.test.base import BaseTest++import yaml+from parameterized import parameterized++from products.business_knowledge.backend import logic+from products.business_knowledge.backend.logic import create_text_source++FIXTURES_DIR = Path(__file__).parent / "fixtures"+++def _load_eval_cases() -> list[tuple[str, str, bool]]:+ """Return (label, query, expect_found) tuples for parameterized tests."""+ with open(FIXTURES_DIR / "retrieval_eval.yaml") as f:+ data = yaml.safe_load(f)+ cases: list[tuple[str, str, bool]] = []+ for entry in data:+ source_name = entry["source_name"]+ for q in entry["queries"]:+ label = f"{source_name}|{q['query']}"+ cases.append((label, q["query"], q["expect_found"]))+ return cases+++class TestRetrievalEval(BaseTest):+ @classmethod+ def setUpTestData(cls) -> None:+ super().setUpTestData()+ with open(FIXTURES_DIR / "retrieval_eval.yaml") as f:+ data = yaml.safe_load(f)+ for entry in data:+ create_text_source(+ team_id=cls.team.id,+ created_by_id=cls.user.id,+ name=entry["source_name"],+ text=entry["text"],+ )++ @parameterized.expand(_load_eval_cases)+ def test_search(self, _label: str, query: str, expect_found: bool) -> None:+ results = logic.search_knowledge(self.team.id, query)+ if expect_found:+ assert len(results) > 0, f"Expected results for '{query}' but got none"+ else:+ assert len(results) == 0, (+ f"Expected no results for '{query}' but got {len(results)}: {[r.source_name for r in results]}"+ )++ def test_empty_query_returns_nothing(self) -> None:+ assert logic.search_knowledge(self.team.id, "") == []+ assert logic.search_knowledge(self.team.id, " ") == []++ def test_limit_respected(self) -> None:+ results = logic.search_knowledge(self.team.id, "refund", limit=1)+ assert len(results) <= 1++ def test_results_have_source_metadata(self) -> None:+ results = logic.search_knowledge(self.team.id, "refund")+ assert len(results) > 0+ r = results[0]+ assert r.source_name == "Refund Policy"+ assert r.chunk_id is not None+ assert r.source_id is not Nonediff --git a/products/business_knowledge/backend/tests/test_tasks.py b/products/business_knowledge/backend/tests/test_tasks.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/business_knowledge/backend/tests/test_url_ingest.py b/products/business_knowledge/backend/tests/test_url_ingest.pynew file mode 100644index 000000000000..3b3e690b642f--- /dev/null+++ b/products/business_knowledge/backend/tests/test_url_ingest.py@@ -0,0 +1,458 @@+"""+Tests for Stage 2a URL ingestion: SSRF hardening, fetch/parse/chunk happy+path, conditional-GET 304 behavior, cross-team isolation on refresh.++Design notes:+- We mock `requests.Session.get` at the module level of `url_fetch` rather+ than monkey-patching `requests` globally — keeps blast radius to this+ product's fetch path and matches how other PostHog tests isolate HTTP.+- SSRF is covered exhaustively in `posthog/security/test/test_url_validation.py`.+ We only smoke-test that our create path *routes through* it (one localhost+ attempt should fail fast).+"""++from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework import status++from products.business_knowledge.backend import url_fetch+from products.business_knowledge.backend.logic import (+ InvalidUrlError,+ QuotaExceededError,+ SourceBusyError,+ create_url_source,+ refresh_source,+ update_url_source,+)+from products.business_knowledge.backend.models import (+ KnowledgeChunk,+ KnowledgeDocument,+ KnowledgeSource,+ RefreshStatus,+ SourceStatus,+ SourceType,+)+++def _mock_response(+ *,+ status_code: int = 200,+ body: bytes = b"",+ content_type: str = "text/html; charset=utf-8",+ etag: str | None = None,+ location: str | None = None,+) -> MagicMock:+ headers: dict[str, str] = {"Content-Type": content_type}+ if etag:+ headers["ETag"] = etag+ if location:+ headers["Location"] = location+ response = MagicMock()+ response.status_code = status_code+ response.headers = headers+ response.iter_content = MagicMock(return_value=iter([body] if body else []))+ response.close = MagicMock()+ return response+++class TestNormalizeUrl(BaseTest):+ def test_strips_userinfo(self) -> None:+ assert url_fetch.strip_userinfo("https://user:[email protected]/x") == "https://example.com/x"++ def test_lowercases_host_and_scheme(self) -> None:+ assert url_fetch.normalize_url("HTTPS://Example.COM/PATH") == "https://example.com/PATH"++ def test_drops_fragment(self) -> None:+ assert url_fetch.normalize_url("https://example.com/x#section") == "https://example.com/x"++ @parameterized.expand(+ [+ ("empty", ""),+ ("scheme_only", "http://"),+ ("missing_scheme", "example.com/x"),+ ]+ )+ def test_rejects_garbage(self, _name: str, raw: str) -> None:+ with self.assertRaises(url_fetch.UrlFetchError):+ url_fetch.normalize_url(raw)+++class TestFetchUrl(BaseTest):+ @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips", return_value=(True, None, set()))+ @patch("products.business_knowledge.backend.url_fetch.requests.Session")+ def test_happy_path_returns_body(self, mock_session_cls: MagicMock, _ssrf: MagicMock) -> None:+ session = mock_session_cls.return_value+ session.get.return_value = _mock_response(body=b"<html>hi</html>", etag='"abc"')+ result = url_fetch.fetch_url("https://example.com/x")+ assert result.status == 200+ assert result.body == b"<html>hi</html>"+ assert result.etag == '"abc"'++ @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips", return_value=(True, None, set()))+ @patch("products.business_knowledge.backend.url_fetch.requests.Session")+ def test_conditional_get_returns_304(self, mock_session_cls: MagicMock, _ssrf: MagicMock) -> None:+ session = mock_session_cls.return_value+ session.get.return_value = _mock_response(status_code=304, body=b"")+ result = url_fetch.fetch_url("https://example.com/x", etag='"abc"')+ assert result.status == 304+ assert result.body is None++ @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips", return_value=(True, None, set()))+ @patch("products.business_knowledge.backend.url_fetch.requests.Session")+ def test_size_cap_aborts(self, mock_session_cls: MagicMock, _ssrf: MagicMock) -> None:+ session = mock_session_cls.return_value+ # Bigger than URL_MAX_BYTES.+ big_chunk = b"x" * (10 * 1024 * 1024 + 1)+ response = _mock_response(body=b"")+ response.iter_content = MagicMock(return_value=iter([big_chunk]))+ session.get.return_value = response+ with self.assertRaises(url_fetch.UrlFetchError):+ url_fetch.fetch_url("https://example.com/x")++ @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips")+ @patch("products.business_knowledge.backend.url_fetch.requests.Session")+ def test_redirect_revalidates_ssrf(self, mock_session_cls: MagicMock, mock_ssrf: MagicMock) -> None:+ # First hop allowed (public), second hop blocked (internal). If the+ # client blindly followed, the second Location would be fetched.+ mock_ssrf.side_effect = [(True, None, set()), (False, "Loopback", set())]+ session = mock_session_cls.return_value+ session.get.return_value = _mock_response(status_code=302, body=b"", location="http://127.0.0.1/admin")+ with self.assertRaises(url_fetch.UrlFetchError):+ url_fetch.fetch_url("https://example.com/x")+ # SSRF check was re-run on the redirect target.+ assert mock_ssrf.call_count == 2++ @patch(+ "products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips",+ return_value=(False, "Loopback", set()),+ )+ def test_ssrf_blocked_upfront(self, _ssrf: MagicMock) -> None:+ with self.assertRaises(url_fetch.UrlFetchError):+ url_fetch.fetch_url("http://localhost/admin")+++_BASIC_HTML = b"""<!doctype html>+<html><head><title>Billing</title></head>+<body>+<article>+<h1>Refund policy</h1>+<p>We issue full refunds within 30 days of purchase. No questions asked.</p>+<p>To request a refund, open a ticket with your order number.</p>+</article>+</body></html>"""+++class TestCreateUrlSource(BaseTest):+ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_happy_path_creates_document_and_chunks(self, _ssrf: MagicMock, mock_fetch: MagicMock) -> None:+ mock_fetch.return_value = url_fetch.FetchResult(+ status=200,+ body=_BASIC_HTML,+ content_type="text/html",+ etag='"v1"',+ final_url="https://docs.example.com/billing",+ )+ source = create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Billing docs",+ url="https://docs.example.com/billing",+ )+ assert source.status == SourceStatus.READY+ assert source.source_type == SourceType.URL+ assert source.source_url == "https://docs.example.com/billing"+ assert source.last_refresh_status == RefreshStatus.SUCCESS+ assert source.last_etag == '"v1"'+ assert KnowledgeDocument.objects.unscoped().filter(source=source).count() == 1+ assert KnowledgeChunk.objects.unscoped().filter(source=source, team=self.team).count() >= 1++ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(False, "Loopback"))+ def test_ssrf_rejection_does_not_create_source(self, _ssrf: MagicMock) -> None:+ with self.assertRaises(InvalidUrlError):+ create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Bad",+ url="http://127.0.0.1/admin",+ )+ assert KnowledgeSource.objects.unscoped().filter(team=self.team).count() == 0++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_fetch_failure_persists_error_source(self, _ssrf: MagicMock, mock_fetch: MagicMock) -> None:+ mock_fetch.side_effect = url_fetch.UrlFetchError("Remote responded with status 503.")+ source = create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Flaky",+ url="https://flaky.example.com/",+ )+ assert source.status == SourceStatus.ERROR+ assert source.last_refresh_status == RefreshStatus.ERROR+ assert source.error_message == "Remote responded with status 503."++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_quota_exceeded_during_chunk_insert_marks_error(self, _ssrf: MagicMock, mock_fetch: MagicMock) -> None:+ mock_fetch.return_value = url_fetch.FetchResult(+ status=200,+ body=_BASIC_HTML,+ content_type="text/html",+ etag='"v1"',+ final_url="https://docs.example.com/billing",+ )+ with patch(+ "products.business_knowledge.backend.logic._replace_source_content",+ side_effect=QuotaExceededError("Team already near the 100000 chunk cap."),+ ):+ with self.assertRaises(QuotaExceededError):+ create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Over quota",+ url="https://docs.example.com/billing",+ )+ source = KnowledgeSource.objects.unscoped().get(team_id=self.team.id, name="Over quota")+ assert source.status == SourceStatus.ERROR+ assert "Quota exceeded" in source.error_message++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_concurrent_create_blocked_by_processing_claim(self, _ssrf: MagicMock, mock_fetch: MagicMock) -> None:+ mock_fetch.return_value = url_fetch.FetchResult(+ status=200,+ body=_BASIC_HTML,+ content_type="text/html",+ etag='"v1"',+ final_url="https://docs.example.com/billing",+ )+ create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="First",+ url="https://docs.example.com/billing",+ )+ # Simulate a PROCESSING row left by a concurrent in-flight request.+ KnowledgeSource.objects.unscoped().create(+ team_id=self.team.id,+ name="In-flight",+ source_type=SourceType.URL,+ status=SourceStatus.PROCESSING,+ source_url="https://other.example.com/",+ )+ with self.assertRaises(SourceBusyError):+ create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Second",+ url="https://other.example.com/",+ )+ # The fetch should never be called for the second create.+ assert mock_fetch.call_count == 1+++class TestUpdateUrlSource(BaseTest):+ def _seed(self) -> KnowledgeSource:+ with (+ patch(+ "products.business_knowledge.backend.logic.url_fetch.fetch_url",+ return_value=url_fetch.FetchResult(+ status=200,+ body=_BASIC_HTML,+ content_type="text/html",+ etag='"v1"',+ final_url="https://docs.example.com/billing",+ ),+ ),+ patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None)),+ ):+ return create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Billing",+ url="https://docs.example.com/billing",+ )++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_busy_reverts_url_change(self, _ssrf: MagicMock, _fetch: MagicMock) -> None:+ source = self._seed()+ KnowledgeSource.objects.unscoped().create(+ team_id=self.team.id,+ name="Blocker",+ source_type=SourceType.URL,+ status=SourceStatus.PROCESSING,+ source_url="https://blocker.example.com/",+ )+ with self.assertRaises(SourceBusyError):+ update_url_source(+ source_id=source.id,+ team_id=self.team.id,+ url="https://new.example.com/docs",+ )+ source.refresh_from_db()+ assert source.source_url == "https://docs.example.com/billing"+++class TestRefreshSource(BaseTest):+ def _seed(self, etag: str = '"old"') -> KnowledgeSource:+ with (+ patch(+ "products.business_knowledge.backend.logic.url_fetch.fetch_url",+ return_value=url_fetch.FetchResult(+ status=200,+ body=_BASIC_HTML,+ content_type="text/html",+ etag=etag,+ final_url="https://docs.example.com/billing",+ ),+ ),+ patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None)),+ ):+ return create_url_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Billing",+ url="https://docs.example.com/billing",+ )++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_304_keeps_chunks_marks_not_modified(self, _ssrf: MagicMock, mock_fetch: MagicMock) -> None:+ source = self._seed(etag='"v1"')+ original_chunks = list(+ KnowledgeChunk.objects.unscoped().filter(source=source).order_by("ordinal").values_list("id", flat=True)+ )+ mock_fetch.return_value = url_fetch.FetchResult(+ status=304,+ body=None,+ content_type=None,+ etag='"v1"',+ final_url="https://docs.example.com/billing",+ )+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)+ assert refreshed is not None+ assert refreshed.last_refresh_status == RefreshStatus.NOT_MODIFIED+ # Chunks preserved identity — agents with cached chunk ids are still valid.+ new_chunks = list(+ KnowledgeChunk.objects.unscoped().filter(source=source).order_by("ordinal").values_list("id", flat=True)+ )+ assert new_chunks == original_chunks++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_200_with_changed_content_rebuilds_chunks(self, _ssrf: MagicMock, mock_fetch: MagicMock) -> None:+ source = self._seed(etag='"v1"')+ old_contents = set(KnowledgeChunk.objects.unscoped().filter(source=source).values_list("content", flat=True))+ new_html = b"""<!doctype html><html><body><article>+<h1>Refund policy</h1>+<p>BRAND NEW: 60-day refunds are now available.</p>+</article></body></html>"""+ mock_fetch.return_value = url_fetch.FetchResult(+ status=200,+ body=new_html,+ content_type="text/html",+ etag='"v2"',+ final_url="https://docs.example.com/billing",+ )+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)+ assert refreshed is not None+ assert refreshed.last_refresh_status == RefreshStatus.SUCCESS+ assert refreshed.last_etag == '"v2"'+ new_contents = set(KnowledgeChunk.objects.unscoped().filter(source=source).values_list("content", flat=True))+ # Chunk *content* must change. Chunk ids are deterministic in the url ++ # ordinal space, so they stay stable across refreshes — that's by design+ # so agents' cached citations keep resolving.+ assert new_contents != old_contents+ assert any("60-day" in c for c in new_contents)++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_busy_source_rejects(self, _ssrf: MagicMock, _fetch: MagicMock) -> None:+ source = self._seed()+ KnowledgeSource.objects.unscoped().filter(id=source.id).update(status=SourceStatus.PROCESSING)+ with self.assertRaises(SourceBusyError):+ refresh_source(source_id=source.id, team_id=self.team.id)++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ def test_refresh_blocked_when_another_source_processing(self, _ssrf: MagicMock, _fetch: MagicMock) -> None:+ source_a = self._seed()+ source_b = self._seed()+ KnowledgeSource.objects.unscoped().filter(id=source_a.id).update(status=SourceStatus.PROCESSING)+ with self.assertRaises(SourceBusyError):+ refresh_source(source_id=source_b.id, team_id=self.team.id)++ def test_cross_team_refresh_returns_none(self) -> None:+ from posthog.models.team import Team++ source = self._seed()+ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ assert refresh_source(source_id=source.id, team_id=other_team.id) is None+++@patch("posthoganalytics.feature_enabled", return_value=True)+class TestUrlApi(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/business_knowledge/sources/"++ @patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")+ @patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))+ @patch(+ "products.business_knowledge.backend.api.serializers.is_url_allowed",+ return_value=(True, None),+ )+ def test_create_url_source_api(+ self, _serializer_ssrf: MagicMock, _logic_ssrf: MagicMock, mock_fetch: MagicMock, _ff: MagicMock+ ) -> None:+ mock_fetch.return_value = url_fetch.FetchResult(+ status=200,+ body=_BASIC_HTML,+ content_type="text/html",+ etag='"v1"',+ final_url="https://docs.example.com/billing",+ )+ response = self.client.post(+ self.url,+ {"name": "Docs", "url": "https://docs.example.com/billing", "source_type": "url"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content+ body = response.json()+ assert body["source_type"] == "url"+ assert body["status"] == "ready"+ assert body["source_url"] == "https://docs.example.com/billing"++ @patch(+ "products.business_knowledge.backend.api.serializers.is_url_allowed",+ return_value=(False, "Loopback"),+ )+ def test_create_url_source_rejects_internal(self, _ssrf: MagicMock, _ff: MagicMock) -> None:+ response = self.client.post(+ self.url,+ {"name": "Bad", "url": "http://127.0.0.1/admin", "source_type": "url"},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content++ def test_cross_team_refresh_returns_404(self, _ff: MagicMock) -> None:+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ theirs = KnowledgeSource.objects.unscoped().create(+ team=other_team,+ name="Theirs",+ source_type=SourceType.URL,+ status=SourceStatus.READY,+ source_url="https://docs.example.com/",+ )+ response = self.client.post(f"{self.url}{theirs.id}/refresh/")+ assert response.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/business_knowledge/backend/url_fetch.py b/products/business_knowledge/backend/url_fetch.pynew file mode 100644index 000000000000..a68051d0627a--- /dev/null+++ b/products/business_knowledge/backend/url_fetch.py@@ -0,0 +1,326 @@+"""+SSRF-hardened HTTP fetch for URL-backed knowledge sources.++Responsibilities:+- Validate URL (reuses `posthog.security.url_validation`) before each hop.+- Pin validated IPs so ``requests`` connects to the exact IPs we checked,+ eliminating the DNS-rebinding TOCTOU window.+- Manual redirect handling — we refuse the default `requests` redirect chain+ because it does *not* re-validate the target IP, which is the classic+ DNS-rebinding / open-redirect bypass for SSRF.+- Stream-read the body with a hard byte cap so a malicious server can't blow+ up process memory by advertising `Content-Length: 0` and then never closing.+- Conditional GET (`If-None-Match`) so repeat refreshes are cheap.+"""++from __future__ import annotations++import hashlib+import ipaddress+import urllib.parse as urlparse+from dataclasses import dataclass++import requests+import structlog+from requests.adapters import HTTPAdapter++from posthog.security.url_validation import validate_url_and_pin_ips++from .constants import URL_CONNECT_TIMEOUT, URL_MAX_BYTES, URL_MAX_REDIRECTS, URL_READ_TIMEOUT, URL_USER_AGENT++logger = structlog.get_logger(__name__)+++class UrlFetchError(Exception):+ """Generic fetch failure. Message is user-safe (no internal detail)."""+++@dataclass(frozen=True)+class FetchResult:+ status: int # 200 on success, 304 on Not Modified+ body: bytes | None # None on 304+ content_type: str | None+ etag: str | None+ final_url: str+++def strip_userinfo(url: str) -> str:+ """+ Remove `user:pass@` from authority. Userinfo in URLs is a known SSRF+ smuggling vector (some libraries interpret it as the host when stricter+ parsers don't).+ """++ parsed = urlparse.urlparse(url)+ if parsed.username is None and parsed.password is None:+ return url+ netloc = parsed.hostname or ""+ if parsed.port:+ netloc = f"{netloc}:{parsed.port}"+ return urlparse.urlunparse(parsed._replace(netloc=netloc))+++def normalize_url(raw: str) -> str:+ """+ Canonicalize a user-submitted URL before validating or storing it.++ Intentionally minimal: strip userinfo + fragment, lowercase the scheme+ and host. We do NOT touch the path/query — a lot of docs sites care about+ trailing slashes and case in path segments.+ """++ raw = raw.strip()+ parsed = urlparse.urlparse(raw)+ if not parsed.scheme or not parsed.netloc:+ raise UrlFetchError("Invalid URL.")+ scheme = parsed.scheme.lower()+ host = (parsed.hostname or "").lower()+ if not host:+ raise UrlFetchError("Invalid URL.")+ netloc = host+ if parsed.port:+ netloc = f"{netloc}:{parsed.port}"+ return urlparse.urlunparse((scheme, netloc, parsed.path, parsed.params, parsed.query, ""))+++def sha256_of(text: str) -> str:+ return hashlib.sha256(text.encode("utf-8")).hexdigest()+++# --- DNS-pinning adapter — eliminates TOCTOU rebinding window ----------------+++class _PinnedIPAdapter(HTTPAdapter):+ """+ Requests adapter that rewrites URLs to connect to pre-validated IPs,+ preventing DNS rebinding between validation and connection.++ For HTTPS, sets ``assert_hostname`` and ``server_hostname`` on the+ connection pool so TLS SNI and certificate verification use the+ original hostname (not the IP).++ NOT thread-safe — designed for single-use sessions in ``_ssrf_safe_get``.+ """++ def __init__(self) -> None:+ super().__init__()+ self._pin_map: dict[str, str] = {}+ self._current_original_host: str | None = None++ def pin(self, hostname: str, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> None:+ self._pin_map[hostname.lower()] = str(ip)++ def send( # type: ignore[override]+ self,+ request: requests.PreparedRequest,+ stream: bool = False,+ timeout: None | float | tuple[float, float] = None,+ verify: bool | str = True,+ cert: None | str | tuple[str, str] = None,+ proxies: dict[str, str] | None = None,+ ) -> requests.Response:+ parsed = urlparse.urlparse(request.url or "")+ host = (parsed.hostname or "").lower()+ ip_str = self._pin_map.get(host)++ if ip_str is not None:+ self._current_original_host = host++ ip_netloc = f"[{ip_str}]" if ":" in ip_str else ip_str+ if parsed.port:+ ip_netloc = f"{ip_netloc}:{parsed.port}"++ request.url = urlparse.urlunparse((parsed.scheme, ip_netloc, parsed.path, parsed.params, parsed.query, ""))++ original_netloc = host+ if parsed.port:+ original_netloc = f"{host}:{parsed.port}"+ if request.headers is not None:+ request.headers["Host"] = original_netloc+ else:+ self._current_original_host = None++ return super().send(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)++ def cert_verify(self, conn: object, url: str, verify: bool | str, cert: None | str | tuple[str, str]) -> None:+ super().cert_verify(conn, url, verify, cert)+ original = getattr(self, "_current_original_host", None)+ if original:+ # We mutate urllib3 pool internals intentionally — these attributes+ # exist at runtime (verified against urllib3 2.6.3) but aren't+ # visible to static type checkers.+ if hasattr(conn, "assert_hostname"):+ conn.assert_hostname = original # ty: ignore[invalid-assignment]+ # Inject server_hostname into conn_kw so newly created connections+ # use the original hostname for TLS SNI (not the rewritten IP).+ # urllib3 passes **conn_kw to ConnectionCls.__init__, and+ # HTTPSConnection.connect() reads self.server_hostname for SNI.+ if hasattr(conn, "conn_kw") and isinstance(getattr(conn, "conn_kw", None), dict):+ conn.conn_kw["server_hostname"] = original # ty: ignore[invalid-assignment]+++# --- Shared SSRF-safe fetch core ---------------------------------------------+++def _read_capped(response: requests.Response, cap: int) -> bytes:+ """Stream the body into memory but abort as soon as we cross `cap` bytes."""++ chunks: list[bytes] = []+ total = 0+ for chunk in response.iter_content(chunk_size=64 * 1024):+ if not chunk:+ continue+ total += len(chunk)+ if total > cap:+ raise UrlFetchError("Remote response exceeds the maximum allowed size.")+ chunks.append(chunk)+ return b"".join(chunks)+++def _ssrf_safe_get(+ url: str,+ *,+ headers: dict[str, str],+ max_bytes: int = URL_MAX_BYTES,+ etag: str | None = None,+) -> FetchResult:+ """+ Core SSRF-hardened GET with manual redirect handling and DNS pinning.++ Re-validates ``validate_url_and_pin_ips`` on every redirect hop and+ pins the validated IPs so ``requests`` connects to the exact addresses+ we checked (no DNS rebinding window). Stream-reads the body with a+ hard byte cap.++ Raises ``UrlFetchError`` with a user-safe message on any failure.+ """++ current = strip_userinfo(normalize_url(url))+ adapter = _PinnedIPAdapter()+ session = requests.Session()+ session.mount("http://", adapter) # nosemgrep: request-session-with-http+ session.mount("https://", adapter)+ try:+ for _hop in range(URL_MAX_REDIRECTS + 1):+ allowed, reason, pinned_ips = validate_url_and_pin_ips(current)+ if not allowed:+ logger.warning(+ "business_knowledge.url_fetch.ssrf_blocked",+ url=current,+ reason=reason,+ )+ raise UrlFetchError("URL is not reachable from this environment.")++ # Pin the first validated IP so requests connects to it directly+ parsed = urlparse.urlparse(current)+ hostname = (parsed.hostname or "").lower()+ if pinned_ips:+ adapter.pin(hostname, next(iter(pinned_ips)))++ merged_headers = dict(headers)+ if etag:+ merged_headers["If-None-Match"] = etag++ try:+ response = session.get(+ current,+ headers=merged_headers,+ timeout=(URL_CONNECT_TIMEOUT, URL_READ_TIMEOUT),+ allow_redirects=False,+ stream=True,+ )+ except requests.RequestException as exc:+ logger.info(+ "business_knowledge.url_fetch.transport_error",+ url=current,+ error_type=type(exc).__name__,+ )+ raise UrlFetchError("Failed to fetch the URL.") from exc++ try:+ if response.status_code in (301, 302, 303, 307, 308):+ location = response.headers.get("Location")+ if not location:+ raise UrlFetchError("Redirect without Location header.")+ next_url = strip_userinfo(urlparse.urljoin(current, location))+ current = normalize_url(next_url)+ continue++ if response.status_code == 304:+ return FetchResult(+ status=304,+ body=None,+ content_type=response.headers.get("Content-Type"),+ etag=response.headers.get("ETag") or etag,+ final_url=current,+ )++ if response.status_code >= 400:+ raise UrlFetchError(f"Remote responded with status {response.status_code}.")++ declared = response.headers.get("Content-Length")+ if declared and declared.isdigit() and int(declared) > max_bytes:+ raise UrlFetchError("Remote response exceeds the maximum allowed size.")++ body = _read_capped(response, max_bytes)+ return FetchResult(+ status=200,+ body=body,+ content_type=response.headers.get("Content-Type"),+ etag=response.headers.get("ETag"),+ final_url=current,+ )+ finally:+ response.close()++ raise UrlFetchError("Too many redirects.")+ finally:+ session.close()+++# --- Public API ---------------------------------------------------------------+++_CONTENT_HEADERS = {+ "User-Agent": URL_USER_AGENT,+ "Accept": "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1",+ "Accept-Language": "en;q=0.9,*;q=0.5",+}++_METADATA_HEADERS = {+ "User-Agent": URL_USER_AGENT,+ "Accept": "application/xml,text/xml,text/html;q=0.9,text/plain;q=0.5,*/*;q=0.1",+}+++def fetch_url(url: str, *, etag: str | None = None) -> FetchResult:+ """+ Fetch `url` with SSRF re-validation on every redirect hop.++ Raises `UrlFetchError` with a user-safe message on any failure.+ """++ return _ssrf_safe_get(url, headers=_CONTENT_HEADERS, etag=etag)+++def fetch_text(url: str, *, max_bytes: int = URL_MAX_BYTES) -> str:+ """+ SSRF-safe GET returning decoded text. Used by discover for machine-readable+ metadata (sitemap.xml, robots.txt, HTML for link extraction).++ Raises `UrlFetchError` on failure.+ """++ result = _ssrf_safe_get(url, headers=_METADATA_HEADERS, max_bytes=max_bytes)+ if result.body is None:+ return ""+ return result.body.decode("utf-8", errors="replace")+++def is_html_content_type(content_type: str | None) -> bool:+ if not content_type:+ # Missing header — trafilatura can still do something sensible with+ # raw HTML, and we fall back to bs4 if it can't.+ return True+ lowered = content_type.split(";", 1)[0].strip().lower()+ return lowered in {"text/html", "application/xhtml+xml", "text/plain"}diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..eacddc417054--- /dev/null+++ b/products/business_knowledge/frontend/generated/api.schemas.ts@@ -0,0 +1,141 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `text` - Text+ * `url` - URL+ * `file` - File+ */+export type KnowledgeSourceSourceTypeEnumApi =+ (typeof KnowledgeSourceSourceTypeEnumApi)[keyof typeof KnowledgeSourceSourceTypeEnumApi]++export const KnowledgeSourceSourceTypeEnumApi = {+ Text: 'text',+ Url: 'url',+ File: 'file',+} as const++/**+ * * `pending` - Pending+ * `processing` - Processing+ * `ready` - Ready+ * `error` - Error+ */+export type KnowledgeSourceStatusEnumApi =+ (typeof KnowledgeSourceStatusEnumApi)[keyof typeof KnowledgeSourceStatusEnumApi]++export const KnowledgeSourceStatusEnumApi = {+ Pending: 'pending',+ Processing: 'processing',+ Ready: 'ready',+ Error: 'error',+} as const++/**+ * * `success` - Success+ * `not_modified` - Not modified+ * `error` - Error+ */+export type LastRefreshStatusEnumApi = (typeof LastRefreshStatusEnumApi)[keyof typeof LastRefreshStatusEnumApi]++export const LastRefreshStatusEnumApi = {+ Success: 'success',+ NotModified: 'not_modified',+ Error: 'error',+} as const++/**+ * * `single` - Single page+ * `sitemap` - Sitemap+ * `same_origin` - Same origin crawl+ * `github_repo` - GitHub repository+ */+export type CrawlModeEnumApi = (typeof CrawlModeEnumApi)[keyof typeof CrawlModeEnumApi]++export const CrawlModeEnumApi = {+ Single: 'single',+ Sitemap: 'sitemap',+ SameOrigin: 'same_origin',+ GithubRepo: 'github_repo',+} as const++export interface KnowledgeSourceApi {+ readonly id: string+ readonly team_id: number+ readonly name: string+ readonly source_type: KnowledgeSourceSourceTypeEnumApi+ readonly status: KnowledgeSourceStatusEnumApi+ readonly error_message: string+ /** Number of documents belonging to this source. */+ readonly document_count: number+ /** Number of chunks belonging to this source. */+ readonly chunk_count: number+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null+ readonly source_url: string+ /** @nullable */+ readonly last_refresh_at: string | null+ readonly last_refresh_status: LastRefreshStatusEnumApi+ readonly last_refresh_error: string+ readonly crawl_mode: CrawlModeEnumApi+ readonly crawl_config: unknown+ readonly original_filename: string+ readonly file_content_type: string+ /** @nullable */+ readonly file_size_bytes: number | null+}++export interface PaginatedKnowledgeSourceListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: KnowledgeSourceApi[]+}++export interface CreateTextSourceApi {+ /**+ * Short human label for the source. Shown in the settings list and in agent citations.+ * @maxLength 255+ */+ name: string+ /** Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL/file support in Stage 2/3. */+ text: string+}++/**+ * PATCH payload for text sources. Both fields optional, at least one+required. `text` triggers a re-chunk; `name` alone does not.+ */+export interface PatchedUpdateTextSourceApi {+ /**+ * New human label for the source.+ * @maxLength 255+ */+ name?: string+ /** Replacement text. Omit to keep the existing content. */+ text?: string+}++export type BusinessKnowledgeSourcesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type BusinessKnowledgeSourcesTextRetrieve200 = {+ text?: string+}diff --git a/products/business_knowledge/frontend/generated/api.ts b/products/business_knowledge/frontend/generated/api.tsnew file mode 100644index 000000000000..c0da13e0e5d0--- /dev/null+++ b/products/business_knowledge/frontend/generated/api.ts@@ -0,0 +1,163 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ BusinessKnowledgeSourcesListParams,+ BusinessKnowledgeSourcesTextRetrieve200,+ CreateTextSourceApi,+ KnowledgeSourceApi,+ PaginatedKnowledgeSourceListApi,+ PatchedUpdateTextSourceApi,+} from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getBusinessKnowledgeSourcesListUrl = (projectId: string, params?: BusinessKnowledgeSourcesListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/business_knowledge/sources/?${stringifiedParams}`+ : `/api/projects/${projectId}/business_knowledge/sources/`+}++export const businessKnowledgeSourcesList = async (+ projectId: string,+ params?: BusinessKnowledgeSourcesListParams,+ options?: RequestInit+): Promise<PaginatedKnowledgeSourceListApi> => {+ return apiMutator<PaginatedKnowledgeSourceListApi>(getBusinessKnowledgeSourcesListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getBusinessKnowledgeSourcesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/business_knowledge/sources/`+}++export const businessKnowledgeSourcesCreate = async (+ projectId: string,+ createTextSourceApi: CreateTextSourceApi,+ options?: RequestInit+): Promise<KnowledgeSourceApi> => {+ return apiMutator<KnowledgeSourceApi>(getBusinessKnowledgeSourcesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createTextSourceApi),+ })+}++export const getBusinessKnowledgeSourcesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/sources/${id}/`+}++export const businessKnowledgeSourcesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<KnowledgeSourceApi> => {+ return apiMutator<KnowledgeSourceApi>(getBusinessKnowledgeSourcesRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getBusinessKnowledgeSourcesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/sources/${id}/`+}++export const businessKnowledgeSourcesPartialUpdate = async (+ projectId: string,+ id: string,+ patchedUpdateTextSourceApi?: PatchedUpdateTextSourceApi,+ options?: RequestInit+): Promise<KnowledgeSourceApi> => {+ return apiMutator<KnowledgeSourceApi>(getBusinessKnowledgeSourcesPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedUpdateTextSourceApi),+ })+}++export const getBusinessKnowledgeSourcesDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/sources/${id}/`+}++export const businessKnowledgeSourcesDestroy = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBusinessKnowledgeSourcesDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getBusinessKnowledgeSourcesRefreshCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/sources/${id}/refresh/`+}++export const businessKnowledgeSourcesRefreshCreate = async (+ projectId: string,+ id: string,+ knowledgeSourceApi?: NonReadonly<KnowledgeSourceApi>,+ options?: RequestInit+): Promise<KnowledgeSourceApi> => {+ return apiMutator<KnowledgeSourceApi>(getBusinessKnowledgeSourcesRefreshCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(knowledgeSourceApi),+ })+}++export const getBusinessKnowledgeSourcesTextRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/sources/${id}/text/`+}++export const businessKnowledgeSourcesTextRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<BusinessKnowledgeSourcesTextRetrieve200> => {+ return apiMutator<BusinessKnowledgeSourcesTextRetrieve200>(+ getBusinessKnowledgeSourcesTextRetrieveUrl(projectId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}diff --git a/products/business_knowledge/frontend/generated/api.zod.ts b/products/business_knowledge/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..8a82257124a4--- /dev/null+++ b/products/business_knowledge/frontend/generated/api.zod.ts@@ -0,0 +1,41 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const businessKnowledgeSourcesCreateBodyNameMax = 255++export const BusinessKnowledgeSourcesCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(businessKnowledgeSourcesCreateBodyNameMax)+ .describe('Short human label for the source. Shown in the settings list and in agent citations.'),+ text: zod+ .string()+ .describe(+ 'Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL\/file support in Stage 2\/3.'+ ),+})++export const businessKnowledgeSourcesPartialUpdateBodyNameMax = 255++export const BusinessKnowledgeSourcesPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(businessKnowledgeSourcesPartialUpdateBodyNameMax)+ .optional()+ .describe('New human label for the source.'),+ text: zod.string().optional().describe('Replacement text. Omit to keep the existing content.'),+ })+ .describe(+ 'PATCH payload for text sources. Both fields optional, at least one\nrequired. `text` triggers a re-chunk; `name` alone does not.'+ )++export const BusinessKnowledgeSourcesRefreshCreateBody = /* @__PURE__ */ zod.looseObject({})diff --git a/pyproject.toml b/pyproject.tomlindex 96136a96440e..7e552abd45a3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -103,6 +103,7 @@ dependencies = ["psycopg[binary]==3.2.4","pyarrow==18.1.0","pydantic~=2.12.0",+ "pypdf==6.10.2","pyod==2.0.7","pyjwt~=2.12.1","pymssql==2.3.5",@@ -111,6 +112,7 @@ dependencies = ["pyroscope-io~=0.8.8","croniter~=6.0.0","python-dateutil~=2.9.0",+ "python-docx==1.2.0","python-snappy~=0.7.3","python3-saml==1.16.0","pytz==2023.3",@@ -136,6 +138,7 @@ dependencies = ["tenacity==9.1.2","tiktoken==0.9.*","tldextract~=5.1",+ "trafilatura==2.0.0","types-cachetools==5.5.0.20240820","css-inline==0.18.0","click~=8.0",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 774ea0192959..d919b3130d14 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7965,6 +7965,22 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * * `single` - Single page+ * `sitemap` - Sitemap+ * `same_origin` - Same origin crawl+ * `github_repo` - GitHub repository+ */+ export type CrawlModeEnum = typeof CrawlModeEnum[keyof typeof CrawlModeEnum];+++ export const CrawlModeEnum = {+ Single: 'single',+ Sitemap: 'sitemap',+ SameOrigin: 'same_origin',+ GithubRepo: 'github_repo',+ } as const;+export interface CreateGroup {/*** @minimum -2147483648@@ -8187,6 +8203,16 @@ export namespace Schemas {uploads: UploadTarget[];}+ export interface CreateTextSource {+ /**+ * Short human label for the source. Shown in the settings list and in agent citations.+ * @maxLength 255+ */+ name: string;+ /** Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL/file support in Stage 2/3. */+ text: string;+ }+/*** * `web` - web* `api` - api@@ -18566,6 +18592,77 @@ export namespace Schemas {'20': '2.0',} as const;+ /**+ * * `text` - Text+ * `url` - URL+ * `file` - File+ */+ export type KnowledgeSourceSourceTypeEnum = typeof KnowledgeSourceSourceTypeEnum[keyof typeof KnowledgeSourceSourceTypeEnum];+++ export const KnowledgeSourceSourceTypeEnum = {+ Text: 'text',+ Url: 'url',+ File: 'file',+ } as const;++ /**+ * * `pending` - Pending+ * `processing` - Processing+ * `ready` - Ready+ * `error` - Error+ */+ export type KnowledgeSourceStatusEnum = typeof KnowledgeSourceStatusEnum[keyof typeof KnowledgeSourceStatusEnum];+++ export const KnowledgeSourceStatusEnum = {+ Pending: 'pending',+ Processing: 'processing',+ Ready: 'ready',+ Error: 'error',+ } as const;++ /**+ * * `success` - Success+ * `not_modified` - Not modified+ * `error` - Error+ */+ export type LastRefreshStatusEnum = typeof LastRefreshStatusEnum[keyof typeof LastRefreshStatusEnum];+++ export const LastRefreshStatusEnum = {+ Success: 'success',+ NotModified: 'not_modified',+ Error: 'error',+ } as const;++ export interface KnowledgeSource {+ readonly id: string;+ readonly team_id: number;+ readonly name: string;+ readonly source_type: KnowledgeSourceSourceTypeEnum;+ readonly status: KnowledgeSourceStatusEnum;+ readonly error_message: string;+ /** Number of documents belonging to this source. */+ readonly document_count: number;+ /** Number of chunks belonging to this source. */+ readonly chunk_count: number;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ readonly source_url: string;+ /** @nullable */+ readonly last_refresh_at: string | null;+ readonly last_refresh_status: LastRefreshStatusEnum;+ readonly last_refresh_error: string;+ readonly crawl_mode: CrawlModeEnum;+ readonly crawl_config: unknown;+ readonly original_filename: string;+ readonly file_content_type: string;+ /** @nullable */+ readonly file_size_bytes: number | null;+ }+export interface LLMModelInfo {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string;@@ -21305,6 +21402,15 @@ export namespace Schemas {results: IntegrationConfig[];}+ export interface PaginatedKnowledgeSourceList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: KnowledgeSource[];+ }+export interface PaginatedLLMPromptListList {count: number;/** @nullable */@@ -29563,6 +29669,20 @@ export namespace Schemas {enable_pr_comments?: boolean | null;}+ /**+ * PATCH payload for text sources. Both fields optional, at least one+ required. `text` triggers a re-chunk; `name` alone does not.+ */+ export interface PatchedUpdateTextSource {+ /**+ * New human label for the source.+ * @maxLength 255+ */+ name?: string;+ /** Replacement text. Omit to keep the existing content. */+ text?: string;+ }+/*** Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is.*/@@ -39955,6 +40075,21 @@ export namespace Schemas {search?: string;};+ export type BusinessKnowledgeSourcesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type BusinessKnowledgeSourcesTextRetrieve200 = {+ text?: string;+ };+export type CohortsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 20863768f453..ed68473ae9bf 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -27,6 +27,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['batch_export:write','batch_import:read','batch_import:write',+ 'business_knowledge:read',+ 'business_knowledge:write','cohort:read','cohort:write','comment:read',diff --git a/tach.toml b/tach.tomlindex bf5c52b9907b..6c1a9c52ac91 100644--- a/tach.toml+++ b/tach.toml@@ -60,6 +60,7 @@ depends_on = ["products.access_control","products.analytics_platform","products.batch_exports",+ "products.business_knowledge","products.conversations","products.customer_analytics","products.dashboards",@@ -580,8 +581,10 @@ layer = "modules"[[interfaces]]expose = [- "backend\\.facade.*",- "backend\\.presentation\\.views.*",+ "backend\\.api.*",+ "backend\\.logic.*",+ "backend\\.constants.*",+ "backend\\.models.*",]from = ["products.business_knowledge",diff --git a/uv.lock b/uv.lockindex a9fbe1b85e9b..19a0d2b18559 100644--- a/uv.lock+++ b/uv.lock@@ -437,6 +437,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3d/9e/1c90a122ea6180e8c72eb7294adc92531b0e08eb3d2324c2ba70d37f4802/azure_storage_blob-12.27.1-py3-none-any.whl", hash = "sha256:65d1e25a4628b7b6acd20ff7902d8da5b4fde8e46e19c8f6d213a3abc3ece272", size = 428954, upload-time = "2025-10-29T12:27:18.072Z" },]+[[package]]+name = "babel"+version = "2.18.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" },+]+[[package]]name = "backoff"version = "2.2.1"@@ -1047,6 +1056,20 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d1/e2/f05240d2c39a1ed228d8328a78b6f44cd695f7ef47beb3e684cf93604f86/contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc", size = 193655, upload-time = "2025-07-26T12:01:37.999Z" },]+[[package]]+name = "courlan"+version = "1.3.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "babel" },+ { name = "tld" },+ { name = "urllib3" },+]+sdist = { url = "https://files.pythonhosted.org/packages/6f/54/6d6ceeff4bed42e7a10d6064d35ee43a810e7b3e8beb4abeae8cff4713ae/courlan-1.3.2.tar.gz", hash = "sha256:0b66f4db3a9c39a6e22dd247c72cfaa57d68ea660e94bb2c84ec7db8712af190", size = 206382, upload-time = "2024-10-29T16:40:20.994Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/8e/ca/6a667ccbe649856dcd3458bab80b016681b274399d6211187c6ab969fc50/courlan-1.3.2-py3-none-any.whl", hash = "sha256:d0dab52cf5b5b1000ee2839fbc2837e93b2514d3cb5bb61ae158a55b7a04c6be", size = 33848, upload-time = "2024-10-29T16:40:18.325Z" },+]+[[package]]name = "coverage"version = "7.12.0"@@ -2986,6 +3009,22 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/07/c6/80c95b1b2b94682a72cbdbfb85b81ae2daffa4291fbfa1b1464502ede10d/hpack-4.1.0-py3-none-any.whl", hash = "sha256:157ac792668d995c657d93111f46b4535ed114f0c9c8d672271bbec7eae1b496", size = 34357, upload-time = "2025-01-22T21:44:56.92Z" },]+[[package]]+name = "htmldate"+version = "1.9.4"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "charset-normalizer" },+ { name = "dateparser" },+ { name = "lxml" },+ { name = "python-dateutil" },+ { name = "urllib3" },+]+sdist = { url = "https://files.pythonhosted.org/packages/9d/10/ead9dabc999f353c3aa5d0dc0835b1e355215a5ecb489a7f4ef2ddad5e33/htmldate-1.9.4.tar.gz", hash = "sha256:1129063e02dd0354b74264de71e950c0c3fcee191178321418ccad2074cc8ed0", size = 44690, upload-time = "2025-11-04T17:46:44.983Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a1/bd/adfcdaaad5805c0c5156aeefd64c1e868c05e9c1cd6fd21751f168cd88c7/htmldate-1.9.4-py3-none-any.whl", hash = "sha256:1b94bcc4e08232a5b692159903acf95548b6a7492dddca5bb123d89d6325921c", size = 31558, upload-time = "2025-11-04T17:46:43.258Z" },+]+[[package]]name = "httpcore"version = "1.0.9"@@ -3397,6 +3436,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/01/0e/b27cdbaccf30b890c40ed1da9fd4a3593a5cf94dae54fb34f8a4b74fcd3f/jsonschema_specifications-2025.4.1-py3-none-any.whl", hash = "sha256:4653bffbd6584f7de83a67e0d620ef16900b390ddc7939d56684d6c81e33f1af", size = 18437, upload-time = "2025-04-23T12:34:05.422Z" },]+[[package]]+name = "justext"+version = "3.0.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "lxml", extra = ["html-clean"] },+]+sdist = { url = "https://files.pythonhosted.org/packages/49/f3/45890c1b314f0d04e19c1c83d534e611513150939a7cf039664d9ab1e649/justext-3.0.2.tar.gz", hash = "sha256:13496a450c44c4cd5b5a75a5efcd9996066d2a189794ea99a49949685a0beb05", size = 828521, upload-time = "2025-02-25T20:21:49.934Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f2/ac/52f4e86d1924a7fc05af3aeb34488570eccc39b4af90530dd6acecdf16b5/justext-3.0.2-py2.py3-none-any.whl", hash = "sha256:62b1c562b15c3c6265e121cc070874243a443bfd53060e869393f09d6b6cc9a7", size = 837940, upload-time = "2025-02-25T20:21:44.179Z" },+]+[[package]]name = "jwcrypto"version = "1.5.7"@@ -3774,6 +3825,23 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ea/7b/93c73c67db235931527301ed3785f849c78991e2e34f3fd9a6663ffda4c5/lxml-6.0.2-cp312-cp312-win_arm64.whl", hash = "sha256:61cb10eeb95570153e0c0e554f58df92ecf5109f75eacad4a95baa709e26c3d6", size = 3672836, upload-time = "2025-09-22T04:01:52.145Z" },]+[package.optional-dependencies]+html-clean = [+ { name = "lxml-html-clean" },+]++[[package]]+name = "lxml-html-clean"+version = "0.4.4"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "lxml" },+]+sdist = { url = "https://files.pythonhosted.org/packages/9a/a4/5c62acfacd69ff4f5db395100f5cfb9b54e7ac8c69a235e4e939fd13f021/lxml_html_clean-0.4.4.tar.gz", hash = "sha256:58f39a9d632711202ed1d6d0b9b47a904e306c85de5761543b90e3e3f736acfb", size = 23899, upload-time = "2026-02-27T09:35:52.911Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d9/76/7ffc1d3005cf7749123bc47cb3ea343cd97b0ac2211bab40f57283577d0e/lxml_html_clean-0.4.4-py3-none-any.whl", hash = "sha256:ce2ef506614ecb85ee1c5fe0a2aa45b06a19514ec7949e9c8f34f06925cfabcb", size = 14565, upload-time = "2026-02-27T09:35:51.86Z" },+]+[[package]]name = "lz4"version = "4.4.4"@@ -5247,8 +5315,10 @@ dependencies = [{ name = "pymssql" },{ name = "pymysql" },{ name = "pyod" },+ { name = "pypdf" },{ name = "pyroscope-io" },{ name = "python-dateutil" },+ { name = "python-docx" },{ name = "python-snappy" },{ name = "python3-saml" },{ name = "pytz" },@@ -5276,6 +5346,7 @@ dependencies = [{ name = "tenacity" },{ name = "tiktoken" },{ name = "tldextract" },+ { name = "trafilatura" },{ name = "types-cachetools" },{ name = "umap-learn" },{ name = "user-agents" },@@ -5508,8 +5579,10 @@ requires-dist = [{ name = "pymssql", specifier = "==2.3.5" },{ name = "pymysql", specifier = "==1.1.1" },{ name = "pyod", specifier = "==2.0.7" },+ { name = "pypdf", specifier = "==6.10.2" },{ name = "pyroscope-io", specifier = "~=0.8.8" },{ name = "python-dateutil", specifier = "~=2.9.0" },+ { name = "python-docx", specifier = "==1.2.0" },{ name = "python-snappy", specifier = "~=0.7.3" },{ name = "python3-saml", specifier = "==1.16.0" },{ name = "pytz", specifier = "==2023.3" },@@ -5537,6 +5610,7 @@ requires-dist = [{ name = "tenacity", specifier = "==9.1.2" },{ name = "tiktoken", specifier = "==0.9.*" },{ name = "tldextract", specifier = "~=5.1" },+ { name = "trafilatura", specifier = "==2.0.0" },{ name = "types-cachetools", specifier = "==5.5.0.20240820" },{ name = "umap-learn", specifier = "~=0.5.0" },{ name = "user-agents", specifier = "~=2.2.0" },@@ -6178,6 +6252,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/05/e7/df2285f3d08fee213f2d041540fa4fc9ca6c2d44cf36d3a035bf2a8d2bcc/pyparsing-3.2.3-py3-none-any.whl", hash = "sha256:a749938e02d6fd0b59b356ca504a24982314bb090c383e3cf201c95ef7e2bfcf", size = 111120, upload-time = "2025-03-25T05:01:24.908Z" },]+[[package]]+name = "pypdf"+version = "6.10.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7b/3f/9f2167401c2e94833ca3b69535bad89e533b5de75fefe4197a2c224baec2/pypdf-6.10.2.tar.gz", hash = "sha256:7d09ce108eff6bf67465d461b6ef352dcb8d84f7a91befc02f904455c6eea11d", size = 5315679, upload-time = "2026-04-15T16:37:36.978Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/0c/d6/1d5c60cc17bbdf37c1552d9c03862fc6d32c5836732a0415b2d637edc2d0/pypdf-6.10.2-py3-none-any.whl", hash = "sha256:aa53be9826655b51c96741e5d7983ca224d898ac0a77896e64636810517624aa", size = 336308, upload-time = "2026-04-15T16:37:34.851Z" },+]+[[package]]name = "pypng"version = "0.20220715.0"@@ -6388,6 +6471,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },]+[[package]]+name = "python-docx"+version = "1.2.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "lxml" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a9/f7/eddfe33871520adab45aaa1a71f0402a2252050c14c7e3009446c8f4701c/python_docx-1.2.0.tar.gz", hash = "sha256:7bc9d7b7d8a69c9c02ca09216118c86552704edc23bac179283f2e38f86220ce", size = 5723256, upload-time = "2025-06-16T20:46:27.921Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d0/00/1e03a4989fa5795da308cd774f05b704ace555a70f9bf9d3be057b680bcf/python_docx-1.2.0-py3-none-any.whl", hash = "sha256:3fd478f3250fbbbfd3b94fe1e985955737c145627498896a8a6bf81f4baf66c7", size = 252987, upload-time = "2025-06-16T20:46:22.506Z" },+]+[[package]]name = "python-dotenv"version = "1.1.0"@@ -7544,6 +7640,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/5b/64/b16003419a1d7728d0d8c0d56a4c24325e7b10a21a9dd1fc0f7115c02f0a/tiktoken-0.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:5a62d7a25225bafed786a524c1b9f0910a1128f4232615bf3f8257a73aaa3b16", size = 894897, upload-time = "2025-02-14T06:02:36.265Z" },]+[[package]]+name = "tld"+version = "0.13.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/5c/5d/76b4383ac4e5b5e254e50c09807b3e13820bed6d6c11cd540264988d6802/tld-0.13.2.tar.gz", hash = "sha256:d983fa92b9d717400742fca844e29d5e18271079c7bcfabf66d01b39b4a14345", size = 467175, upload-time = "2026-03-06T23:50:34.498Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/9e/90/39a85a4b63c84213e78b3c17d22e1bf45328acf8ebb33ef93be30d0a3911/tld-0.13.2-py2.py3-none-any.whl", hash = "sha256:9b8fdbdb880e7ba65b216a4937f2c94c49a7226723783d5838fc958ac76f4e0c", size = 296743, upload-time = "2026-03-06T23:50:32.465Z" },+]+[[package]]name = "tldextract"version = "5.3.1"@@ -7686,6 +7791,24 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540, upload-time = "2024-11-24T20:12:19.698Z" },]+[[package]]+name = "trafilatura"+version = "2.0.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "certifi" },+ { name = "charset-normalizer" },+ { name = "courlan" },+ { name = "htmldate" },+ { name = "justext" },+ { name = "lxml" },+ { name = "urllib3" },+]+sdist = { url = "https://files.pythonhosted.org/packages/06/25/e3ebeefdebfdfae8c4a4396f5a6ea51fc6fa0831d63ce338e5090a8003dc/trafilatura-2.0.0.tar.gz", hash = "sha256:ceb7094a6ecc97e72fea73c7dba36714c5c5b577b6470e4520dca893706d6247", size = 253404, upload-time = "2024-12-03T15:23:24.16Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/8a/b6/097367f180b6383a3581ca1b86fcae284e52075fa941d1232df35293363c/trafilatura-2.0.0-py3-none-any.whl", hash = "sha256:77eb5d1e993747f6f20938e1de2d840020719735690c840b9a1024803a4cd51d", size = 132557, upload-time = "2024-12-03T15:23:21.41Z" },+]+[[package]]name = "traitlets"version = "5.14.3"