: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): record support AI knowledge gaps as suggestions (#66636)
Alex Ve4bd30ec91c7
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 06e6b1ff9cbb..f9fedafa27c0 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -168,6 +168,7 @@ rules:|IntervieweeContext|KnowledgeChunk|KnowledgeDocument+ |KnowledgeGapSuggestion|KnowledgeSource|Link|LiveDebuggerBreakpoint@@ -435,6 +436,7 @@ rules:|IntervieweeContext|KnowledgeChunk|KnowledgeDocument+ |KnowledgeGapSuggestion|KnowledgeSource|Link|LiveDebuggerBreakpointdiff --git a/products/business_knowledge/backend/api/__init__.py b/products/business_knowledge/backend/api/__init__.pyindex 36ac74e53709..a195eddab08e 100644--- a/products/business_knowledge/backend/api/__init__.py+++ b/products/business_knowledge/backend/api/__init__.py@@ -1,3 +1,3 @@-from .views import KnowledgeDocumentViewSet, KnowledgeSourceViewSet+from .views import KnowledgeDocumentViewSet, KnowledgeGapSuggestionViewSet, KnowledgeSourceViewSet-__all__ = ["KnowledgeDocumentViewSet", "KnowledgeSourceViewSet"]+__all__ = ["KnowledgeDocumentViewSet", "KnowledgeGapSuggestionViewSet", "KnowledgeSourceViewSet"]diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.pyindex 797a44e6d3f8..1abb2ecc13b4 100644--- a/products/business_knowledge/backend/api/serializers.py+++ b/products/business_knowledge/backend/api/serializers.py@@ -531,3 +531,55 @@ class CreateFileSourceSerializer(_NameValidationMixin, serializers.Serializer):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 value+++# ---------------------------------------------------------------------------+# Knowledge gap suggestions+# ---------------------------------------------------------------------------+++class KnowledgeGapSuggestionSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this gap suggestion.")+ ticket_id = serializers.UUIDField(read_only=True, help_text="The ticket that surfaced this gap.")+ topic = serializers.CharField(read_only=True, help_text="Raw topic the AI couldn't answer.")+ normalized_topic = serializers.CharField(read_only=True, help_text="Normalized cluster key for grouping.")+ ticket_type = serializers.CharField(read_only=True, help_text="Ticket classification type.")+ outcome = serializers.CharField(read_only=True, help_text="Pipeline outcome that produced this gap.")+ status = serializers.CharField(read_only=True, help_text="Current status: pending, accepted, or dismissed.")+ resolved_source_id = serializers.UUIDField(+ read_only=True, allow_null=True, help_text="Knowledge source created to fill this gap."+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When this gap was first recorded.")+++class AggregatedGapSerializer(serializers.Serializer):+ normalized_topic = serializers.CharField(read_only=True, help_text="Normalized cluster key.")+ topic = serializers.CharField(read_only=True, help_text="Representative raw topic string.")+ ticket_count = serializers.IntegerField(read_only=True, help_text="Number of distinct tickets with this gap.")+++class GapActionSerializer(serializers.Serializer):+ resolved_source_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text="Optional knowledge source to link when accepting.",+ )+++class GapTopicActionSerializer(serializers.Serializer):+ normalized_topic = serializers.CharField(+ required=True,+ help_text="The normalized topic key identifying the gap cluster to act on.",+ )+ resolved_source_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text="Optional knowledge source to link when accepting.",+ )+++class GapTopicActionResultSerializer(serializers.Serializer):+ normalized_topic = serializers.CharField(+ read_only=True, help_text="The normalized topic cluster that was acted on."+ )+ updated = serializers.IntegerField(read_only=True, help_text="Number of gap rows whose status changed.")diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.pyindex 925b22064430..abe65cbd95c7 100644--- a/products/business_knowledge/backend/api/views.py+++ b/products/business_knowledge/backend/api/views.py@@ -1,6 +1,6 @@"""DRF views for business_knowledge."""-from typing import cast+from typing import Any, castfrom uuid import UUIDfrom django.conf import settings@@ -27,15 +27,20 @@ from posthog.temporal.common.client import sync_connectfrom .. import logicfrom ..constants import BK_DRILLDOWN_DEFAULT_RADIUS, BK_DRILLDOWN_MAX_RADIUSfrom ..file_parse import FileParseError-from ..models import KnowledgeDocument, KnowledgeSource, SourceType+from ..models import GapStatus, KnowledgeDocument, KnowledgeGapSuggestion, KnowledgeSource, SourceTypefrom ..models.constants import CrawlModefrom ..temporal.coordinator import IngestSourceInputs, RefreshSourceInputsfrom .serializers import (+ AggregatedGapSerializer,CreateCrawlSourceSerializer,CreateFileSourceSerializer,CreateTextSourceSerializer,CreateUrlSourceSerializer,+ GapActionSerializer,+ GapTopicActionResultSerializer,+ GapTopicActionSerializer,KnowledgeDocumentWindowSerializer,+ KnowledgeGapSuggestionSerializer,KnowledgeSearchResultSerializer,KnowledgeSourceSerializer,UpdateTextSourceSerializer,@@ -499,3 +504,141 @@ class KnowledgeDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return int(raw)except (TypeError, ValueError):raise exceptions.ValidationError({name: "Must be an integer."})+++class KnowledgeGapSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Surfaces topics the support AI couldn't answer from the knowledge base.++ Two list shapes controlled by the ``ticket_id`` query param:+ - **per-ticket** (``?ticket_id=<uuid>``): individual gap rows for that ticket.+ - **aggregated** (no ``ticket_id``): gaps grouped by normalized topic with counts,+ for the Business knowledge suggestions panel.+ """++ scope_object = "business_knowledge"+ queryset = KnowledgeGapSuggestion.objects.unscoped()+ serializer_class = KnowledgeGapSuggestionSerializer+ permission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]+ 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)++ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ # Any path that exposes data derived from a specific support ticket (topic, status,+ # outcome, ticket type, ticket id) must also require `ticket:read` — `business_knowledge`+ # alone must not be a backdoor to ticket data. This covers the per-ticket list path+ # (`?ticket_id=`) and the single-row `accept`/`dismiss` actions, whose responses serialize+ # the ticket-linked fields. Only applies to token auth; session users are gated by team+ # membership (and already have ticket access via the ticket API). The topic-level+ # `accept_topic`/`dismiss_topic` actions and the aggregated list expose no ticket data, so+ # they fall through to the default `business_knowledge` scope.+ if self.action == "list" and request.query_params.get("ticket_id"):+ return ["business_knowledge:read", "ticket:read"]+ if self.action in ("accept", "dismiss"):+ return ["business_knowledge:write", "ticket:read"]+ return None++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="ticket_id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.QUERY,+ required=False,+ description="When provided, returns per-ticket gap rows instead of aggregated view. "+ "Requires `ticket:read` scope in addition to `business_knowledge:read`.",+ ),+ ],+ responses={200: KnowledgeGapSuggestionSerializer(many=True)},+ )+ def list(self, request: Request, **kwargs) -> Response:+ ticket_id = request.query_params.get("ticket_id")+ if ticket_id:+ try:+ UUID(ticket_id)+ except ValueError:+ raise exceptions.ValidationError({"ticket_id": "Must be a valid UUID."})+ suggestions = logic.list_gap_suggestions_for_ticket(self.team_id, ticket_id)+ page = self.paginate_queryset(suggestions)+ if page is not None:+ return self.get_paginated_response(KnowledgeGapSuggestionSerializer(instance=page, many=True).data)+ return Response(KnowledgeGapSuggestionSerializer(instance=suggestions, many=True).data)++ aggregated = logic.aggregate_gap_suggestions(self.team_id)+ return Response(AggregatedGapSerializer(instance=aggregated, many=True).data)++ @extend_schema(+ request=GapActionSerializer,+ responses={200: KnowledgeGapSuggestionSerializer},+ )+ @action(detail=True, methods=["post"], url_path="accept")+ def accept(self, request: Request, **kwargs) -> Response:+ suggestion = self.get_object()+ ser = GapActionSerializer(data=request.data)+ ser.is_valid(raise_exception=True)+ logic.set_gap_status(+ self.team_id,+ suggestion_id=suggestion.id,+ status=GapStatus.ACCEPTED,+ resolved_source_id=ser.validated_data.get("resolved_source_id"),+ )+ suggestion.refresh_from_db()+ return Response(KnowledgeGapSuggestionSerializer(instance=suggestion).data)++ @extend_schema(+ request=None,+ responses={200: KnowledgeGapSuggestionSerializer},+ )+ @action(detail=True, methods=["post"], url_path="dismiss")+ def dismiss(self, request: Request, **kwargs) -> Response:+ suggestion = self.get_object()+ logic.set_gap_status(+ self.team_id,+ suggestion_id=suggestion.id,+ status=GapStatus.DISMISSED,+ )+ suggestion.refresh_from_db()+ return Response(KnowledgeGapSuggestionSerializer(instance=suggestion).data)++ @extend_schema(+ request=GapTopicActionSerializer,+ responses={200: GapTopicActionResultSerializer},+ )+ @action(detail=False, methods=["post"], url_path="accept_topic")+ def accept_topic(self, request: Request, **kwargs) -> Response:+ """Accept all pending suggestions for a normalized topic cluster."""+ ser = GapTopicActionSerializer(data=request.data)+ ser.is_valid(raise_exception=True)+ normalized_topic = ser.validated_data["normalized_topic"]+ updated = logic.set_gap_status(+ self.team_id,+ normalized_topic=normalized_topic,+ status=GapStatus.ACCEPTED,+ resolved_source_id=ser.validated_data.get("resolved_source_id"),+ only_pending=True,+ )+ if updated == 0:+ raise exceptions.NotFound("No actionable suggestions found for this topic.")+ return Response({"normalized_topic": normalized_topic, "updated": updated})++ @extend_schema(+ request=GapTopicActionSerializer,+ responses={200: GapTopicActionResultSerializer},+ )+ @action(detail=False, methods=["post"], url_path="dismiss_topic")+ def dismiss_topic(self, request: Request, **kwargs) -> Response:+ """Dismiss all pending suggestions for a normalized topic cluster."""+ ser = GapTopicActionSerializer(data=request.data)+ ser.is_valid(raise_exception=True)+ normalized_topic = ser.validated_data["normalized_topic"]+ updated = logic.set_gap_status(+ self.team_id,+ normalized_topic=normalized_topic,+ status=GapStatus.DISMISSED,+ only_pending=True,+ )+ if updated == 0:+ raise exceptions.NotFound("No actionable suggestions found for this topic.")+ return Response({"normalized_topic": normalized_topic, "updated": updated})diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex aba8e6e40dca..2a63bacfa78b 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -20,7 +20,7 @@ from django.db import (connection as db_connection,transaction,)-from django.db.models import Count, Exists, F, OuterRef, Q, QuerySet+from django.db.models import Count, Exists, F, Max, OuterRef, Q, QuerySetfrom django.db.models.functions import Substrfrom django.utils import timezone@@ -73,8 +73,10 @@ from .constants import (from .models import (REFRESH_INTERVAL_TIMEDELTAS,CrawlMode,+ GapStatus,KnowledgeChunk,KnowledgeDocument,+ KnowledgeGapSuggestion,KnowledgeSource,RefreshInterval,SafetyVerdict,@@ -2563,3 +2565,118 @@ def clear_document_embeddings_emitted(*, team_id: int, document_id: UUID) -> NonKnowledgeDocument.objects.filter(team_id=team_id, id=document_id).update(embeddings_emitted_at=None, updated_at=timezone.now())+++# ---------------------------------------------------------------------------+# Knowledge gap suggestions+# ---------------------------------------------------------------------------++_GAP_NOISE_TOPICS = frozenset({"parse_failure"})+++def _normalize_topic(topic: str) -> str:+ return topic.strip().lower()[:255]+++def upsert_knowledge_gaps(+ team_id: int,+ ticket_id: str,+ topics: list[str],+ ticket_type: str = "",+ outcome: str = "",+) -> int:+ """Create one KnowledgeGapSuggestion per (ticket, normalized topic).++ Idempotent via the unique constraint — safe under Temporal activity retries.+ Returns the number of rows created (not the total including existing ones).+ """+ created_count = 0+ for raw_topic in topics:+ normalized = _normalize_topic(raw_topic)+ if not normalized or normalized in _GAP_NOISE_TOPICS:+ continue+ _, created = KnowledgeGapSuggestion.objects.for_team(team_id).get_or_create(+ team_id=team_id,+ ticket_id=ticket_id,+ normalized_topic=normalized,+ defaults={+ "topic": raw_topic.strip(),+ "ticket_type": ticket_type,+ "outcome": outcome,+ },+ )+ if created:+ created_count += 1+ return created_count+++def list_gap_suggestions_for_ticket(+ team_id: int,+ ticket_id: str,+) -> QuerySet[KnowledgeGapSuggestion]:+ return KnowledgeGapSuggestion.objects.for_team(team_id).filter(ticket_id=ticket_id).order_by("-created_at")+++@dataclass+class AggregatedGap:+ normalized_topic: str+ topic: str+ ticket_count: int+++def aggregate_gap_suggestions(+ team_id: int,+ status: str = GapStatus.PENDING,+ limit: int = 50,+) -> list[AggregatedGap]:+ """Group pending gaps by normalized_topic, ranked by ticket count."""+ rows = (+ KnowledgeGapSuggestion.objects.for_team(team_id)+ .filter(status=status)+ .values("normalized_topic")+ .annotate(+ ticket_count=Count("ticket_id", distinct=True),+ representative_topic=Substr(Max("topic"), 1, 500),+ )+ .order_by("-ticket_count")[:limit]+ )+ return [+ AggregatedGap(+ normalized_topic=r["normalized_topic"],+ topic=r["representative_topic"],+ ticket_count=r["ticket_count"],+ )+ for r in rows+ ]+++def set_gap_status(+ team_id: int,+ *,+ suggestion_id: UUID | None = None,+ normalized_topic: str | None = None,+ status: str,+ resolved_source_id: UUID | None = None,+ only_pending: bool = False,+) -> int:+ """Accept or dismiss gap suggestions. Returns updated row count.++ Pass suggestion_id for a single row, or normalized_topic to flip the whole+ cluster (all tickets with that topic). Set only_pending=True to restrict+ the update to rows still in PENDING status.+ """+ qs = KnowledgeGapSuggestion.objects.for_team(team_id)+ if suggestion_id is not None:+ qs = qs.filter(id=suggestion_id)+ elif normalized_topic is not None:+ qs = qs.filter(normalized_topic=normalized_topic)+ else:+ raise ValueError("One of suggestion_id or normalized_topic is required")++ if only_pending:+ qs = qs.filter(status=GapStatus.PENDING)++ update_kwargs: dict[str, object] = {"status": status}+ if resolved_source_id is not None:+ update_kwargs["resolved_source_id"] = resolved_source_id+ return qs.update(**update_kwargs)diff --git a/products/business_knowledge/backend/migrations/0014_knowledge_gap_suggestion.py b/products/business_knowledge/backend/migrations/0014_knowledge_gap_suggestion.pynew file mode 100644index 000000000000..d961b78d99fd--- /dev/null+++ b/products/business_knowledge/backend/migrations/0014_knowledge_gap_suggestion.py@@ -0,0 +1,70 @@+import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("business_knowledge", "0013_bk_source_always_include_index"),+ ("posthog", "1245_duckgres_sink_schema_state"),+ ]++ operations = [+ migrations.CreateModel(+ name="KnowledgeGapSuggestion",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("ticket_id", models.UUIDField(db_index=True)),+ ("topic", models.TextField()),+ ("normalized_topic", models.CharField(max_length=255)),+ ("ticket_type", models.CharField(blank=True, default="", max_length=32)),+ ("outcome", models.CharField(blank=True, default="", max_length=32)),+ (+ "status",+ models.CharField(+ choices=[("pending", "Pending"), ("accepted", "Accepted"), ("dismissed", "Dismissed")],+ default="pending",+ max_length=16,+ ),+ ),+ (+ "resolved_source",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="business_knowledge.knowledgesource",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="business_knowledge_gap_suggestions",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_business_knowledge_knowledgegapsuggestion",+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "ticket_id", "normalized_topic"),+ name="bk_gap_unique_per_ticket_topic",+ ),+ ],+ },+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/0015_bk_gap_team_status_topic_index.py b/products/business_knowledge/backend/migrations/0015_bk_gap_team_status_topic_index.pynew file mode 100644index 000000000000..542d2374b231--- /dev/null+++ b/products/business_knowledge/backend/migrations/0015_bk_gap_team_status_topic_index.py@@ -0,0 +1,21 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("business_knowledge", "0014_knowledge_gap_suggestion"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="knowledgegapsuggestion",+ index=models.Index(+ fields=["team", "status", "normalized_topic"],+ name="bk_gap_team_status_topic",+ ),+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtindex 66a568d272c0..17ecd997e4cb 100644--- a/products/business_knowledge/backend/migrations/max_migration.txt+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -1 +1 @@-0013_bk_source_always_include_index+0015_bk_gap_team_status_topic_indexdiff --git a/products/business_knowledge/backend/models/__init__.py b/products/business_knowledge/backend/models/__init__.pyindex a8fd11a4fb8c..5de90f80f467 100644--- a/products/business_knowledge/backend/models/__init__.py+++ b/products/business_knowledge/backend/models/__init__.py@@ -2,6 +2,7 @@ from .constants import (REFRESH_INTERVAL_TIMEDELTAS,CrawlMode,EmbeddingStatus,+ GapStatus,RefreshInterval,RefreshStatus,SafetyVerdict,@@ -10,14 +11,17 @@ from .constants import ()from .knowledge_chunk import KnowledgeChunkfrom .knowledge_document import KnowledgeDocument+from .knowledge_gap_suggestion import KnowledgeGapSuggestionfrom .knowledge_source import KnowledgeSource__all__ = ["REFRESH_INTERVAL_TIMEDELTAS","CrawlMode","EmbeddingStatus",+ "GapStatus","KnowledgeChunk","KnowledgeDocument",+ "KnowledgeGapSuggestion","KnowledgeSource","RefreshInterval","RefreshStatus",diff --git a/products/business_knowledge/backend/models/constants.py b/products/business_knowledge/backend/models/constants.pyindex 81c267dd7248..e6c22b25cc9f 100644--- a/products/business_knowledge/backend/models/constants.py+++ b/products/business_knowledge/backend/models/constants.py@@ -92,6 +92,12 @@ class EmbeddingStatus(models.TextChoices):DISABLED = "disabled", "Disabled"+class GapStatus(models.TextChoices):+ PENDING = "pending", "Pending"+ ACCEPTED = "accepted", "Accepted"+ DISMISSED = "dismissed", "Dismissed"++class SafetyVerdict(models.TextChoices):"""Content-safety classification of a document, set by the backgrounddiff --git a/products/business_knowledge/backend/models/knowledge_gap_suggestion.py b/products/business_knowledge/backend/models/knowledge_gap_suggestion.pynew file mode 100644index 000000000000..32265ca92c61--- /dev/null+++ b/products/business_knowledge/backend/models/knowledge_gap_suggestion.py@@ -0,0 +1,46 @@+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel++from .constants import GapStatus+from .knowledge_source import KnowledgeSource+++class KnowledgeGapSuggestion(TeamScopedRootMixin, UUIDModel):+ """A topic the support AI couldn't answer from the knowledge base.++ One row per (ticket, normalized topic). The ticket view filters by ticket_id;+ the BK view aggregates by normalized_topic across tickets.+ """++ team = models.ForeignKey(+ "posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="business_knowledge_gap_suggestions"+ )+ ticket_id = models.UUIDField(db_index=True)+ # Rows are created by the support AI pipeline, not a user, so there's no `created_by` FK+ # (avoids an FK constraint on the hot posthog_user table). Just track when the gap appeared.+ created_at = models.DateTimeField(auto_now_add=True)+ topic = models.TextField()+ normalized_topic = models.CharField(max_length=255)+ ticket_type = models.CharField(max_length=32, blank=True, default="")+ outcome = models.CharField(max_length=32, blank=True, default="")+ status = models.CharField(max_length=16, choices=GapStatus.choices, default=GapStatus.PENDING)+ resolved_source = models.ForeignKey(+ KnowledgeSource, null=True, blank=True, on_delete=models.SET_NULL, related_name="+"+ )++ class Meta:+ db_table = "posthog_business_knowledge_knowledgegapsuggestion"+ constraints = [+ models.UniqueConstraint(+ fields=["team", "ticket_id", "normalized_topic"],+ name="bk_gap_unique_per_ticket_topic",+ ),+ ]+ indexes = [+ models.Index(fields=["team", "status", "normalized_topic"], name="bk_gap_team_status_topic"),+ ]++ def __str__(self) -> str:+ return f"Gap: {self.topic[:60]} (ticket={self.ticket_id})"diff --git a/products/business_knowledge/backend/routes.py b/products/business_knowledge/backend/routes.pyindex 65128d5f2fc3..1a6380016ec3 100644--- a/products/business_knowledge/backend/routes.py+++ b/products/business_knowledge/backend/routes.py@@ -1,6 +1,10 @@from posthog.api.routing import RouterRegistry-from products.business_knowledge.backend.api import KnowledgeDocumentViewSet, KnowledgeSourceViewSet+from products.business_knowledge.backend.api import (+ KnowledgeDocumentViewSet,+ KnowledgeGapSuggestionViewSet,+ KnowledgeSourceViewSet,+)def register_routes(routers: RouterRegistry) -> None:@@ -16,3 +20,9 @@ def register_routes(routers: RouterRegistry) -> None:"environment_business_knowledge_documents",["team_id"],)+ routers.projects.register(+ r"business_knowledge/gap_suggestions",+ KnowledgeGapSuggestionViewSet,+ "environment_business_knowledge_gap_suggestions",+ ["team_id"],+ )diff --git a/products/business_knowledge/backend/tests/test_knowledge_gap_suggestion.py b/products/business_knowledge/backend/tests/test_knowledge_gap_suggestion.pynew file mode 100644index 000000000000..cf5f06f25267--- /dev/null+++ b/products/business_knowledge/backend/tests/test_knowledge_gap_suggestion.py@@ -0,0 +1,222 @@+import uuid++from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++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.models import GapStatus, KnowledgeGapSuggestion+++class TestUpsertKnowledgeGaps(BaseTest):+ def _ticket_id(self) -> str:+ return str(uuid.uuid4())++ def test_basic_upsert(self) -> None:+ tid = self._ticket_id()+ created = logic.upsert_knowledge_gaps(+ team_id=self.team.id,+ ticket_id=tid,+ topics=["How to configure webhooks", "Rate limiting"],+ ticket_type="how_to",+ outcome="escalated_no_reply",+ )+ assert created == 2+ assert KnowledgeGapSuggestion.objects.for_team(self.team.id).filter(ticket_id=tid).count() == 2++ def test_idempotent_under_retry(self) -> None:+ tid = self._ticket_id()+ topics = ["Billing FAQ"]+ logic.upsert_knowledge_gaps(self.team.id, tid, topics)+ logic.upsert_knowledge_gaps(self.team.id, tid, topics)+ assert KnowledgeGapSuggestion.objects.for_team(self.team.id).filter(ticket_id=tid).count() == 1++ def test_normalization(self) -> None:+ tid = self._ticket_id()+ logic.upsert_knowledge_gaps(self.team.id, tid, [" UPPERCASE Topic "])+ gap = KnowledgeGapSuggestion.objects.for_team(self.team.id).get(ticket_id=tid)+ assert gap.normalized_topic == "uppercase topic"+ assert gap.topic == "UPPERCASE Topic"++ @parameterized.expand(["", " ", "parse_failure"])+ def test_filters_noise(self, noise_topic: str) -> None:+ tid = self._ticket_id()+ created = logic.upsert_knowledge_gaps(self.team.id, tid, [noise_topic])+ assert created == 0++ def test_cross_team_isolation(self) -> None:+ other_org = Organization.objects.create(name="other_org")+ other_project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=other_org)+ other_team = Team.objects.create(id=other_project.id, project=other_project, organization=other_org)++ tid = self._ticket_id()+ logic.upsert_knowledge_gaps(self.team.id, tid, ["Shared topic"])+ logic.upsert_knowledge_gaps(other_team.id, tid, ["Shared topic"])++ assert KnowledgeGapSuggestion.objects.for_team(self.team.id).count() == 1+ assert KnowledgeGapSuggestion.objects.for_team(other_team.id).count() == 1+++class TestAggregateGapSuggestions(BaseTest):+ def test_groups_by_normalized_topic(self) -> None:+ for _ in range(3):+ logic.upsert_knowledge_gaps(self.team.id, str(uuid.uuid4()), ["Webhook setup"], ticket_type="how_to")+ logic.upsert_knowledge_gaps(self.team.id, str(uuid.uuid4()), ["Rate limits"])++ agg = logic.aggregate_gap_suggestions(self.team.id)+ topics = {a.normalized_topic: a.ticket_count for a in agg}+ assert topics["webhook setup"] == 3+ assert topics["rate limits"] == 1++ def test_only_pending(self) -> None:+ tid = str(uuid.uuid4())+ logic.upsert_knowledge_gaps(self.team.id, tid, ["Dismissed topic"])+ logic.set_gap_status(self.team.id, normalized_topic="dismissed topic", status=GapStatus.DISMISSED)++ agg = logic.aggregate_gap_suggestions(self.team.id)+ assert len(agg) == 0+++class TestSetGapStatus(BaseTest):+ def test_accept_cluster(self) -> None:+ for _ in range(2):+ logic.upsert_knowledge_gaps(self.team.id, str(uuid.uuid4()), ["Same topic"])++ updated = logic.set_gap_status(self.team.id, normalized_topic="same topic", status=GapStatus.ACCEPTED)+ assert updated == 2+ assert KnowledgeGapSuggestion.objects.for_team(self.team.id).filter(status=GapStatus.ACCEPTED).count() == 2++ def test_dismiss_single(self) -> None:+ tid = str(uuid.uuid4())+ logic.upsert_knowledge_gaps(self.team.id, tid, ["Topic A"])+ gap = KnowledgeGapSuggestion.objects.for_team(self.team.id).first()+ assert gap is not None+ logic.set_gap_status(self.team.id, suggestion_id=gap.id, status=GapStatus.DISMISSED)+ gap.refresh_from_db()+ assert gap.status == GapStatus.DISMISSED+++@patch("posthoganalytics.feature_enabled", return_value=True)+class TestKnowledgeGapSuggestionAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/business_knowledge/gap_suggestions/"++ def test_list_aggregated(self, _ff) -> None:+ for _ in range(2):+ logic.upsert_knowledge_gaps(self.team.id, str(uuid.uuid4()), ["Setup help"])+ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ results = data if isinstance(data, list) else data.get("results", data)+ assert len(results) == 1+ assert results[0]["ticket_count"] == 2++ def test_list_per_ticket(self, _ff) -> None:+ tid = str(uuid.uuid4())+ logic.upsert_knowledge_gaps(self.team.id, tid, ["Topic A", "Topic B"])+ response = self.client.get(f"{self.url}?ticket_id={tid}")+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ results = data if isinstance(data, list) else data.get("results", data)+ assert len(results) == 2++ def test_dismiss_action(self, _ff) -> None:+ tid = str(uuid.uuid4())+ logic.upsert_knowledge_gaps(self.team.id, tid, ["Dismiss me"])+ gap = KnowledgeGapSuggestion.objects.for_team(self.team.id).first()+ assert gap is not None+ response = self.client.post(f"{self.url}{gap.id}/dismiss/")+ assert response.status_code == status.HTTP_200_OK+ gap.refresh_from_db()+ assert gap.status == GapStatus.DISMISSED++ def test_accept_action(self, _ff) -> None:+ tid = str(uuid.uuid4())+ logic.upsert_knowledge_gaps(self.team.id, tid, ["Accept me"])+ gap = KnowledgeGapSuggestion.objects.for_team(self.team.id).first()+ assert gap is not None+ response = self.client.post(f"{self.url}{gap.id}/accept/", {}, format="json")+ assert response.status_code == status.HTTP_200_OK+ gap.refresh_from_db()+ assert gap.status == GapStatus.ACCEPTED++ def test_team_isolation(self, _ff) -> None:+ other_org = Organization.objects.create(name="other_org")+ other_project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=other_org)+ other_team = Team.objects.create(id=other_project.id, project=other_project, organization=other_org)+ logic.upsert_knowledge_gaps(other_team.id, str(uuid.uuid4()), ["Other team topic"])++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ results = data if isinstance(data, list) else data.get("results", data)+ assert len(results) == 0++ def test_aggregate_does_not_expose_ticket_ids(self, _ff) -> None:+ logic.upsert_knowledge_gaps(self.team.id, str(uuid.uuid4()), ["Leaky topic"])+ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ results = data if isinstance(data, list) else data.get("results", data)+ assert len(results) == 1+ assert "sample_ticket_ids" not in results[0]+++@patch("posthoganalytics.feature_enabled", return_value=True)+class TestKnowledgeGapSuggestionScopes(APIBaseTest):+ """A token must carry `ticket:read` to reach ticket-derived data via the per-ticket path."""++ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/business_knowledge/gap_suggestions/"+ self.ticket_id = str(uuid.uuid4())+ logic.upsert_knowledge_gaps(self.team.id, self.ticket_id, ["Topic A"])++ def _auth_with_pak(self, scopes: list[str]) -> None:+ key = self.create_personal_api_key_with_scopes(scopes)+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")++ def test_aggregate_allowed_with_business_knowledge_read_only(self, _ff) -> None:+ self._auth_with_pak(["business_knowledge:read"])+ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK++ def test_per_ticket_denied_without_ticket_read(self, _ff) -> None:+ self._auth_with_pak(["business_knowledge:read"])+ response = self.client.get(f"{self.url}?ticket_id={self.ticket_id}")+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_per_ticket_allowed_with_ticket_read(self, _ff) -> None:+ self._auth_with_pak(["business_knowledge:read", "ticket:read"])+ response = self.client.get(f"{self.url}?ticket_id={self.ticket_id}")+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ results = data if isinstance(data, list) else data.get("results", data)+ assert len(results) == 1++ def _first_gap_id(self) -> str:+ gap = KnowledgeGapSuggestion.objects.for_team(self.team.id).first()+ assert gap is not None+ return str(gap.id)++ @parameterized.expand(["accept", "dismiss"])+ def test_detail_action_denied_without_ticket_read(self, _ff, verb: str) -> None:+ gap_id = self._first_gap_id()+ self._auth_with_pak(["business_knowledge:write"])+ response = self.client.post(f"{self.url}{gap_id}/{verb}/", {}, format="json")+ assert response.status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand(["accept", "dismiss"])+ def test_detail_action_allowed_with_ticket_read(self, _ff, verb: str) -> None:+ gap_id = self._first_gap_id()+ self._auth_with_pak(["business_knowledge:write", "ticket:read"])+ response = self.client.post(f"{self.url}{gap_id}/{verb}/", {}, format="json")+ assert response.status_code == status.HTTP_200_OKdiff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.tsindex 98308e1bf52e..7d0c0457f0a0 100644--- a/products/business_knowledge/frontend/generated/api.schemas.ts+++ b/products/business_knowledge/frontend/generated/api.schemas.ts@@ -56,6 +56,64 @@ export interface KnowledgeSearchResultApi {readonly content: string}+export interface KnowledgeGapSuggestionApi {+ /** Unique identifier for this gap suggestion. */+ readonly id: string+ /** The ticket that surfaced this gap. */+ readonly ticket_id: string+ /** Raw topic the AI couldn't answer. */+ readonly topic: string+ /** Normalized cluster key for grouping. */+ readonly normalized_topic: string+ /** Ticket classification type. */+ readonly ticket_type: string+ /** Pipeline outcome that produced this gap. */+ readonly outcome: string+ /** Current status: pending, accepted, or dismissed. */+ readonly status: string+ /**+ * Knowledge source created to fill this gap.+ * @nullable+ */+ readonly resolved_source_id: string | null+ /** When this gap was first recorded. */+ readonly created_at: string+}++export interface PaginatedKnowledgeGapSuggestionListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: KnowledgeGapSuggestionApi[]+}++export interface GapActionApi {+ /**+ * Optional knowledge source to link when accepting.+ * @nullable+ */+ resolved_source_id?: string | null+}++export interface GapTopicActionApi {+ /** The normalized topic key identifying the gap cluster to act on. */+ normalized_topic: string+ /**+ * Optional knowledge source to link when accepting.+ * @nullable+ */+ resolved_source_id?: string | null+}++export interface GapTopicActionResultApi {+ /** The normalized topic cluster that was acted on. */+ readonly normalized_topic: string+ /** Number of gap rows whose status changed. */+ readonly updated: number+}+/*** * `text` - Text* * `url` - URL@@ -240,6 +298,21 @@ export type BusinessKnowledgeDocumentsSearchListParams = {rerank?: boolean}+export type BusinessKnowledgeGapSuggestionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * When provided, returns per-ticket gap rows instead of aggregated view. Requires `ticket:read` scope in addition to `business_knowledge:read`.+ */+ ticket_id?: string+}+export type BusinessKnowledgeSourcesListParams = {/*** Number of results to return per page.diff --git a/products/business_knowledge/frontend/generated/api.ts b/products/business_knowledge/frontend/generated/api.tsindex afffd9155921..c20c5dd1f53b 100644--- a/products/business_knowledge/frontend/generated/api.ts+++ b/products/business_knowledge/frontend/generated/api.ts@@ -11,12 +11,18 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {BusinessKnowledgeDocumentsSearchListParams,BusinessKnowledgeDocumentsWindowListParams,+ BusinessKnowledgeGapSuggestionsListParams,BusinessKnowledgeSourcesListParams,BusinessKnowledgeSourcesTextRetrieve200,CreateTextSourceApi,+ GapActionApi,+ GapTopicActionApi,+ GapTopicActionResultApi,KnowledgeDocumentWindowApi,+ KnowledgeGapSuggestionApi,KnowledgeSearchResultApi,KnowledgeSourceApi,+ PaginatedKnowledgeGapSuggestionListApi,PaginatedKnowledgeSourceListApi,PatchedUpdateTextSourceApi,} from './api.schemas'@@ -110,6 +116,136 @@ export const businessKnowledgeDocumentsSearchList = async (})}+export const getBusinessKnowledgeGapSuggestionsListUrl = (+ projectId: string,+ params?: BusinessKnowledgeGapSuggestionsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/business_knowledge/gap_suggestions/?${stringifiedParams}`+ : `/api/projects/${projectId}/business_knowledge/gap_suggestions/`+}++/**+ * Surfaces topics the support AI couldn't answer from the knowledge base.+ *+ * Two list shapes controlled by the ``ticket_id`` query param:+ * - **per-ticket** (``?ticket_id=<uuid>``): individual gap rows for that ticket.+ * - **aggregated** (no ``ticket_id``): gaps grouped by normalized topic with counts,+ * for the Business knowledge suggestions panel.+ */+export const businessKnowledgeGapSuggestionsList = async (+ projectId: string,+ params?: BusinessKnowledgeGapSuggestionsListParams,+ options?: RequestInit+): Promise<PaginatedKnowledgeGapSuggestionListApi> => {+ return apiMutator<PaginatedKnowledgeGapSuggestionListApi>(+ getBusinessKnowledgeGapSuggestionsListUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getBusinessKnowledgeGapSuggestionsAcceptCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/gap_suggestions/${id}/accept/`+}++/**+ * Surfaces topics the support AI couldn't answer from the knowledge base.+ *+ * Two list shapes controlled by the ``ticket_id`` query param:+ * - **per-ticket** (``?ticket_id=<uuid>``): individual gap rows for that ticket.+ * - **aggregated** (no ``ticket_id``): gaps grouped by normalized topic with counts,+ * for the Business knowledge suggestions panel.+ */+export const businessKnowledgeGapSuggestionsAcceptCreate = async (+ projectId: string,+ id: string,+ gapActionApi?: GapActionApi,+ options?: RequestInit+): Promise<KnowledgeGapSuggestionApi> => {+ return apiMutator<KnowledgeGapSuggestionApi>(getBusinessKnowledgeGapSuggestionsAcceptCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(gapActionApi),+ })+}++export const getBusinessKnowledgeGapSuggestionsDismissCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/business_knowledge/gap_suggestions/${id}/dismiss/`+}++/**+ * Surfaces topics the support AI couldn't answer from the knowledge base.+ *+ * Two list shapes controlled by the ``ticket_id`` query param:+ * - **per-ticket** (``?ticket_id=<uuid>``): individual gap rows for that ticket.+ * - **aggregated** (no ``ticket_id``): gaps grouped by normalized topic with counts,+ * for the Business knowledge suggestions panel.+ */+export const businessKnowledgeGapSuggestionsDismissCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<KnowledgeGapSuggestionApi> => {+ return apiMutator<KnowledgeGapSuggestionApi>(getBusinessKnowledgeGapSuggestionsDismissCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getBusinessKnowledgeGapSuggestionsAcceptTopicCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/business_knowledge/gap_suggestions/accept_topic/`+}++/**+ * Accept all pending suggestions for a normalized topic cluster.+ */+export const businessKnowledgeGapSuggestionsAcceptTopicCreate = async (+ projectId: string,+ gapTopicActionApi: GapTopicActionApi,+ options?: RequestInit+): Promise<GapTopicActionResultApi> => {+ return apiMutator<GapTopicActionResultApi>(getBusinessKnowledgeGapSuggestionsAcceptTopicCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(gapTopicActionApi),+ })+}++export const getBusinessKnowledgeGapSuggestionsDismissTopicCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/business_knowledge/gap_suggestions/dismiss_topic/`+}++/**+ * Dismiss all pending suggestions for a normalized topic cluster.+ */+export const businessKnowledgeGapSuggestionsDismissTopicCreate = async (+ projectId: string,+ gapTopicActionApi: GapTopicActionApi,+ options?: RequestInit+): Promise<GapTopicActionResultApi> => {+ return apiMutator<GapTopicActionResultApi>(getBusinessKnowledgeGapSuggestionsDismissTopicCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(gapTopicActionApi),+ })+}+export const getBusinessKnowledgeSourcesListUrl = (projectId: string, params?: BusinessKnowledgeSourcesListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/business_knowledge/frontend/generated/api.zod.ts b/products/business_knowledge/frontend/generated/api.zod.tsindex be8c0a86c6ca..e73f675a9ad4 100644--- a/products/business_knowledge/frontend/generated/api.zod.ts+++ b/products/business_knowledge/frontend/generated/api.zod.ts@@ -9,6 +9,34 @@*/import * as zod from 'zod'+/**+ * Surfaces topics the support AI couldn't answer from the knowledge base.+ *+ * Two list shapes controlled by the ``ticket_id`` query param:+ * - **per-ticket** (``?ticket_id=<uuid>``): individual gap rows for that ticket.+ * - **aggregated** (no ``ticket_id``): gaps grouped by normalized topic with counts,+ * for the Business knowledge suggestions panel.+ */+export const BusinessKnowledgeGapSuggestionsAcceptCreateBody = /* @__PURE__ */ zod.object({+ resolved_source_id: zod.uuid().nullish().describe('Optional knowledge source to link when accepting.'),+})++/**+ * Accept all pending suggestions for a normalized topic cluster.+ */+export const BusinessKnowledgeGapSuggestionsAcceptTopicCreateBody = /* @__PURE__ */ zod.object({+ normalized_topic: zod.string().describe('The normalized topic key identifying the gap cluster to act on.'),+ resolved_source_id: zod.uuid().nullish().describe('Optional knowledge source to link when accepting.'),+})++/**+ * Dismiss all pending suggestions for a normalized topic cluster.+ */+export const BusinessKnowledgeGapSuggestionsDismissTopicCreateBody = /* @__PURE__ */ zod.object({+ normalized_topic: zod.string().describe('The normalized topic key identifying the gap cluster to act on.'),+ resolved_source_id: zod.uuid().nullish().describe('Optional knowledge source to link when accepting.'),+})+export const businessKnowledgeSourcesCreateBodyNameMax = 255export const businessKnowledgeSourcesCreateBodyAlwaysIncludeDefault = falsediff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsxindex 490a77ba9058..718e324b0845 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, IconPencil, IconPlusSmall, IconRefresh, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'+import { IconBook, IconCheck, IconPencil, IconPlusSmall, IconRefresh, IconTrash, IconX } from '@posthog/icons'+import { LemonButton, LemonCard, LemonCollapse, LemonDialog, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'import { TZLabel } from 'lib/components/TZLabel'@@ -16,7 +16,7 @@ import { CreateKnowledgeSourceModal } from '../components/CreateKnowledgeSourceMimport { EditKnowledgeSourceModal } from '../components/EditKnowledgeSourceModal'import { RefreshStatusCell } from '../components/RefreshStatusCell'import { StatusTag } from '../components/StatusTag'-import { KnowledgeSource, businessKnowledgeLogic } from './businessKnowledgeLogic'+import { type AggregatedGap, KnowledgeSource, businessKnowledgeLogic } from './businessKnowledgeLogic'const REFRESH_INTERVAL_OPTIONS: RefreshIntervalOption[] = [{ value: 'manual', label: 'Manual only' },@@ -33,8 +33,10 @@ export const scene: SceneExport = {export function BusinessKnowledgeScene(): JSX.Element {const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')- const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds } = useValues(businessKnowledgeLogic)- const { openCreateModal, openEditModal, deleteSource, refreshSource } = useActions(businessKnowledgeLogic)+ const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds, gapSuggestions, gapSuggestionsLoading } =+ useValues(businessKnowledgeLogic)+ const { openCreateModal, openEditModal, deleteSource, refreshSource, acceptGapSuggestion, dismissGapSuggestion } =+ useActions(businessKnowledgeLogic)if (!isEnabled) {return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />@@ -47,7 +49,7 @@ export function BusinessKnowledgeScene(): JSX.Element {description="Upload text, public URLs, or files so PostHog AI can understand your business context, vision, and policies."resourceType={{ type: 'default_icon_type', forceIcon: <IconBook /> }}actions={- <LemonButton type="primary" icon={<IconPlusSmall />} onClick={openCreateModal}>+ <LemonButton type="primary" icon={<IconPlusSmall />} onClick={() => openCreateModal()}>Add source</LemonButton>}@@ -59,6 +61,15 @@ 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}@@ -187,3 +198,71 @@ 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 290b3b9c9e48..a0dc0f5dca63 100644--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts@@ -3,6 +3,7 @@ import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { getCurrentTeamId } from 'lib/utils/getAppContext'import {createFileSource,@@ -15,9 +16,20 @@ import {updateSource,} from '../api'import type { CreateUrlSourcePayload, RefreshIntervalValue, UpdateSourcePayload } from '../api'+import {+ businessKnowledgeGapSuggestionsAcceptTopicCreate,+ businessKnowledgeGapSuggestionsDismissTopicCreate,+ businessKnowledgeGapSuggestionsList,+} from '../generated/api'import type { KnowledgeSourceApi } from '../generated/api.schemas'import type { businessKnowledgeLogicType } from './businessKnowledgeLogicType'+export interface AggregatedGap {+ normalized_topic: string+ topic: string+ ticket_count: number+}+export type KnowledgeSource = KnowledgeSourceApiexport type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'@@ -101,7 +113,7 @@ function splitGlobs(raw: string): string[] {export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([path(['products', 'business_knowledge', 'businessKnowledgeLogic']),actions({- openCreateModal: true,+ openCreateModal: (prefillName?: string) => ({ prefillName }),closeCreateModal: true,setCreateTab: (tab: CreateTab) => ({ tab }),openEditModal: (source: KnowledgeSource) => ({ source }),@@ -109,6 +121,11 @@ 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: [@@ -139,6 +156,15 @@ 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: [@@ -161,15 +187,34 @@ 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()@@ -196,22 +241,23 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([always_include: false,} as UrlSourceFormValues,errors: validateUrl,- submit: async (values: UrlSourceFormValues) => {- const includeGlobs = splitGlobs(values.include_globs)+ submit: async (formValues: UrlSourceFormValues) => {+ const acceptTopic = values.acceptingGapTopic+ const includeGlobs = splitGlobs(formValues.include_globs)const payload: CreateUrlSourcePayload = {- name: values.name,- url: values.url,+ name: formValues.name,+ url: formValues.url,source_type: 'url',- crawl_mode: values.crawl_mode,- refresh_interval: values.refresh_interval,- always_include: values.always_include,- ...(values.crawl_mode !== 'single' && {+ crawl_mode: formValues.crawl_mode,+ refresh_interval: formValues.refresh_interval,+ always_include: formValues.always_include,+ ...(formValues.crawl_mode !== 'single' && {// Only send include_globs when the user explicitly set them;// otherwise the backend auto-derives scope from the entry URL path....(includeGlobs.length > 0 && { include_globs: includeGlobs }),- exclude_globs: splitGlobs(values.exclude_globs),- max_pages: values.max_pages,- max_depth: values.max_depth,+ exclude_globs: splitGlobs(formValues.exclude_globs),+ max_pages: formValues.max_pages,+ max_depth: formValues.max_depth,}),}try {@@ -219,6 +265,9 @@ 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()@@ -247,6 +296,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([if (!file) {return}+ const acceptTopic = values.acceptingGapTopicconst formData = new FormData()formData.append('name', name)formData.append('file', file)@@ -255,6 +305,9 @@ 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()@@ -444,6 +497,38 @@ 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: [@@ -458,5 +543,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([}),afterMount(({ actions }) => {actions.loadSources()+ actions.loadGapSuggestions()}),])diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yamlindex 5eab3ae1bf6e..bdd480b6b25f 100644--- a/products/business_knowledge/mcp/tools.yaml+++ b/products/business_knowledge/mcp/tools.yaml@@ -39,6 +39,21 @@ tools:for any question about the team's own product, policies, domain knowledge, or internal docs. Set rerank=truefor a listwise LLM rerank pass when top-result precision matters.feature_flag: product-business-knowledge+ business-knowledge-gap-suggestions-accept-create:+ operation: business_knowledge_gap_suggestions_accept_create+ enabled: false+ business-knowledge-gap-suggestions-accept-topic-create:+ operation: business_knowledge_gap_suggestions_accept_topic_create+ enabled: false+ business-knowledge-gap-suggestions-dismiss-create:+ operation: business_knowledge_gap_suggestions_dismiss_create+ enabled: false+ business-knowledge-gap-suggestions-dismiss-topic-create:+ operation: business_knowledge_gap_suggestions_dismiss_topic_create+ enabled: false+ business-knowledge-gap-suggestions-list:+ operation: business_knowledge_gap_suggestions_list+ enabled: falsebusiness-knowledge-sources-destroy:operation: business_knowledge_sources_destroyenabled: falsediff --git a/products/conversations/backend/temporal/__init__.py b/products/conversations/backend/temporal/__init__.pyindex 5ffc8561022a..07b4436552dc 100644--- a/products/conversations/backend/temporal/__init__.py+++ b/products/conversations/backend/temporal/__init__.py@@ -1,3 +1,6 @@+from products.conversations.backend.temporal.ai_reply.activities.persist_knowledge_gap import (+ support_persist_knowledge_gap_activity,+)from products.conversations.backend.temporal.coordinator import (SupportReplyCoordinatorWorkflow,support_collect_eligible_tickets_activity,@@ -31,6 +34,7 @@ ACTIVITIES = [support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_persist_knowledge_gap_activity,support_record_triage_activity,support_collect_eligible_tickets_activity,]diff --git a/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.py b/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.pynew file mode 100644index 000000000000..2d3962fe13c6--- /dev/null+++ b/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.py@@ -0,0 +1,53 @@+from __future__ import annotations++from temporalio import activity, workflow++from products.conversations.backend.temporal.ai_reply.schemas import PersistKnowledgeGapInput++# Guard non-deterministic imports so this module is safe to load inside the Temporal workflow+# sandbox. It's pulled in via the package `__init__` when the sandbox imports the workflow; an+# unguarded `import structlog` re-executes structlog (→ rich) in the sandbox and crashes+# workflow validation. Only the activity touches these at runtime.+with workflow.unsafe.imports_passed_through():+ import structlog++ from posthog.sync import database_sync_to_async+ from posthog.temporal.common.utils import close_db_connections++ from products.business_knowledge.backend.logic import upsert_knowledge_gaps++logger = structlog.get_logger(__name__)+++@close_db_connections+async def support_persist_knowledge_gap_activity(input: PersistKnowledgeGapInput) -> None:+ """Record knowledge gaps from the support pipeline as suggestions for the BK product."""+ if not input.missing:+ return+ created = await database_sync_to_async(_persist_sync, thread_sensitive=False)(+ input.team_id, input.ticket_id, input.missing, input.ticket_type, input.outcome+ )+ if created:+ logger.info(+ "support_reply: knowledge gaps recorded",+ team_id=input.team_id,+ ticket_id=input.ticket_id,+ created=created,+ )+++def _persist_sync(+ team_id: int,+ ticket_id: str,+ missing: list[str],+ ticket_type: str,+ outcome: str,+) -> int:+ return upsert_knowledge_gaps(+ team_id=team_id,+ ticket_id=ticket_id,+ topics=missing,+ ticket_type=ticket_type,+ outcome=outcome,+ )diff --git a/products/conversations/backend/temporal/ai_reply/schemas.py b/products/conversations/backend/temporal/ai_reply/schemas.pyindex 475b3727d0db..0d956dce65a3 100644--- a/products/conversations/backend/temporal/ai_reply/schemas.py+++ b/products/conversations/backend/temporal/ai_reply/schemas.py@@ -162,6 +162,15 @@ class ReviewReplyOutput:reason: str = ""+@dataclass+class PersistKnowledgeGapInput:+ team_id: int+ ticket_id: str+ missing: list[str] = field(default_factory=list)+ ticket_type: str = ""+ outcome: str = ""++class SupportReplySource(BaseModel):ref: str = Field(description="The citation reference: a chunk_id UUID or a documentation URL")excerpt: str = Field(description="The exact text from this source that supports the reply")diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.pyindex 3b80ae6a58ae..b67e2ed23e42 100644--- a/products/conversations/backend/temporal/pipeline.py+++ b/products/conversations/backend/temporal/pipeline.py@@ -9,6 +9,9 @@ from temporalio.common import RetryPolicyfrom products.conversations.backend.temporal.ai_reply.activities.build_context import support_build_context_activityfrom products.conversations.backend.temporal.ai_reply.activities.classify import support_classify_activityfrom products.conversations.backend.temporal.ai_reply.activities.draft import support_draft_activity+from products.conversations.backend.temporal.ai_reply.activities.persist_knowledge_gap import (+ support_persist_knowledge_gap_activity,+)from products.conversations.backend.temporal.ai_reply.activities.persist_reply import support_persist_reply_activityfrom products.conversations.backend.temporal.ai_reply.activities.record_triage import support_record_triage_activityfrom products.conversations.backend.temporal.ai_reply.activities.refine_queries import support_refine_queries_activity@@ -24,6 +27,7 @@ from products.conversations.backend.temporal.ai_reply.constants import (from products.conversations.backend.temporal.ai_reply.schemas import (ClassifyInput,DraftInput,+ PersistKnowledgeGapInput,PersistReplyInput,RecordTriageInput,RefineQueriesInput,@@ -101,6 +105,26 @@ class SupportReplyWorkflow:except Exception:workflow.logger.warning("support_reply: failed to record triage", status=patch.get("status"))+ async def _persist_gaps(gap_missing: list[str], gap_ticket_type: str, gap_outcome: str) -> None:+ """Best-effort: record knowledge gaps without breaking the pipeline."""+ if not gap_missing:+ return+ try:+ await workflow.execute_activity(+ support_persist_knowledge_gap_activity,+ PersistKnowledgeGapInput(+ team_id=team_id,+ ticket_id=ticket_id,+ missing=gap_missing,+ ticket_type=gap_ticket_type,+ outcome=gap_outcome,+ ),+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ except Exception:+ workflow.logger.warning("support_reply: failed to persist knowledge gaps")+# Build contextctx_output = await workflow.execute_activity(support_build_context_activity,@@ -292,6 +316,8 @@ class SupportReplyWorkflow:start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),)+ if validate_output.missing:+ await _persist_gaps(validate_output.missing, ticket_type, "persisted")outcome = {"result": "persisted","ticket_type": ticket_type,@@ -299,6 +325,7 @@ class SupportReplyWorkflow:"diagnostics_allowed": ctx_output.diagnostics_allowed,"confidence": validate_output.confidence,"attempts": attempt + 1,+ "missing": validate_output.missing,}return f"persisted (confidence={validate_output.confidence:.2f}, attempts={attempt + 1})"@@ -351,6 +378,8 @@ class SupportReplyWorkflow:start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),)+ if best_missing:+ await _persist_gaps(best_missing, ticket_type, "escalated_with_best")outcome = {"result": "escalated_with_best","ticket_type": ticket_type,@@ -358,15 +387,19 @@ class SupportReplyWorkflow:"diagnostics_allowed": ctx_output.diagnostics_allowed,"confidence": best_confidence,"attempts": MAX_ATTEMPTS,+ "missing": best_missing,}return f"escalated_with_best (confidence={best_confidence:.2f})"+ if best_missing:+ await _persist_gaps(best_missing, ticket_type, "escalated_no_reply")outcome = {"result": "escalated_no_reply","ticket_type": ticket_type,"needs_diagnostics": needs_diagnostics,"diagnostics_allowed": ctx_output.diagnostics_allowed,"attempts": MAX_ATTEMPTS,+ "missing": best_missing,}return "escalated_no_reply"finally:diff --git a/products/conversations/frontend/scenes/ticket/AIPanel.tsx b/products/conversations/frontend/scenes/ticket/AIPanel.tsxindex b99a3aaba759..49a2357b5d40 100644--- a/products/conversations/frontend/scenes/ticket/AIPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/AIPanel.tsx@@ -1,9 +1,13 @@-import { LemonCollapse, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'+import { IconX } from '@posthog/icons'+import { LemonButton, 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,@@ -12,6 +16,9 @@ import {interface AIPanelProps {aiTriage?: AITriage+ knowledgeGaps?: KnowledgeGapSuggestion[]+ knowledgeGapsLoading?: boolean+ onDismissGap?: (suggestionId: string) => void}function AITriageHeaderTag({ aiTriage }: { aiTriage?: AITriage }): JSX.Element | null {@@ -31,8 +38,9 @@ function AITriageHeaderTag({ aiTriage }: { aiTriage?: AITriage }): JSX.Element |return null}-export function AIPanel({ aiTriage }: AIPanelProps): JSX.Element {+export function AIPanel({ aiTriage, knowledgeGaps, knowledgeGapsLoading, onDismissGap }: AIPanelProps): JSX.Element {const hasData = aiTriage && aiTriage.status+ const pendingGaps = knowledgeGaps?.filter((g) => g.status === 'pending') ?? []return (<LemonCollapse@@ -115,6 +123,50 @@ export function AIPanel({ aiTriage }: AIPanelProps): JSX.Element {<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 c773a29d3a01..1b60d6727a49 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -79,6 +79,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemdraftContent,draftIsPrivate,snoozedUntil,+ knowledgeGaps,+ knowledgeGapsLoading,} = useValues(logic)const {setStatus,@@ -91,6 +93,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemloadOlderMessages,setDraftContent,setDraftIsPrivate,+ dismissKnowledgeGap,} = useActions(logic)const { user } = useValues(userLogic)@@ -406,7 +409,14 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem{user?.is_staff && ticket && <StaffActionsPanel />}{/* AI Triage Panel */}- {aiSuggestionsEnabled && ticket && <AIPanel aiTriage={ticket.ai_triage} />}+ {aiSuggestionsEnabled && ticket && (+ <AIPanel+ aiTriage={ticket.ai_triage}+ knowledgeGaps={knowledgeGaps}+ knowledgeGapsLoading={knowledgeGapsLoading}+ onDismissGap={dismissKnowledgeGap}+ />+ )}{ticket?.channel_source === 'widget' && (<>diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 701815cbaff3..7e585844e6fb 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -6,6 +6,7 @@ import { beforeUnload, router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'+import { getCurrentTeamId } from 'lib/utils/getAppContext'import { urls } from 'scenes/urls'import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'@@ -17,9 +18,14 @@ import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'import type { CommentType, PersonType } from '~/types'import { PropertyFilterType, PropertyOperator, Region } from '~/types'+import {+ businessKnowledgeGapSuggestionsDismissCreate,+ businessKnowledgeGapSuggestionsList,+} from 'products/business_knowledge/frontend/generated/api'+import type { TicketAssignee } from '../../components/Assignee'import { supportTicketCounterLogic } from '../../supportTicketCounterLogic'-import type { ChatMessage, Ticket, TicketPriority, TicketStatus } from '../../types'+import type { ChatMessage, KnowledgeGapSuggestion, Ticket, TicketPriority, TicketStatus } from '../../types'import { supportTicketsSceneLogic } from '../tickets/supportTicketsSceneLogic'import type { supportTicketSceneLogicType } from './supportTicketSceneLogicType'@@ -153,6 +159,10 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([loadPerson: true,loadPreviousTickets: true,+ // Knowledge gap suggestions+ loadKnowledgeGaps: true,+ dismissKnowledgeGap: (suggestionId: string) => ({ suggestionId }),+// Draft message state (persists across tab switches)setDraftContent: (content: JSONContent | null) => ({ content }),setDraftIsPrivate: (isPrivate: boolean) => ({ isPrivate }),@@ -216,6 +226,26 @@ 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 []+ }+ },+ },+ ],})),reducers({ticket: [@@ -439,6 +469,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([// Load session context dataactions.loadPerson()+ actions.loadKnowledgeGaps()// Refresh the unread count since viewing a ticket marks it as readsupportTicketCounterLogic.findMounted()?.actions.refreshCount()@@ -570,6 +601,14 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([actions.setMessageSending(false)}},+ dismissKnowledgeGap: async ({ suggestionId }) => {+ try {+ await businessKnowledgeGapSuggestionsDismissCreate(String(getCurrentTeamId()), suggestionId)+ actions.loadKnowledgeGaps()+ } catch {+ lemonToast.error('Failed to dismiss suggestion')+ }+ },})),afterMount(({ actions, props }) => {if (props.id !== 'new') {diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex ec3e4c4f11d9..2cab01397e76 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -47,6 +47,21 @@ export interface AITriage {finished_at?: stringworkflow_id?: stringrun_id?: string+ missing?: string[]+}++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}export interface TicketViewFilters {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9914c54dadf0..6a5d383622ff 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24030,6 +24030,31 @@ export namespace Schemas {deleted: boolean;}+ export interface GapAction {+ /**+ * Optional knowledge source to link when accepting.+ * @nullable+ */+ resolved_source_id?: string | null;+ }++ export interface GapTopicAction {+ /** The normalized topic key identifying the gap cluster to act on. */+ normalized_topic: string;+ /**+ * Optional knowledge source to link when accepting.+ * @nullable+ */+ resolved_source_id?: string | null;+ }++ export interface GapTopicActionResult {+ /** The normalized topic cluster that was acted on. */+ readonly normalized_topic: string;+ /** Number of gap rows whose status changed. */+ readonly updated: number;+ }+export type GenerateRequestStepsItem = { [key: string]: unknown };export interface GenerateRequest {@@ -27680,6 +27705,30 @@ export namespace Schemas {readonly document_title: string;}+ export interface KnowledgeGapSuggestion {+ /** Unique identifier for this gap suggestion. */+ readonly id: string;+ /** The ticket that surfaced this gap. */+ readonly ticket_id: string;+ /** Raw topic the AI couldn't answer. */+ readonly topic: string;+ /** Normalized cluster key for grouping. */+ readonly normalized_topic: string;+ /** Ticket classification type. */+ readonly ticket_type: string;+ /** Pipeline outcome that produced this gap. */+ readonly outcome: string;+ /** Current status: pending, accepted, or dismissed. */+ readonly status: string;+ /**+ * Knowledge source created to fill this gap.+ * @nullable+ */+ readonly resolved_source_id: string | null;+ /** When this gap was first recorded. */+ readonly created_at: string;+ }+/*** One ranked chunk from a business knowledge search.*@@ -31585,6 +31634,15 @@ export namespace Schemas {results: IntervieweeContext[];}+ export interface PaginatedKnowledgeGapSuggestionList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: KnowledgeGapSuggestion[];+ }+export interface PaginatedKnowledgeSourceList {count: number;/** @nullable */@@ -60101,6 +60159,21 @@ export namespace Schemas {rerank?: boolean;};+ export type BusinessKnowledgeGapSuggestionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * When provided, returns per-ticket gap rows instead of aggregated view. Requires `ticket:read` scope in addition to `business_knowledge:read`.+ */+ ticket_id?: string;+ };+export type BusinessKnowledgeSourcesListParams = {/*** Number of results to return per page.diff --git a/tach.toml b/tach.tomlindex 1e4e3a70dc4a..13e955e701d2 100644--- a/tach.toml+++ b/tach.toml@@ -111,7 +111,6 @@ depends_on = ["products.tracing","products.user_interviews","products.mcp_analytics",- "products.warehouse_sources_queue","products.web_analytics","products.workflows","products.actions",@@ -203,8 +202,7 @@ layer = "modules"path = "products.conversations"depends_on = ["ee",- "posthog",- "products.posthog_ai", "products.tasks", "products.business_knowledge",+ "posthog", "products.tasks", "products.business_knowledge",]layer = "modules"@@ -262,7 +260,6 @@ depends_on = ["ee","posthog","products.cdp",- "products.dashboards","products.data_modeling","products.revenue_analytics", "products.warehouse_sources", "products.data_tools", "products.batch_exports",]@@ -541,7 +538,6 @@ depends_on = ["products.cdp","products.exports","products.signals",- "products.workflows",]layer = "modules"@@ -977,7 +973,7 @@ from = [[[modules]]path = "products.engineering_analytics"-depends_on = ["posthog", "products.warehouse_sources", "products.data_warehouse"]+depends_on = ["posthog", "products.warehouse_sources"]layer = "modules"[[interfaces]]