: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): support generated knowledge documents (#98249)
Alex V59fac4bd73ae
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.pyindex 1abb2ecc13b4..ef69e1b6f130 100644--- a/products/business_knowledge/backend/api/serializers.py+++ b/products/business_knowledge/backend/api/serializers.py@@ -112,6 +112,7 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):"team_id","name","source_type",+ "is_generated","status","error_message","document_count",@@ -489,7 +490,7 @@ class KnowledgeSearchResultSerializer(serializers.Serializer):)source_type = serializers.CharField(read_only=True,- help_text="Source type (text, url, or file).",+ help_text="Source type: text, URL, or file.",)document_title = serializers.CharField(read_only=True,diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.pyindex c9822c1bcadd..a25e92328b40 100644--- a/products/business_knowledge/backend/api/views.py+++ b/products/business_knowledge/backend/api/views.py@@ -55,6 +55,11 @@ from .serializers import (logger = structlog.get_logger(__name__)+def _ensure_user_managed_source(source: KnowledgeSource) -> None:+ if source.is_generated:+ raise exceptions.PermissionDenied(detail="Generated sources are read-only.")++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@@ -90,6 +95,8 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def create(self, request: Request, **kwargs) -> Response:source_type = request.data.get("source_type", SourceType.TEXT.value)+ if str(request.data.get("is_generated", "")).lower() in {"1", "true"}:+ raise exceptions.ValidationError({"is_generated": "Generated sources are created automatically."})if source_type == SourceType.FILE.value:return self._create_file_source(request)if source_type == SourceType.URL.value:@@ -240,6 +247,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):except KnowledgeSource.DoesNotExist:raise exceptions.NotFound()+ _ensure_user_managed_source(source)if source.source_type == SourceType.URL.value:return self._update_url_source(source, request)if source.source_type == SourceType.FILE.value:@@ -264,6 +272,8 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)except logic.QuotaExceededError:raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ except logic.GeneratedSourceReadOnlyError:+ raise exceptions.PermissionDenied(detail="Generated sources are read-only.")if updated is None:raise exceptions.NotFound()return Response(KnowledgeSourceSerializer(instance=updated).data)@@ -283,6 +293,8 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise exceptions.ValidationError({"text": "Text exceeds the maximum allowed size."})except logic.QuotaExceededError:raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ except logic.GeneratedSourceReadOnlyError:+ raise exceptions.PermissionDenied(detail="Generated sources are read-only.")if updated is None:raise exceptions.NotFound()return Response(KnowledgeSourceSerializer(instance=updated).data)@@ -309,6 +321,8 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):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.")+ except logic.GeneratedSourceReadOnlyError:+ raise exceptions.PermissionDenied(detail="Generated sources are read-only.")if updated is None:raise exceptions.NotFound()return Response(KnowledgeSourceSerializer(instance=updated).data)@@ -320,7 +334,10 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):source_id = UUID(pk)except (ValueError, DjangoValidationError):raise exceptions.NotFound()- content = logic.get_source_text_for_team(source_id, self.team_id)+ try:+ content = logic.get_source_text_for_team(source_id, self.team_id)+ except logic.GeneratedSourceReadOnlyError:+ raise exceptions.PermissionDenied(detail="Generated sources must be read through document windows.")if content is None:raise exceptions.NotFound()return Response({"text": content})@@ -342,6 +359,8 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise exceptions.ValidationError({"url": "Only URL sources can be refreshed."})except logic.QuotaExceededError:raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")+ except logic.GeneratedSourceReadOnlyError:+ raise exceptions.PermissionDenied(detail="Generated sources are read-only.")self._start_background_refresh(source)fresh = logic.get_for_team(source.id, self.team_id) or sourcereturn Response(KnowledgeSourceSerializer(instance=fresh).data)@@ -370,7 +389,11 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):source_id = UUID(pk)except (ValueError, DjangoValidationError):raise exceptions.NotFound()- if not logic.delete_source(source_id, self.team_id):+ try:+ deleted = logic.delete_source(source_id, self.team_id)+ except logic.GeneratedSourceReadOnlyError:+ raise exceptions.PermissionDenied(detail="Generated sources are read-only.")+ if not deleted:raise exceptions.NotFound()return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex e385d34a33be..6fdd79e36077 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -20,17 +20,19 @@ from django.db import (connection as db_connection,transaction,)-from django.db.models import Count, Exists, F, Max, OuterRef, Q, QuerySet-from django.db.models.functions import Substr+from django.db.models import Count, Exists, F, IntegerField, Max, OuterRef, Q, QuerySet, Subquery, Value+from django.db.models.functions import Coalesce, Substrfrom django.utils import timezoneimport structlogfrom langchain_core.messages import HumanMessage, SystemMessagefrom posthog.api.embedding_worker import generate_embedding+from posthog.dataclasses import frozenfrom posthog.helpers.full_text_search import process_queryfrom posthog.models.organization import OrganizationMembership-from posthog.models.scoping import with_team_scope+from posthog.models.scoping import team_scope, with_team_scope+from posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.ph_client import feature_enabled_or_false@@ -91,6 +93,12 @@ from .url_fetch import sha256_oflogger = structlog.get_logger(__name__)+GENERATED_SOURCE_NAME = "Learned from support"+GENERATED_KNOWLEDGE_ORIGIN = "support_ticket"+MAX_ANALYSIS_VERSION_LENGTH = 128+MAX_PROVIDER_LENGTH = 64+MAX_GENERATED_DOCUMENT_TITLE_LENGTH = 512+# Deterministic namespace for chunk uuid5. Rolling this breaks id stability# across data — so don't. Generated once via uuid.uuid4() and frozen._CHUNK_NAMESPACE = UUID("4b7b0b50-5e2f-4a9f-8a8b-8b8d5f6f4a3e")@@ -116,6 +124,44 @@ class SourceBusyError(Exception):"""A refresh is already running for this source."""+class GeneratedSourceReadOnlyError(Exception):+ """A system-managed source cannot be changed through user mutation paths."""+++class InvalidGeneratedKnowledgeDocument(ValueError):+ """The generated document violates the internal write contract."""+++@frozen+class CreateGeneratedKnowledgeDocument:+ team_id: int+ # The product that supplied the evidence, e.g. "conversations". Part of the document identity.+ provider: str+ ticket_id: UUID+ ticket_number: int+ # The environment team the ticket lives in; the document row itself is stored on the canonical team.+ source_team_id: int+ resolution_comment_id: UUID+ analysis_version: str+ title: str+ content: str+++@frozen+class GeneratedKnowledgeDocument:+ id: UUID+ source_id: UUID+ created: bool+++@frozen+class _ValidatedGeneratedDocumentInput:+ provider: str+ analysis_version: str+ title: str+ content: str++class EmptyContentError(Exception):"""Remote returned nothing usable after parsing."""@@ -223,7 +269,12 @@ def _bulk_create_chunks(def _count_sources(team_id: int) -> int:- return KnowledgeSource.objects.filter(team_id=team_id).count()+ return KnowledgeSource.objects.filter(team_id=team_id, is_generated=False).count()+++def _ensure_user_managed_source(source: KnowledgeSource) -> None:+ if source.is_generated:+ raise GeneratedSourceReadOnlyError("Generated sources are managed by PostHog.")# Advisory-lock namespace so we don't collide with other lock users.@@ -299,6 +350,34 @@ def check_text_source_quota(team_id: int, text: str) -> None:# --- Queries -----------------------------------------------------------------+def _document_count_subquery() -> Coalesce:+ count = (+ KnowledgeDocument.objects.filter(+ team_id=OuterRef("team_id"),+ source_id=OuterRef("pk"),+ )+ .order_by()+ .values("source_id")+ .annotate(total=Count("id"))+ .values("total")[:1]+ )+ return Coalesce(Subquery(count, output_field=IntegerField()), Value(0))+++def _chunk_count_subquery() -> Coalesce:+ count = (+ KnowledgeChunk.objects.filter(+ team_id=OuterRef("team_id"),+ source_id=OuterRef("pk"),+ )+ .order_by()+ .values("source_id")+ .annotate(total=Count("id"))+ .values("total")[:1]+ )+ return Coalesce(Subquery(count, output_field=IntegerField()), Value(0))++def _unsafe_documents_subquery() -> Exists:return Exists(KnowledgeDocument.objects.filter(@@ -352,8 +431,8 @@ def list_for_team(team_id: int) -> list[KnowledgeSource]:return list(KnowledgeSource.objects.filter(team_id=team_id).annotate(- _document_count=Count("documents", distinct=True),- _chunk_count=Count("chunks", distinct=True),+ _document_count=_document_count_subquery(),+ _chunk_count=_chunk_count_subquery(),_has_unsafe_documents=_unsafe_documents_subquery(),_has_pending_embeddings=_pending_embedding_documents_subquery(),_ai_processing_approved=F("team__organization__is_ai_data_processing_approved"),@@ -366,8 +445,8 @@ def list_for_team(team_id: int) -> list[KnowledgeSource]: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),+ _document_count=_document_count_subquery(),+ _chunk_count=_chunk_count_subquery(),_has_unsafe_documents=_unsafe_documents_subquery(),_has_pending_embeddings=_pending_embedding_documents_subquery(),_ai_processing_approved=F("team__organization__is_ai_data_processing_approved"),@@ -379,18 +458,215 @@ def get_for_team(source_id: UUID, team_id: int) -> KnowledgeSource | 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. 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.+ Return source text for the edit modal.++ Generated sources can contain many documents, so callers must use the+ bounded document-window API to inspect them."""- if not KnowledgeSource.objects.filter(id=source_id, team_id=team_id).exists():+ try:+ source = KnowledgeSource.objects.only("is_generated").get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:return None+ _ensure_user_managed_source(source)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)+def _validate_generated_document_input(+ document_input: CreateGeneratedKnowledgeDocument,+) -> _ValidatedGeneratedDocumentInput:+ provider = document_input.provider.strip()+ analysis_version = document_input.analysis_version.strip()+ title = document_input.title.strip()+ content = document_input.content++ if not provider or len(provider) > MAX_PROVIDER_LENGTH:+ raise InvalidGeneratedKnowledgeDocument("provider is invalid")+ if re.fullmatch(r"[a-z0-9_-]+", provider) is None:+ raise InvalidGeneratedKnowledgeDocument("provider is invalid")+ if document_input.ticket_number <= 0:+ raise InvalidGeneratedKnowledgeDocument("ticket_number is invalid")+ if document_input.source_team_id <= 0:+ raise InvalidGeneratedKnowledgeDocument("source_team_id is invalid")+ if not analysis_version or len(analysis_version) > MAX_ANALYSIS_VERSION_LENGTH:+ raise InvalidGeneratedKnowledgeDocument("analysis_version is invalid")+ if re.fullmatch(r"[A-Za-z0-9._-]+", analysis_version) is None:+ raise InvalidGeneratedKnowledgeDocument("analysis_version is invalid")+ if not title or len(title) > MAX_GENERATED_DOCUMENT_TITLE_LENGTH:+ raise InvalidGeneratedKnowledgeDocument("title is invalid")+ if not content.strip():+ raise InvalidGeneratedKnowledgeDocument("content is empty")+ if len(content.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:+ raise InvalidGeneratedKnowledgeDocument("content is too large")++ combined_content = f"{title}\n{content}".lower()+ if any(+ identifier in combined_content+ for provenance_id in (document_input.ticket_id, document_input.resolution_comment_id)+ for identifier in (str(provenance_id).lower(), provenance_id.hex.lower())+ ):+ raise InvalidGeneratedKnowledgeDocument("provenance identifiers cannot appear in generated content")++ return _ValidatedGeneratedDocumentInput(+ provider=provider,+ analysis_version=analysis_version,+ title=title,+ content=content,+ )+++def _generated_source_id(team_id: int) -> UUID:+ return uuid.uuid5(uuid.NAMESPACE_DNS, f"team-{team_id}.generated.business-knowledge.posthog")+++def _generated_document_stable_id(+ document_input: CreateGeneratedKnowledgeDocument,+ validated_input: _ValidatedGeneratedDocumentInput,+) -> str:+ # stable_id is readable by anyone with business_knowledge:read (system table), so it must not+ # carry the raw ticket or comment ids; those need ticket:read and live in metadata only.+ identity = (+ f"{GENERATED_KNOWLEDGE_ORIGIN}:{validated_input.provider}:"+ f"{document_input.ticket_id}:{document_input.resolution_comment_id}:{validated_input.analysis_version}"+ )+ return f"{GENERATED_KNOWLEDGE_ORIGIN}:{sha256_of(identity)}"+++def _validate_existing_generated_document(+ document: KnowledgeDocument,+ *,+ expected_id: UUID,+ source: KnowledgeSource,+ stable_id: str,+ team_id: int,+) -> None:+ if (+ document.id != expected_id+ or document.team_id != team_id+ or document.source_id != source.id+ or document.stable_id != stable_id+ ):+ raise InvalidGeneratedKnowledgeDocument("generated document identity is already in use")+++def set_generated_knowledge_source_ready(team_id: int, *, ready: bool) -> bool:+ canonical_team_id = resolve_effective_team_id(team_id)+ with team_scope(canonical_team_id, canonical=True):+ try:+ source = KnowledgeSource.objects.get(+ id=_generated_source_id(canonical_team_id),+ team_id=canonical_team_id,+ is_generated=True,+ )+ except KnowledgeSource.DoesNotExist:+ return False+ source.status = SourceStatus.READY if ready else SourceStatus.ERROR+ source.error_message = "" if ready else "Generated source is disabled."+ source.save(update_fields=["status", "error_message", "updated_at"])+ return True+++def create_generated_knowledge_document(+ document_input: CreateGeneratedKnowledgeDocument,+) -> GeneratedKnowledgeDocument:+ canonical_team_id = resolve_effective_team_id(document_input.team_id)+ with team_scope(canonical_team_id, canonical=True):+ document, created = _create_generated_knowledge_document(+ document_input,+ team_id=canonical_team_id,+ )+ return GeneratedKnowledgeDocument(+ id=document.id,+ source_id=document.source_id,+ created=created,+ )+++def _create_generated_knowledge_document(+ document_input: CreateGeneratedKnowledgeDocument,+ *,+ team_id: int,+) -> tuple[KnowledgeDocument, bool]:+ validated_input = _validate_generated_document_input(document_input)+ _acquire_source_quota_lock(team_id)++ source, _ = KnowledgeSource.objects.get_or_create(+ id=_generated_source_id(team_id),+ team_id=team_id,+ defaults={+ "created_by_id": None,+ "name": GENERATED_SOURCE_NAME,+ "source_type": SourceType.TEXT,+ "is_generated": True,+ "status": SourceStatus.READY,+ },+ )+ if not source.is_generated or source.source_type != SourceType.TEXT:+ raise InvalidGeneratedKnowledgeDocument("generated source identity is already in use")++ stable_id = _generated_document_stable_id(document_input, validated_input)+ document_id = uuid.uuid5(source.id, stable_id)+ existing = KnowledgeDocument.objects.filter(+ team_id=team_id,+ source=source,+ stable_id=stable_id,+ ).first()+ if existing is not None:+ _validate_existing_generated_document(+ existing,+ expected_id=document_id,+ source=source,+ stable_id=stable_id,+ team_id=team_id,+ )+ return existing, False++ existing = KnowledgeDocument.objects.filter(id=document_id, team_id=team_id).first()+ if existing is not None:+ _validate_existing_generated_document(+ existing,+ expected_id=document_id,+ source=source,+ stable_id=stable_id,+ team_id=team_id,+ )+ return existing, False++ document, created = KnowledgeDocument.objects.get_or_create(+ id=document_id,+ team_id=team_id,+ source=source,+ stable_id=stable_id,+ defaults={+ "title": validated_input.title,+ "content": validated_input.content,+ "metadata": {+ "source_type": SourceType.TEXT,+ "origin": GENERATED_KNOWLEDGE_ORIGIN,+ "provider": validated_input.provider,+ "ticket_id": str(document_input.ticket_id),+ "ticket_number": document_input.ticket_number,+ "source_team_id": document_input.source_team_id,+ "resolution_comment_id": str(document_input.resolution_comment_id),+ "analysis_version": validated_input.analysis_version,+ },+ "content_hash": sha256_of(validated_input.content),+ "safety_verdict": SafetyVerdict.UNKNOWN,+ },+ )+ if not created:+ return document, False++ chunks = chunk_text(validated_input.content)+ if _count_chunks(team_id) + len(chunks) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError("Generated content exceeds the remaining team chunk budget.")++ _bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)+ return document, True++# --- Mutations ---------------------------------------------------------------@@ -488,6 +764,7 @@ def update_text_source(except KnowledgeSource.DoesNotExist:return None+ _ensure_user_managed_source(source)if always_include is not None:source.always_include = always_include@@ -567,6 +844,7 @@ def update_url_source(source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)except KnowledgeSource.DoesNotExist:return None+ _ensure_user_managed_source(source)if source.source_type != SourceType.URL:raise InvalidUrlError("Can only update URL sources with this endpoint.")@@ -632,6 +910,7 @@ def delete_source(source_id: UUID, team_id: int) -> bool:source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)except KnowledgeSource.DoesNotExist:return False+ _ensure_user_managed_source(source)source.delete()return True@@ -1022,12 +1301,19 @@ def claim_refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSource:invariant. Raises `SourceBusyError` / `InvalidUrlError` synchronously sothe API can return 409 / 400 before kicking off the workflow."""+ try:+ existing_source = KnowledgeSource.objects.only("is_generated").get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ raise+ _ensure_user_managed_source(existing_source)+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:raise+ _ensure_user_managed_source(source)if source.source_type != SourceType.URL or not source.source_url:raise InvalidUrlError("Only URL sources can be refreshed.")if source.status == SourceStatus.PROCESSING:@@ -1050,6 +1336,7 @@ def execute_refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSourceexcept KnowledgeSource.DoesNotExist:return None+ _ensure_user_managed_source(source)try:if source.crawl_mode and source.crawl_mode != CrawlMode.SINGLE:return _refresh_crawl_source(source=source, team_id=team_id)@@ -1570,8 +1857,8 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge@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()+ """True when the team has at least one searchable chunk."""+ return _safe_chunks_qs(team_id).exists()@with_team_scope(canonical=True)diff --git a/products/business_knowledge/backend/migrations/0016_add_generated_source_marker.py b/products/business_knowledge/backend/migrations/0016_add_generated_source_marker.pynew file mode 100644index 000000000000..7ba26c635aea--- /dev/null+++ b/products/business_knowledge/backend/migrations/0016_add_generated_source_marker.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-10 10:50++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("business_knowledge", "0015_bk_gap_team_status_topic_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="knowledgesource",+ name="is_generated",+ field=models.BooleanField(+ db_default=False,+ default=False,+ help_text="Whether PostHog manages this source with knowledge learned from resolved support tickets.",+ ),+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtindex 17ecd997e4cb..61c16adaddfa 100644--- a/products/business_knowledge/backend/migrations/max_migration.txt+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_bk_gap_team_status_topic_index+0016_add_generated_source_markerdiff --git a/products/business_knowledge/backend/models/knowledge_source.py b/products/business_knowledge/backend/models/knowledge_source.pyindex 848cbd4a3de7..f8f6750480c8 100644--- a/products/business_knowledge/backend/models/knowledge_source.py+++ b/products/business_knowledge/backend/models/knowledge_source.py@@ -9,8 +9,8 @@ from .constants import CrawlMode, RefreshInterval, RefreshStatus, SourceStatus,class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):"""- A user-created collection of business knowledge (e.g. "Product docs",- "Support macros"). One source groups one or more documents.+ A collection of business knowledge (e.g. "Product docs", "Support macros").+ One source groups one or more documents."""activity_logging_on_delete = True@@ -18,6 +18,11 @@ class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields,team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="business_knowledge_sources")name = models.CharField(max_length=255)source_type = models.CharField(max_length=16, choices=SourceType.choices)+ is_generated = models.BooleanField(+ default=False,+ db_default=False,+ help_text="Whether PostHog manages this source with knowledge learned from resolved support tickets.",+ )status = models.CharField(max_length=16, choices=SourceStatus.choices, default=SourceStatus.PENDING)# Human-facing failure reason. Empty when status != ERROR.error_message = models.TextField(blank=True, default="")diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.pyindex 62b0fc5feef3..bb43bffb306a 100644--- a/products/business_knowledge/backend/tests/test_api.py+++ b/products/business_knowledge/backend/tests/test_api.py@@ -1,3 +1,5 @@+from uuid import UUID+from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patch@@ -20,6 +22,22 @@ class TestKnowledgeSourceAPI(APIBaseTest):super().setUp()self.url = f"/api/projects/{self.team.id}/business_knowledge/sources/"+ def _create_generated_source(self) -> str:+ result = logic.create_generated_knowledge_document(+ logic.CreateGeneratedKnowledgeDocument(+ team_id=self.team.id,+ provider="conversations",+ ticket_id=UUID("10000000-0000-0000-0000-000000000001"),+ ticket_number=42,+ source_team_id=self.team.id,+ resolution_comment_id=UUID("20000000-0000-0000-0000-000000000002"),+ analysis_version="post_resolution_v1",+ title="Refund policy",+ content="Refunds are available within 30 days.",+ )+ )+ return str(result.source_id)+def test_create_text_source_and_chunks(self, _ff) -> None:response = self.client.post(self.url,@@ -139,6 +157,61 @@ class TestKnowledgeSourceAPI(APIBaseTest):assert patch_resp.status_code == status.HTTP_200_OK, patch_resp.contentassert patch_resp.json()["always_include"] is True+ def test_generated_source_is_marked_in_list(self, _ff) -> None:+ source_id = self._create_generated_source()++ response = self.client.get(self.url)++ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["id"] == source_id+ assert results[0]["source_type"] == "text"+ assert results[0]["is_generated"] is True++ @parameterized.expand(+ [+ ("update", "patch", "", {"name": "Changed"}),+ ("refresh", "post", "refresh/", None),+ ("delete", "delete", "", None),+ ("raw_text", "get", "text/", None),+ ]+ )+ def test_generated_source_is_read_only(self, _ff, _name, method, suffix, body) -> None:+ source_id = self._create_generated_source()++ request_method = getattr(self.client, method)+ response = (+ request_method(f"{self.url}{source_id}/{suffix}", body, format="json")+ if body is not None+ else request_method(f"{self.url}{source_id}/{suffix}")+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert KnowledgeSource.objects.unscoped().filter(id=source_id).exists()++ def test_generated_refresh_is_rejected_before_processing_source_checks(self, _ff) -> None:+ source_id = self._create_generated_source()+ KnowledgeSource.objects.unscoped().create(+ team=self.team,+ name="Refreshing URL",+ source_type="url",+ status="processing",+ )++ response = self.client.post(f"{self.url}{source_id}/refresh/")++ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_generated_source_cannot_be_created_through_api(self, _ff) -> None:+ response = self.client.post(+ self.url,+ {"is_generated": True, "name": "Spoofed", "text": "Content"},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+@patch("posthoganalytics.feature_enabled", return_value=True)class TestEmbeddingStatusAPI(APIBaseTest):diff --git a/products/business_knowledge/backend/tests/test_cross_team_isolation.py b/products/business_knowledge/backend/tests/test_cross_team_isolation.pyindex 5c9810fca418..d49120f6416d 100644--- a/products/business_knowledge/backend/tests/test_cross_team_isolation.py+++ b/products/business_knowledge/backend/tests/test_cross_team_isolation.py@@ -57,3 +57,8 @@ class TestCrossTeamIsolation(BaseTest):assert logic.has_ready_sources(self.team.id) is Trueassert logic.has_ready_sources(self.other_team.id) is False++ def test_ready_source_without_safety_cleared_content_is_not_searchable(self) -> None:+ KnowledgeDocument.objects.unscoped().filter(team=self.team).update(safety_verdict=SafetyVerdict.UNKNOWN)++ assert logic.has_ready_sources(self.team.id) is Falsediff --git a/products/business_knowledge/backend/tests/test_generated_documents.py b/products/business_knowledge/backend/tests/test_generated_documents.pynew file mode 100644index 000000000000..c4628a9c46da--- /dev/null+++ b/products/business_knowledge/backend/tests/test_generated_documents.py@@ -0,0 +1,292 @@+import uuid++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.models.team import Team++from products.business_knowledge.backend import logic+from products.business_knowledge.backend.models import (+ KnowledgeChunk,+ KnowledgeDocument,+ KnowledgeSource,+ SafetyVerdict,+ SourceStatus,+ SourceType,+)+++class TestGeneratedKnowledgeDocuments(BaseTest):+ def _input(+ self,+ *,+ team_id: int | None = None,+ provider: str = "conversations",+ ticket_number: int = 42,+ source_team_id: int | None = None,+ resolution_comment_id: uuid.UUID | None = None,+ analysis_version: str = "post_resolution_v1",+ title: str = "Refund policy",+ content: str = "Refunds are available within 30 days.",+ ) -> logic.CreateGeneratedKnowledgeDocument:+ return logic.CreateGeneratedKnowledgeDocument(+ team_id=team_id or self.team.id,+ provider=provider,+ ticket_id=uuid.UUID("10000000-0000-0000-0000-000000000001"),+ ticket_number=ticket_number,+ source_team_id=source_team_id if source_team_id is not None else (team_id or self.team.id),+ resolution_comment_id=resolution_comment_id or uuid.UUID("20000000-0000-0000-0000-000000000002"),+ analysis_version=analysis_version,+ title=title,+ content=content,+ )++ def test_creates_generated_source_document_and_chunks(self) -> None:+ input = self._input()++ result = logic.create_generated_knowledge_document(input)++ source = KnowledgeSource.objects.unscoped().get(id=result.source_id)+ document = KnowledgeDocument.objects.unscoped().get(id=result.id)+ chunks = list(KnowledgeChunk.objects.unscoped().filter(document=document))+ provenance = {+ "origin": logic.GENERATED_KNOWLEDGE_ORIGIN,+ "provider": input.provider,+ "ticket_id": str(input.ticket_id),+ "ticket_number": input.ticket_number,+ "source_team_id": input.source_team_id,+ "resolution_comment_id": str(input.resolution_comment_id),+ "analysis_version": input.analysis_version,+ }++ assert result.created is True+ assert source.team_id == self.team.id+ assert source.name == logic.GENERATED_SOURCE_NAME+ assert source.source_type == SourceType.TEXT+ assert source.is_generated is True+ assert source.status == SourceStatus.READY+ assert source.created_by_id is None+ assert document.safety_verdict == SafetyVerdict.UNKNOWN+ assert document.metadata == {"source_type": SourceType.TEXT, **provenance}+ assert chunks+ assert logic.search_knowledge(self.team.id, "refunds") == []++ searchable_text = "\n".join(+ [source.name, document.stable_id, document.title, document.content, *(chunk.content for chunk in chunks)]+ )+ assert str(input.ticket_id) not in searchable_text+ assert str(input.resolution_comment_id) not in searchable_text+ assert input.analysis_version not in searchable_text++ def test_retry_returns_existing_document_without_rewriting_it(self) -> None:+ first = logic.create_generated_knowledge_document(self._input())++ retry = logic.create_generated_knowledge_document(+ self._input(title="Changed title", content="Changed content that must not replace the original.")+ )++ document = KnowledgeDocument.objects.unscoped().get(id=first.id)+ assert retry == logic.GeneratedKnowledgeDocument(+ id=first.id,+ source_id=first.source_id,+ created=False,+ )+ assert document.title == "Refund policy"+ assert document.content == "Refunds are available within 30 days."+ assert KnowledgeSource.objects.unscoped().filter(team=self.team, is_generated=True).count() == 1+ assert KnowledgeDocument.objects.unscoped().filter(source_id=first.source_id).count() == 1++ @parameterized.expand(+ [+ ("analysis_version", "conversations", "post_resolution_v2"),+ ("provider", "other_provider", "post_resolution_v1"),+ ]+ )+ def test_new_identity_reuses_team_source(self, _name: str, provider: str, analysis_version: str) -> None:+ first = logic.create_generated_knowledge_document(self._input())+ second = logic.create_generated_knowledge_document(+ self._input(provider=provider, analysis_version=analysis_version)+ )++ assert first.source_id == second.source_id+ assert first.id != second.id+ assert KnowledgeSource.objects.unscoped().filter(team=self.team, is_generated=True).count() == 1+ assert KnowledgeDocument.objects.unscoped().filter(source_id=first.source_id).count() == 2++ def test_same_provenance_is_isolated_between_teams(self) -> None:+ other_team = Team.objects.create_with_data(+ organization=self.organization,+ initiating_user=self.user,+ name="Other",+ )++ mine = logic.create_generated_knowledge_document(self._input())+ theirs = logic.create_generated_knowledge_document(self._input(team_id=other_team.id))++ assert mine.source_id != theirs.source_id+ assert mine.id != theirs.id+ assert KnowledgeDocument.objects.unscoped().get(id=mine.id).team_id == self.team.id+ assert KnowledgeDocument.objects.unscoped().get(id=theirs.id).team_id == other_team.id++ def test_child_team_writes_to_canonical_team(self) -> None:+ child_team = Team.objects.create(+ organization=self.organization,+ parent_team=self.team,+ project=self.team.project,+ name="Child environment",+ )++ result = logic.create_generated_knowledge_document(self._input(team_id=child_team.id))++ document = KnowledgeDocument.objects.unscoped().get(id=result.id)+ assert KnowledgeSource.objects.unscoped().get(id=result.source_id).team_id == self.team.id+ assert document.team_id == self.team.id+ assert document.metadata["source_team_id"] == child_team.id++ def test_disabling_generated_source_removes_it_from_search_without_deleting_data(self) -> None:+ result = logic.create_generated_knowledge_document(self._input())+ document = KnowledgeDocument.objects.unscoped().get(id=result.id)+ logic.set_document_safety(+ team_id=self.team.id,+ document_id=document.id,+ verdict=SafetyVerdict.SAFE,+ content_hash=document.content_hash,+ )+ assert logic.search_knowledge(self.team.id, "refunds")++ assert logic.set_generated_knowledge_source_ready(self.team.id, ready=False) is True++ assert logic.search_knowledge(self.team.id, "refunds") == []+ assert KnowledgeDocument.objects.unscoped().filter(id=result.id).exists()+ assert KnowledgeChunk.objects.unscoped().filter(document_id=result.id).exists()++ def test_disabling_generated_source_remains_effective_after_later_publish(self) -> None:+ first = logic.create_generated_knowledge_document(self._input())+ assert logic.set_generated_knowledge_source_ready(self.team.id, ready=False) is True++ second = logic.create_generated_knowledge_document(self._input(analysis_version="post_resolution_v2"))++ source = KnowledgeSource.objects.unscoped().get(id=first.source_id)+ assert second.source_id == first.source_id+ assert source.status == SourceStatus.ERROR++ def test_logic_mutations_reject_generated_source(self) -> None:+ result = logic.create_generated_knowledge_document(self._input())++ with self.assertRaises(logic.GeneratedSourceReadOnlyError):+ logic.update_text_source(+ source_id=result.source_id,+ team_id=self.team.id,+ name="Changed",+ text="Changed content",+ )+ with self.assertRaises(logic.GeneratedSourceReadOnlyError):+ logic.delete_source(result.source_id, self.team.id)+ with self.assertRaises(logic.GeneratedSourceReadOnlyError):+ logic.claim_refresh_source(source_id=result.source_id, team_id=self.team.id)++ def test_generated_source_does_not_consume_user_source_quota(self) -> None:+ logic.create_generated_knowledge_document(self._input())++ with patch.object(logic, "MAX_SOURCES_PER_TEAM", 1):+ logic.create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="User source",+ text="User-authored content",+ )+ with self.assertRaises(logic.QuotaExceededError):+ logic.create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Second user source",+ text="More user-authored content",+ )++ def test_generated_source_can_be_created_at_user_source_quota(self) -> None:+ with patch.object(logic, "MAX_SOURCES_PER_TEAM", 1):+ logic.create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="User source",+ text="User-authored content",+ )++ result = logic.create_generated_knowledge_document(self._input())++ assert KnowledgeSource.objects.unscoped().get(id=result.source_id).is_generated is True++ def test_chunk_quota_failure_rolls_back_new_source(self) -> None:+ with (+ patch.object(logic, "MAX_CHUNKS_PER_TEAM", 0),+ self.assertRaises(logic.QuotaExceededError),+ ):+ logic.create_generated_knowledge_document(self._input())++ assert not KnowledgeSource.objects.unscoped().filter(team=self.team, is_generated=True).exists()++ @parameterized.expand(+ [+ (+ "title",+ "x" * (logic.MAX_GENERATED_DOCUMENT_TITLE_LENGTH + 1),+ "Valid content",+ ),+ (+ "content",+ "Valid title",+ "x" * (logic.MAX_TEXT_SIZE_BYTES + 1),+ ),+ ]+ )+ def test_rejects_unbounded_document_fields(self, _name: str, title: str, content: str) -> None:+ with self.assertRaises(logic.InvalidGeneratedKnowledgeDocument):+ logic.create_generated_knowledge_document(self._input(title=title, content=content))++ @parameterized.expand(+ [+ ("empty", ""),+ ("too_long", "x" * (logic.MAX_ANALYSIS_VERSION_LENGTH + 1)),+ ("invalid_character", "post resolution v1"),+ ]+ )+ def test_rejects_invalid_analysis_version(self, _name: str, analysis_version: str) -> None:+ with self.assertRaises(logic.InvalidGeneratedKnowledgeDocument):+ logic.create_generated_knowledge_document(self._input(analysis_version=analysis_version))++ @parameterized.expand(+ [+ ("empty_provider", "", 42, 1),+ ("uppercase_provider", "Conversations", 42, 1),+ ("too_long_provider", "x" * (logic.MAX_PROVIDER_LENGTH + 1), 42, 1),+ ("zero_ticket_number", "conversations", 0, 1),+ ("zero_source_team", "conversations", 42, 0),+ ]+ )+ def test_rejects_invalid_provenance(+ self, _name: str, provider: str, ticket_number: int, source_team_id: int+ ) -> None:+ with self.assertRaises(logic.InvalidGeneratedKnowledgeDocument):+ logic.create_generated_knowledge_document(+ self._input(provider=provider, ticket_number=ticket_number, source_team_id=source_team_id)+ )++ @parameterized.expand(+ [+ ("ticket_in_title", "10000000-0000-0000-0000-000000000001", "Valid content"),+ ("ticket_in_content", "Valid title", "See ticket 10000000-0000-0000-0000-000000000001."),+ ("ticket_hex_in_content", "Valid title", "See ticket 10000000000000000000000000000001."),+ ("comment_in_title", "20000000-0000-0000-0000-000000000002", "Valid content"),+ ("comment_in_content", "Valid title", "See comment 20000000-0000-0000-0000-000000000002."),+ ]+ )+ def test_rejects_provenance_identifiers_in_searchable_content(+ self,+ _name: str,+ title: str,+ content: str,+ ) -> None:+ with self.assertRaises(logic.InvalidGeneratedKnowledgeDocument):+ logic.create_generated_knowledge_document(self._input(title=title, content=content))diff --git a/products/business_knowledge/frontend/components/StatusTag.tsx b/products/business_knowledge/frontend/components/StatusTag.tsxindex 7d36fb010dfd..d7db87ae7ed0 100644--- a/products/business_knowledge/frontend/components/StatusTag.tsx+++ b/products/business_knowledge/frontend/components/StatusTag.tsx@@ -3,6 +3,13 @@ import { LemonTag, Tooltip } from '@posthog/lemon-ui'import { KnowledgeSource } from '../scenes/businessKnowledgeLogic'export function StatusTag({ source }: { source: KnowledgeSource }): JSX.Element {+ if (source.is_generated && source.status === 'error' && source.error_message) {+ return (+ <Tooltip title={source.error_message}>+ <LemonTag type="muted">disabled</LemonTag>+ </Tooltip>+ )+ }if (source.status === 'ready') {// Chunks + keyword (full-text) search are ready immediately, but semantic// embeddings are generated by a background job that can take up to an hour.diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.tsindex 2bb7ec8d6045..87e05b56cd45 100644--- a/products/business_knowledge/frontend/generated/api.schemas.ts+++ b/products/business_knowledge/frontend/generated/api.schemas.ts@@ -46,7 +46,7 @@ export interface KnowledgeSearchResultApi {readonly source_id: string/** Human label of the knowledge source this chunk belongs to. */readonly source_name: string- /** Source type (text, url, or file). */+ /** Source type: text, URL, or file. */readonly source_type: string/** Title of the document this chunk belongs to. */readonly document_title: string@@ -200,6 +200,8 @@ export interface KnowledgeSourceApi {readonly team_id: numberreadonly name: stringreadonly source_type: SourceTypeEnumApi+ /** Whether PostHog manages this source with knowledge learned from resolved support tickets. */+ readonly is_generated: booleanreadonly status: SourceStatusEnumApireadonly error_message: string/** Number of documents belonging to this source. */diff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsxindex 4bf9c81b3491..265aa459340a 100644--- a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx+++ b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'-import { IconBook, IconCheck, IconPencil, IconPlusSmall, IconRefresh, IconTrash, IconX } from '@posthog/icons'-import { LemonButton, LemonCard, LemonCollapse, LemonDialog, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'+import { IconBook, IconPencil, IconPlusSmall, IconRefresh, IconTrash } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'import { TZLabel } from 'lib/components/TZLabel'@@ -17,12 +17,7 @@ import { EditKnowledgeSourceModal } from '../components/EditKnowledgeSourceModalimport { RefreshStatusCell } from '../components/RefreshStatusCell'import { StatusTag } from '../components/StatusTag'import { businessKnowledgeEmptyState } from '../emptyState/businessKnowledgeEmptyState'-import {- type AggregatedGap,- KnowledgeSource,- REFRESH_INTERVAL_OPTIONS,- businessKnowledgeLogic,-} from './businessKnowledgeLogic'+import { KnowledgeSource, REFRESH_INTERVAL_OPTIONS, businessKnowledgeLogic } from './businessKnowledgeLogic'export const scene: SceneExport = {component: BusinessKnowledgeScene,@@ -33,10 +28,8 @@ export const scene: SceneExport = {export function BusinessKnowledgeScene(): JSX.Element {const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')- const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds, gapSuggestions, gapSuggestionsLoading } =- useValues(businessKnowledgeLogic)- const { openCreateModal, openEditModal, deleteSource, refreshSource, acceptGapSuggestion, dismissGapSuggestion } =- useActions(businessKnowledgeLogic)+ const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds } = useValues(businessKnowledgeLogic)+ const { openCreateModal, openEditModal, deleteSource, refreshSource } = useActions(businessKnowledgeLogic)if (!isEnabled) {return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />@@ -61,23 +54,18 @@ export function BusinessKnowledgeScene(): JSX.Element {<span>{totalChunks.toLocaleString()} chunks indexed</span></div>- {gapSuggestions.length > 0 && (- <GapSuggestionsPanel- suggestions={gapSuggestions}- loading={gapSuggestionsLoading}- onAccept={acceptGapSuggestion}- onDismiss={dismissGapSuggestion}- />- )}-<LemonTable<KnowledgeSource>dataSource={sources}loading={sourcesLoading}rowKey={(row) => row.id}- onRow={(row) => ({- onClick: () => openEditModal(row),- style: { cursor: 'pointer' },- })}+ onRow={(row) =>+ row.is_generated+ ? {}+ : {+ onClick: () => openEditModal(row),+ style: { cursor: 'pointer' },+ }+ }columns={[{title: 'Name',@@ -86,6 +74,14 @@ export function BusinessKnowledgeScene(): JSX.Element {<div className="flex flex-col"><span className="flex items-center gap-1"><strong>{row.name}</strong>+ {row.is_generated ? (+ <LemonTag+ type="highlight"+ title="PostHog adds knowledge here from resolved support tickets. You cannot edit this source."+ >+ Learned+ </LemonTag>+ ) : null}{row.has_unsafe_documents ? (<LemonTagtype="danger"@@ -125,7 +121,8 @@ export function BusinessKnowledgeScene(): JSX.Element {key: 'chunk_count',render: (_, row) => {const pages = row.document_count- return row.source_type === 'url' && row.crawl_mode && row.crawl_mode !== 'single'+ return row.is_generated ||+ (row.source_type === 'url' && row.crawl_mode && row.crawl_mode !== 'single')? `${pages.toLocaleString()} / ${row.chunk_count.toLocaleString()}`: row.chunk_count.toLocaleString()},@@ -144,50 +141,51 @@ export function BusinessKnowledgeScene(): JSX.Element {title: '',key: 'actions',width: 0,- render: (_, row) => (- <div className="flex gap-1 justify-end">- {row.source_type === 'url' && (+ render: (_, row) =>+ row.is_generated ? null : (+ <div className="flex gap-1 justify-end">+ {row.source_type === 'url' && (+ <LemonButton+ icon={<IconRefresh />}+ size="small"+ tooltip="Re-fetch and re-index this URL"+ loading={refreshingIds.includes(row.id)}+ onClick={(e) => {+ e.stopPropagation()+ refreshSource(row.id)+ }}+ />+ )}<LemonButton- icon={<IconRefresh />}+ icon={<IconPencil />}size="small"- tooltip="Re-fetch and re-index this URL"- loading={refreshingIds.includes(row.id)}+ tooltip="Edit"onClick={(e) => {e.stopPropagation()- refreshSource(row.id)+ openEditModal(row)}}/>- )}- <LemonButton- icon={<IconPencil />}- size="small"- tooltip="Edit"- onClick={(e) => {- e.stopPropagation()- openEditModal(row)- }}- />- <LemonButton- icon={<IconTrash />}- status="danger"- size="small"- tooltip="Delete"- onClick={(e) => {- e.stopPropagation()- LemonDialog.open({- title: `Delete "${row.name}"?`,- description: 'Chunks will be removed.',- primaryButton: {- children: 'Delete',- status: 'danger',- onClick: () => deleteSource(row.id),- },- secondaryButton: { children: 'Cancel' },- })- }}- />- </div>- ),+ <LemonButton+ icon={<IconTrash />}+ status="danger"+ size="small"+ tooltip="Delete"+ onClick={(e) => {+ e.stopPropagation()+ LemonDialog.open({+ title: `Delete "${row.name}"?`,+ description: 'Chunks will be removed.',+ primaryButton: {+ children: 'Delete',+ status: 'danger',+ onClick: () => deleteSource(row.id),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }}+ />+ </div>+ ),},]}emptyState="No knowledge sources yet. Click 'Add source' to index your first."@@ -198,71 +196,3 @@ export function BusinessKnowledgeScene(): JSX.Element {</SceneContent>)}--function GapSuggestionsPanel({- suggestions,- loading,- onAccept,- onDismiss,-}: {- suggestions: AggregatedGap[]- loading: boolean- onAccept: (normalizedTopic: string, topic: string) => void- onDismiss: (normalizedTopic: string) => void-}): JSX.Element {- return (- <LemonCollapse- className="mb-4"- panels={[- {- key: 'gap_suggestions',- header: (- <span className="flex items-center gap-1">- Suggested additions- <LemonTag type="highlight" size="small">- {suggestions.length}- </LemonTag>- </span>- ),- content: loading ? (- <div className="text-muted text-sm p-2">Loading suggestions...</div>- ) : (- <div className="space-y-2">- <p className="text-muted text-xs">- Topics customers asked about that the AI couldn't answer from your knowledge base.- Accept to create a source, or dismiss.- </p>- {suggestions.map((gap) => (- <LemonCard key={gap.normalized_topic} className="flex items-center justify-between p-3">- <div className="flex-1 min-w-0">- <div className="font-medium truncate">{gap.topic}</div>- <div className="text-xs text-muted">- {gap.ticket_count} ticket{gap.ticket_count !== 1 ? 's' : ''}- </div>- </div>- <div className="flex gap-1 ml-2">- <LemonButton- size="small"- type="primary"- icon={<IconCheck />}- tooltip="Accept — create a source for this topic"- onClick={() => onAccept(gap.normalized_topic, gap.topic)}- >- Accept- </LemonButton>- <LemonButton- size="small"- icon={<IconX />}- tooltip="Dismiss"- onClick={() => onDismiss(gap.normalized_topic)}- />- </div>- </LemonCard>- ))}- </div>- ),- },- ]}- />- )-}diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.tsindex 86a50adb62ae..d29d6e1fab95 100644--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts@@ -4,7 +4,6 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } fromimport { loaders } from 'kea-loaders'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { getCurrentTeamId } from 'lib/utils/getAppContext'import {createFileSource,@@ -17,19 +16,8 @@ import {updateSource,} from '../api'import type { CreateUrlSourcePayload, RefreshIntervalOption, RefreshIntervalValue, UpdateSourcePayload } from '../api'-import {- businessKnowledgeGapSuggestionsAcceptTopicCreate,- businessKnowledgeGapSuggestionsDismissTopicCreate,- businessKnowledgeGapSuggestionsList,-} from '../generated/api'import type { KnowledgeSourceApi } from '../generated/api.schemas'-export interface AggregatedGap {- normalized_topic: string- topic: string- ticket_count: number-}-export type KnowledgeSource = KnowledgeSourceApiexport type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'@@ -120,7 +108,6 @@ function splitGlobs(raw: string): string[] {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface businessKnowledgeLogicValues {- acceptingGapTopic: string | nullcreateTab: CreateTabeditSource: TextSourceFormValueseditSourceAllErrors: Record<string, any>@@ -155,8 +142,6 @@ export interface businessKnowledgeLogicValues {fileSourceTouched: booleanfileSourceTouches: Record<string, boolean>fileSourceValidationErrors: DeepPartialMap<FileSourceFormValues, ValidationErrorType>- gapSuggestions: AggregatedGap[]- gapSuggestionsLoading: booleanisCreateModalOpen: booleanisEditModalOpen: booleanisEditSourceSubmitting: boolean@@ -201,32 +186,15 @@ export interface businessKnowledgeLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface businessKnowledgeLogicActions {- acceptGapSuggestion: (- normalizedTopic: string,- topic: string- ) => {- normalizedTopic: string- topic: string- }closeCreateModal: () => {value: true}closeEditModal: () => {value: true}- confirmGapAccept: (- normalizedTopic: string,- sourceId: string- ) => {- normalizedTopic: string- sourceId: string- }deleteSource: (id: string) => {id: string}- dismissGapSuggestion: (normalizedTopic: string) => {- normalizedTopic: string- }loadEditingSourceText: ({ id }: { id: string }) => {id: string}@@ -254,27 +222,6 @@ export interface businessKnowledgeLogicActions {id: string}}- loadGapSuggestions: () => {- value: true- }- loadGapSuggestionsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadGapSuggestionsSuccess: (- gapSuggestions: AggregatedGap[],- payload?: {- value: true- }- ) => {- gapSuggestions: AggregatedGap[]- payload?: {- value: true- }- }loadSources: () => anyloadSourcesFailure: (error: string,@@ -290,8 +237,8 @@ export interface businessKnowledgeLogicActions {sources: KnowledgeSourceApi[]payload?: any}- openCreateModal: (prefillName?: string) => {- prefillName: string | undefined+ openCreateModal: () => {+ value: true}openEditModal: (source: KnowledgeSource) => {source: KnowledgeSourceApi@@ -564,7 +511,7 @@ export type businessKnowledgeLogicType = MakeLogicType<export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([path(['products', 'business_knowledge', 'businessKnowledgeLogic']),actions({- openCreateModal: (prefillName?: string) => ({ prefillName }),+ openCreateModal: true,closeCreateModal: true,setCreateTab: (tab: CreateTab) => ({ tab }),openEditModal: (source: KnowledgeSource) => ({ source }),@@ -572,11 +519,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([deleteSource: (id: string) => ({ id }),refreshSource: (id: string) => ({ id }),refreshSourceDone: (id: string) => ({ id }),- // Gap suggestions- loadGapSuggestions: true,- acceptGapSuggestion: (normalizedTopic: string, topic: string) => ({ normalizedTopic, topic }),- confirmGapAccept: (normalizedTopic: string, sourceId: string) => ({ normalizedTopic, sourceId }),- dismissGapSuggestion: (normalizedTopic: string) => ({ normalizedTopic }),}),reducers({isCreateModalOpen: [@@ -607,15 +549,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([refreshSourceDone: (state, { id }) => state.filter((x) => x !== id),},],- // Set when the create modal was opened by accepting a gap; the cluster is only- // marked accepted once the human actually creates a source (or stays pending on cancel).- acceptingGapTopic: [- null as string | null,- {- acceptGapSuggestion: (_, { normalizedTopic }) => normalizedTopic,- closeCreateModal: () => null,- },- ],}),loaders(({ values }) => ({sources: [@@ -638,34 +571,15 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([resetEditingSourceText: () => ({ id: '', text: '' }),},],- gapSuggestions: [- [] as AggregatedGap[],- {- loadGapSuggestions: async (): Promise<AggregatedGap[]> => {- try {- const response = await businessKnowledgeGapSuggestionsList(String(getCurrentTeamId()))- // Aggregated endpoint returns a plain array; per-ticket returns paginated- const data = Array.isArray(response) ? response : (response.results ?? [])- return data as unknown as AggregatedGap[]- } catch {- return []- }- },- },- ],})),forms(({ actions, values }) => ({textSource: {defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,errors: validateText,submit: async ({ name, text, always_include }: TextSourceFormValues) => {- const acceptTopic = values.acceptingGapTopictry {const created = await createTextSource(name, text, always_include)lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)- if (acceptTopic) {- actions.confirmGapAccept(acceptTopic, created.id)- }actions.closeCreateModal()actions.resetTextSource()actions.loadSources()@@ -693,7 +607,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([} as UrlSourceFormValues,errors: validateUrl,submit: async (formValues: UrlSourceFormValues) => {- const acceptTopic = values.acceptingGapTopicconst includeGlobs = splitGlobs(formValues.include_globs)const payload: CreateUrlSourcePayload = {name: formValues.name,@@ -716,9 +629,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([// Ingestion runs in the background; the source starts PROCESSING// and the list polls until it flips to ready.lemonToast.success(`"${created.name}" added — fetching and indexing in the background`)- if (acceptTopic) {- actions.confirmGapAccept(acceptTopic, created.id)- }actions.closeCreateModal()actions.resetUrlSource()actions.loadSources()@@ -747,7 +657,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([if (!file) {return}- const acceptTopic = values.acceptingGapTopicconst formData = new FormData()formData.append('name', name)formData.append('file', file)@@ -756,9 +665,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([try {const created = await createFileSource(formData)lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)- if (acceptTopic) {- actions.confirmGapAccept(acceptTopic, created.id)- }actions.closeCreateModal()actions.resetFileSource()actions.loadSources()@@ -948,38 +854,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([actions.resetEditUrlSource()actions.resetEditingSourceText()},- acceptGapSuggestion: ({ topic }) => {- // Don't mark the cluster accepted yet — only once the human actually creates a- // source (handled in confirmGapAccept). The acceptingGapTopic reducer holds the- // pending topic so a cancel leaves the suggestion in place.- actions.openCreateModal(topic)- },- confirmGapAccept: async ({ normalizedTopic, sourceId }) => {- try {- await businessKnowledgeGapSuggestionsAcceptTopicCreate(String(getCurrentTeamId()), {- normalized_topic: normalizedTopic,- resolved_source_id: sourceId,- })- actions.loadGapSuggestions()- } catch {- // Best-effort — the source was already created successfully.- }- },- dismissGapSuggestion: async ({ normalizedTopic }) => {- try {- await businessKnowledgeGapSuggestionsDismissTopicCreate(String(getCurrentTeamId()), {- normalized_topic: normalizedTopic,- })- actions.loadGapSuggestions()- } catch {- lemonToast.error('Failed to dismiss suggestion')- }- },- openCreateModal: ({ prefillName }) => {- if (prefillName) {- actions.setTextSourceValue('name', prefillName)- }- },})),selectors({readyCount: [@@ -994,6 +868,5 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([}),afterMount(({ actions }) => {actions.loadSources()- actions.loadGapSuggestions()}),])diff --git a/products/conversations/frontend/scenes/ticket/AIPanel.tsx b/products/conversations/frontend/scenes/ticket/AIPanel.tsxindex 49a2357b5d40..b99a3aaba759 100644--- a/products/conversations/frontend/scenes/ticket/AIPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/AIPanel.tsx@@ -1,13 +1,9 @@-import { IconX } from '@posthog/icons'-import { LemonButton, LemonCollapse, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonCollapse, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { Link } from 'lib/lemon-ui/Link'-import { urls } from 'scenes/urls'import {type AITriage,- type KnowledgeGapSuggestion,aiTriageResultLabel,aiTriageResultTagType,aiTriageTicketTypeDescription,@@ -16,9 +12,6 @@ import {interface AIPanelProps {aiTriage?: AITriage- knowledgeGaps?: KnowledgeGapSuggestion[]- knowledgeGapsLoading?: boolean- onDismissGap?: (suggestionId: string) => void}function AITriageHeaderTag({ aiTriage }: { aiTriage?: AITriage }): JSX.Element | null {@@ -38,9 +31,8 @@ function AITriageHeaderTag({ aiTriage }: { aiTriage?: AITriage }): JSX.Element |return null}-export function AIPanel({ aiTriage, knowledgeGaps, knowledgeGapsLoading, onDismissGap }: AIPanelProps): JSX.Element {+export function AIPanel({ aiTriage }: AIPanelProps): JSX.Element {const hasData = aiTriage && aiTriage.status- const pendingGaps = knowledgeGaps?.filter((g) => g.status === 'pending') ?? []return (<LemonCollapse@@ -123,50 +115,6 @@ export function AIPanel({ aiTriage, knowledgeGaps, knowledgeGapsLoading, onDismi<div className="text-muted-alt text-xs">AI has not processed this ticket yet.</div>),},- ...(pendingGaps.length > 0 || knowledgeGapsLoading- ? [- {- key: 'knowledge_gaps',- header: (- <span className="flex items-center gap-1">- Knowledge gaps- {pendingGaps.length > 0 && (- <LemonTag type="highlight" size="small">- {pendingGaps.length}- </LemonTag>- )}- </span>- ),- content: knowledgeGapsLoading ? (- <Spinner className="text-sm" />- ) : (- <div className="space-y-2 text-xs">- <p className="text-muted-alt">- Topics the AI couldn't cover from{' '}- <Link to={urls.businessKnowledge()}>Business knowledge</Link>.- </p>- {pendingGaps.map((gap) => (- <div key={gap.id} className="flex items-start justify-between gap-1 py-0.5">- <span className="flex-1 break-words">{gap.topic}</span>- {onDismissGap && (- <LemonButton- size="xsmall"- icon={<IconX />}- tooltip="Dismiss"- noPadding- onClick={() => onDismissGap(gap.id)}- />- )}- </div>- ))}- <Link to={urls.businessKnowledge()} className="text-xs">- Manage in Business knowledge- </Link>- </div>- ),- },- ]- : []),]}/>)diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex f90df8781a7d..d82d3c974cc2 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -103,8 +103,6 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemdraftModeEnabled,replyRecipientDescription,snoozedUntil,- knowledgeGaps,- knowledgeGapsLoading,emailReplyBlockedReason,latestAiMessage,feedbackByMessageId,@@ -131,7 +129,6 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemsetDraftContent,setDraftIsPrivate,setDraftModeEnabled,- dismissKnowledgeGap,submitAiReplyFeedback,startEditingMessage,cancelEditingMessage,@@ -596,14 +593,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem{user?.is_staff && ticket && <StaffActionsPanel />}{/* AI Triage Panel */}- {aiSuggestionsEnabled && ticket && (- <AIPanel- aiTriage={ticket.ai_triage}- knowledgeGaps={knowledgeGaps}- knowledgeGapsLoading={knowledgeGapsLoading}- onDismissGap={dismissKnowledgeGap}- />- )}+ {aiSuggestionsEnabled && ticket && <AIPanel aiTriage={ticket.ai_triage} />}{ticket?.channel_source === 'widget' && (<>diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex 880844a7706d..215aec86b5fb 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -58,11 +58,6 @@ jest.mock('~/lib/api', () => {}})-jest.mock('products/business_knowledge/frontend/generated/api', () => ({- businessKnowledgeGapSuggestionsList: jest.fn().mockResolvedValue({ results: [] }),- businessKnowledgeGapSuggestionsDismissCreate: jest.fn().mockResolvedValue(undefined),-}))-jest.mock('products/conversations/frontend/generated/api', () => ({conversationsTicketsMessagesFullEmailRetrieve: jest.fn().mockResolvedValue({ content: 'Full email body' }),conversationsTicketsNotesPartialUpdate: jest.fn().mockResolvedValue(undefined),diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 8140eb60324a..af0a3dc05a63 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -44,10 +44,6 @@ import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'import type { Breadcrumb, CommentType, PersonType, UserType } from '~/types'import { ActivityScope, PropertyFilterType, PropertyOperator, Region } from '~/types'-import {- businessKnowledgeGapSuggestionsDismissCreate,- businessKnowledgeGapSuggestionsList,-} from 'products/business_knowledge/frontend/generated/api'import {conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesDestroy,@@ -66,14 +62,7 @@ import { assigneeSelectLogic } from '../../components/Assignee'import type { Assignee, TicketAssignee } from '../../components/Assignee'import { supportTicketCounterLogic } from '../../supportTicketCounterLogic'import { priorityOptions } from '../../types'-import type {- AiReplyFeedbackRating,- ChatMessage,- KnowledgeGapSuggestion,- Ticket,- TicketPriority,- TicketStatus,-} from '../../types'+import type { AiReplyFeedbackRating, ChatMessage, Ticket, TicketPriority, TicketStatus } from '../../types'import { conversationsDraftModeLogic } from '../settings/conversationsDraftModeLogic'import { supportTicketsSceneLogic } from '../tickets/supportTicketsSceneLogic'@@ -255,8 +244,6 @@ export interface supportTicketSceneLogicValues {hasMoreMessages: booleanhasPendingWork: booleanhasUnsavedChanges: boolean- knowledgeGaps: KnowledgeGapSuggestion[]- knowledgeGapsLoading: booleanlatestAiMessage: ChatMessage | nulllinkedReports: SignalReportApi[]linkedReportsLoading: boolean@@ -303,9 +290,6 @@ export interface supportTicketSceneLogicActions {deleteMessage: (messageId: string) => {messageId: string}- dismissKnowledgeGap: (suggestionId: string) => {- suggestionId: string- }incrementUnreadCustomerCount: () => {value: true}@@ -324,27 +308,6 @@ export interface supportTicketSceneLogicActions {fullEmailContent: stringpayload?: string}- loadKnowledgeGaps: () => {- value: true- }- loadKnowledgeGapsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadKnowledgeGapsSuccess: (- knowledgeGaps: KnowledgeGapSuggestion[],- payload?: {- value: true- }- ) => {- knowledgeGaps: KnowledgeGapSuggestion[]- payload?: {- value: true- }- }loadLinkedReports: () => {value: true}@@ -627,10 +590,6 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([loadPreviousTickets: true,loadLinkedReports: true,- // Knowledge gap suggestions- loadKnowledgeGaps: true,- dismissKnowledgeGap: (suggestionId: string) => ({ suggestionId }),-// Draft message state (persists across tab switches)setDraftContent: (content: string | JSONContent | null) => ({ content }),setDraftIsPrivate: (isPrivate: boolean) => ({ isPrivate }),@@ -749,26 +708,6 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([},},],- knowledgeGaps: [- [] as KnowledgeGapSuggestion[],- {- loadKnowledgeGaps: async (): Promise<KnowledgeGapSuggestion[]> => {- const ticket = values.ticket- if (!ticket) {- return []- }- try {- const response = await businessKnowledgeGapSuggestionsList(String(getCurrentTeamId()), {- ticket_id: ticket.id,- })- const data = Array.isArray(response) ? response : (response.results ?? [])- return data as unknown as KnowledgeGapSuggestion[]- } catch {- return []- }- },- },- ],fullEmailContent: [null as string | null,{@@ -1217,7 +1156,6 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([// Load session context dataactions.loadPerson()- actions.loadKnowledgeGaps()actions.loadLinkedReports()// Refresh the unread count since viewing a ticket marks it as read@@ -1565,14 +1503,6 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([secondaryButton: { children: 'Cancel' },})},- dismissKnowledgeGap: async ({ suggestionId }) => {- try {- await businessKnowledgeGapSuggestionsDismissCreate(String(getCurrentTeamId()), suggestionId)- actions.loadKnowledgeGaps()- } catch {- lemonToast.error('Failed to dismiss suggestion')- }- },submitAiReplyFeedback: async ({ messageId, rating, feedbackText }) => {const ticket = values.ticketif (!ticket) {diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex fadc1db4a5b2..8f83f0438364 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -79,20 +79,6 @@ export interface AITriage {export type AiReplyFeedbackRating = 'good' | 'bad'-export type GapSuggestionStatus = 'pending' | 'accepted' | 'dismissed'--export interface KnowledgeGapSuggestion {- id: string- ticket_id: string- topic: string- normalized_topic: string- ticket_type: string- outcome: string- status: GapSuggestionStatus- resolved_source_id: string | null- created_at: string-}-/*** Canonical saved-view filter shape, generated from the backend's TicketViewFiltersSerializer.* `assignee` is widened locally: the API stores filters raw, so old saved views can stilldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 41cd67266e25..13f3ca26c9de 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48555,7 +48555,7 @@ export namespace Schemas {readonly source_id: string;/** Human label of the knowledge source this chunk belongs to. */readonly source_name: string;- /** Source type (text, url, or file). */+ /** Source type: text, URL, or file. */readonly source_type: string;/** Title of the document this chunk belongs to. */readonly document_title: string;@@ -48632,6 +48632,8 @@ export namespace Schemas {readonly team_id: number;readonly name: string;readonly source_type: SourceTypeEnum;+ /** Whether PostHog manages this source with knowledge learned from resolved support tickets. */+ readonly is_generated: boolean;readonly status: SourceStatusEnum;readonly error_message: string;/** Number of documents belonging to this source. */