Skip to content

: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.

feat(business-knowledge): add libraries for scoped search (#117130)

Alex V801aa0abae83
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 9b0a6b93c7b4..2ebac67c25cf 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -262,6 +262,9 @@ rules:
|KnowledgeDocument
|KnowledgeGapSuggestion
|KnowledgeLearningRun
+ |KnowledgeLibrary
+ |KnowledgeLibraryRepository
+ |KnowledgeLibrarySource
|KnowledgeSource
|PlaygroundChat
|PlaygroundTurn
@@ -727,6 +730,9 @@ rules:
|KnowledgeDocument
|KnowledgeGapSuggestion
|KnowledgeLearningRun
+ |KnowledgeLibrary
+ |KnowledgeLibraryRepository
+ |KnowledgeLibrarySource
|KnowledgeSource
|PlaygroundChat
|PlaygroundTurn
diff --git a/docs/published/docs/business-knowledge/learn-from-support.mdx b/docs/published/docs/business-knowledge/learn-from-support.mdx
index 1abb13d75595..e73ba4c8fb90 100644
--- a/docs/published/docs/business-knowledge/learn-from-support.mdx
+++ b/docs/published/docs/business-knowledge/learn-from-support.mdx
@@ -71,6 +71,9 @@ Private notes, customer messages, deleted replies, and AI replies are not used.
Each reply is checked for reusable information, personal data, secrets, and overlap with existing Business knowledge.
Accepted answers are added as their own learned sources, named after the topic.
+Each new learned source also joins a library named Learned.
+If you take a source out of Learned, it stays out.
+Deleting Learned does not delete the sources. The next new learned source creates the library again and joins only itself.
You can open, edit, or delete a learned source.
PostHog does not change a source that already exists when it analyzes the same ticket again.
diff --git a/docs/published/docs/business-knowledge/start.mdx b/docs/published/docs/business-knowledge/start.mdx
index 508387f2e2c2..2737ea950efb 100644
--- a/docs/published/docs/business-knowledge/start.mdx
+++ b/docs/published/docs/business-knowledge/start.mdx
@@ -35,6 +35,19 @@ A URL source can refresh on a schedule: every hour, every 6 hours, every day, or
Text and file sources do not refresh on a schedule.
+## Libraries
+
+A library limits search to the sources and repositories you put in it.
+A source can be in more than one library, or in none.
+**All** searches every ready source.
+**Unfiled** shows sources that are in no library.
+
+Deleting a library removes only that grouping.
+The sources, documents, and selected repositories stay.
+
+Pass `library_id` to document search, repository search, and file read when you want one library.
+Leave it out to search the whole project.
+
## Playground
The **Playground** tab asks a question against your sources and shows the answer.
diff --git a/ee/hogai/tools/search.py b/ee/hogai/tools/search.py
index b61814618ef2..352b3911b6bb 100644
--- a/ee/hogai/tools/search.py
+++ b/ee/hogai/tools/search.py
@@ -189,7 +189,7 @@ class SearchTool(MaxTool):
await database_sync_to_async(posthoganalytics.capture)(
distinct_id=str(self._team.uuid),
event="business knowledge searched",
- properties={"result_count": len(results), "surface": "posthog_ai"},
+ properties={"result_count": len(results), "surface": "posthog_ai", "library_scoped": False},
groups=groups(team=self._team),
)
except Exception:
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 31ea9c9631d5..c5d6c83c0c4d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9387,21 +9387,21 @@ snapshots:
scenes-app-business-knowledge-playground--saved-chat--light:
hash: v1.k794b7964.f2388b5b836e5f04fe2f7c94b51a2e7c8356bd4806cf135c1ee115951b43d2ec.syOurGASFyjDfm1O0BrEprdwtoTrpOLtWcEeMz_cYAo
scenes-app-businessknowledge-knowledgesourcedetails--file--dark:
- hash: v1.k794b7964.6fce4fcb3dbf4153e1803231c31de01442077368bc563d1e461374db36c8de54.OV6BI-ljYwtd1ZvU0lxpX70ZH8YDfYqq2kbILbe_dH4
+ hash: v1.k794b7964.aa678ca573339c3280899906358dfc7a66cd6a80092cd0e85caf9eb2e9ada21d.KntYpsaUMk50Qp1knzQP00-1cOUiZGmFF7GnkPAlrwc
scenes-app-businessknowledge-knowledgesourcedetails--file--light:
- hash: v1.k794b7964.ba7083911c27961d1050951d8f15f388cb91e880402b7c7fd701fbccef66d07c.b8CnCawVdQo9b5DcE4MIGqmYoeHTiee8kDNxPwi4vds
+ hash: v1.k794b7964.b02a6a3314815609a262fe286a3325753787f94c48b2f8ecbb5129b1d6e5a58c.PePKPOx7YJu1IBEULv7Dl08ovXwdmWsAtctjnx4o1Fw
scenes-app-businessknowledge-knowledgesourcedetails--learned--dark:
- hash: v1.k794b7964.c30245544fe59122dd4dcdd784acb6938af94ed99bb5093072804961686147d5.KhpS0OJ20syyeinctRlJE40zjmN8xuDCYBjXWm9kdZk
+ hash: v1.k794b7964.cdc310b576da080ddacdeb252a62a7f07d3ace9d62cde4a92eea33051b044d93.NcU6fKglObVKs-Pxsmv_rLaVFxtANu7qXan3uBAMSUA
scenes-app-businessknowledge-knowledgesourcedetails--learned--light:
- hash: v1.k794b7964.15e551ed8e0c09c8a8117df3ea29fb333b125af787e0d3f2aa43c0c44a9e846e.KLGmpYF8efOXI89n4hoMgEmMlTf48wNk96WBzpJiQdw
+ hash: v1.k794b7964.68e69b09dcf247ad7caa2f3e4aa6fd86b2462ae47cda53747e77c1ce0c9aa837.LfEjX8uOEOQapOPtn9vPKIRY9AP7IgOacws281YC_8o
scenes-app-businessknowledge-knowledgesourcedetails--text--dark:
- hash: v1.k794b7964.f16ff52a8628939bb64ec44713155455d9c5bfab9bdc06d81fed67f55f29d75e.ltD-2rSDPPvEVCEPb9MjpGiCCeUnAicC-lYoC2GShuM
+ hash: v1.k794b7964.29647f45a35e7b946356f875cb12f0050b7341c79de9c594041ba179c3b1b2ad.vBSP75e-WC0tTQVTrY_8pQHYR3RtmzLBEz-5HmxSTrQ
scenes-app-businessknowledge-knowledgesourcedetails--text--light:
- hash: v1.k794b7964.db5144bba913475024aceaac85922bf9ad7f4f6d619bd99bc23deffa6cb1564a.tSwwIvqtNg2OLxdpOl-nijCWNhFX0g55gRKK6Ntyceg
+ hash: v1.k794b7964.63896b2de9bb688e8e0dab0d4093780d461ae28926e597340528494ca64fb7bf.-Pf5Cyy7KR8gZeQHEjzKq_Tc2KELUVsIxZ5Azmx5Svw
scenes-app-businessknowledge-knowledgesourcedetails--url--dark:
- hash: v1.k794b7964.d0914f08041ecd372a0552e1a5345feebf055db15315a2ce9d31d86e374c888c.A5mzE5WueezZmwuekpiPiRe7Y-avmS9-NHyTdOm3Sx8
+ hash: v1.k794b7964.95899d6187248f5808c9a0ddd62f1555bbd7e3a4a57c9f7eb358b2e598282fe4.bulr2j8nkzBDjJUKawiBh9WJH7GukHHdMnOsh0gWl_k
scenes-app-businessknowledge-knowledgesourcedetails--url--light:
- hash: v1.k794b7964.9758a1ea2f664dc94c5a1395a285cde271db374a797c5c2e95efa4053ed52285.moGQ7fT6k--YLwPyIz-h2dRnpCHNQyRxHikh1nnLo7k
+ hash: v1.k794b7964.f26912eaaf3afadc2a849dccfc005013719c047db90c73aee39ad1095c44942e.1Ek0lPyML_zXAOwlqhkGNx_iEqWLUoycdxoX0ZSSGTc
scenes-app-businessknowledge-knowledgesourcenamecell--learned-from-ticket--dark:
hash: v1.k794b7964.a46d4d71b7c29d97eb5e21a51ea6f3e094057423f4ba8d4056478f8dee07511d.Mz_2JgSjfjfty0b5EX1bU9eBPi9g1Ijhfs0Sl6L9MLM
scenes-app-businessknowledge-knowledgesourcenamecell--learned-from-ticket--light:
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 20fe6a978e73..f68cab3923cd 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6258,6 +6258,8 @@ export enum ActivityScope {
LOGS_ALERT_CONFIGURATION = 'LogsAlertConfiguration',
PRODUCT_TOUR = 'ProductTour',
TICKET = 'Ticket',
+ KNOWLEDGE_SOURCE = 'KnowledgeSource',
+ KNOWLEDGE_LIBRARY = 'KnowledgeLibrary',
INSTANCE_SETTING = 'InstanceSetting',
SIGNAL_SCOUT_CONFIG = 'SignalScoutConfig',
SIGNAL_TEAM_CONFIG = 'SignalTeamConfig',
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index fecf916fed07..cee1f7f032c2 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -123,6 +123,8 @@ ActivityScope = Literal[
"DashboardWidget",
"ProductTour",
"Ticket",
+ "KnowledgeSource",
+ "KnowledgeLibrary",
"InstanceSetting",
"SignalReport",
"SignalScoutConfig",
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index a277dffbcc24..9847e76dad43 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -26,6 +26,7 @@ model_activity:products.alerts.backend.activity_logging.handle_alert_subscriptio
model_activity:products.alerts.backend.activity_logging.handle_threshold_change
model_activity:products.annotations.backend.activity_logging.handle_annotation_change
model_activity:products.batch_exports.backend.activity_logging.handle_batch_export_change
+model_activity:products.business_knowledge.backend.signals.handle_knowledge_library_change
model_activity:products.business_knowledge.backend.signals.handle_knowledge_source_change
model_activity:products.cross_project_dashboards.backend.activity_logging.handle_cross_project_dashboard_change
model_activity:products.customer_analytics.backend.activity_logging.handle_account_view_change
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index ed83afed4d5f..06440d4bc118 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -105,6 +105,8 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.autoresearch.backend.presentation.views.views.AutoresearchTrainingRunViewSet",
"products.batch_exports.backend.presentation.views.batch_export.runs.BatchExportRunViewSet",
"products.batch_exports.backend.presentation.views.file_download.FileDownloadBatchExportOnDemandViewSet",
+ # Lists at most MAX_LIBRARIES_PER_TEAM (100) libraries, so it has no pages.
+ "products.business_knowledge.backend.api.libraries.KnowledgeLibraryViewSet",
"products.business_knowledge.backend.api.playground.BusinessKnowledgePlaygroundChatViewSet",
"products.business_knowledge.backend.api.views.KnowledgeGapSuggestionViewSet",
"products.business_knowledge.backend.api.views.KnowledgeSourceViewSet",
diff --git a/products/business_knowledge/backend/api/__init__.py b/products/business_knowledge/backend/api/__init__.py
index 6f739959d821..fe5c409c358e 100644
--- a/products/business_knowledge/backend/api/__init__.py
+++ b/products/business_knowledge/backend/api/__init__.py
@@ -1,3 +1,4 @@
+from .libraries import KnowledgeLibraryViewSet
from .playground import BusinessKnowledgePlaygroundChatViewSet
from .repositories import BusinessKnowledgeRepositoriesViewSet
from .sandbox import BusinessKnowledgeSandboxViewSet
@@ -11,5 +12,6 @@ __all__ = [
"BusinessKnowledgeSettingsViewSet",
"KnowledgeDocumentViewSet",
"KnowledgeGapSuggestionViewSet",
+ "KnowledgeLibraryViewSet",
"KnowledgeSourceViewSet",
]
diff --git a/products/business_knowledge/backend/api/libraries.py b/products/business_knowledge/backend/api/libraries.py
new file mode 100644
index 000000000000..12c97f79c318
--- /dev/null
+++ b/products/business_knowledge/backend/api/libraries.py
@@ -0,0 +1,193 @@
+from functools import cached_property
+from typing import Any, cast
+from uuid import UUID
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db import transaction
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import exceptions, status
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.viewsets import ViewSet
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.user import User
+from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission
+from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottle
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+from ..github_repos import has_github_repos_feature_flag, selected_repositories
+from ..libraries import (
+ LibraryNotFound,
+ LibraryRejected,
+ create_library,
+ delete_library,
+ get_library,
+ list_libraries,
+ rename_library,
+ replace_library_repos,
+ replace_library_sources,
+ visible_repos,
+)
+from ..models import KnowledgeLibrary
+from .library_serializers import (
+ KnowledgeLibraryCreateSerializer,
+ KnowledgeLibrarySerializer,
+ KnowledgeLibraryUpdateSerializer,
+)
+from .settings import CanonicalTeamTokenPermission, canonical_user_access_control
+
+_READ_ACTIONS = frozenset({"list", "retrieve"})
+_WRITE_ACTIONS = frozenset({"create", "partial_update", "destroy"})
+
+
+class KnowledgeLibraryViewSet(TeamAndOrgViewSetMixin, ViewSet):
+ scope_object = "business_knowledge"
+ # A library is project-wide, not an access-controlled object. Without this flag, editor
+ # access to one source passes the list check for a member whose resource-level access is "none".
+ requires_resource_level_access = True
+ permission_classes = [
+ IsAuthenticated,
+ APIScopePermission,
+ PostHogFeatureFlagPermission,
+ CanonicalTeamTokenPermission,
+ ]
+ posthog_feature_flag = "product-business-knowledge"
+ throttle_classes = [BurstRateThrottle, SustainedRateThrottle]
+ pagination_class = None
+
+ @cached_property
+ def user_access_control(self) -> UserAccessControl:
+ # Libraries belong to the parent project, so its grants decide for every environment.
+ return canonical_user_access_control(self)
+
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
+ if self.action in _WRITE_ACTIONS:
+ return ["business_knowledge:write"]
+ if self.action in _READ_ACTIONS:
+ return ["business_knowledge:read"]
+ return None
+
+ @validated_request(
+ query_serializer=None,
+ responses={200: OpenApiResponse(response=KnowledgeLibrarySerializer(many=True))},
+ summary="List business knowledge libraries",
+ description="Libraries in this project. The default library is first.",
+ operation_id="business_knowledge_libraries_list",
+ )
+ def list(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ libraries = list_libraries(self.team_id)
+ repos = visible_repos(self.team_id, [library.id for library in libraries], self._allowlist())
+ return Response(
+ KnowledgeLibrarySerializer(
+ [_library_payload(library, repos.get(library.id, [])) for library in libraries],
+ many=True,
+ ).data
+ )
+
+ @validated_request(
+ request_serializer=KnowledgeLibraryCreateSerializer,
+ responses={201: OpenApiResponse(response=KnowledgeLibrarySerializer)},
+ summary="Create a business knowledge library",
+ operation_id="business_knowledge_libraries_create",
+ )
+ def create(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ try:
+ library = create_library(self.team_id, request.validated_data["name"])
+ except LibraryRejected as exc:
+ raise exceptions.ValidationError(exc.errors) from exc
+ return Response(self._one(library), status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ responses={200: KnowledgeLibrarySerializer},
+ summary="Get a business knowledge library",
+ operation_id="business_knowledge_libraries_retrieve",
+ )
+ def retrieve(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ return Response(self._one(self._get(pk)))
+
+ @validated_request(
+ request_serializer=KnowledgeLibraryUpdateSerializer,
+ responses={200: OpenApiResponse(response=KnowledgeLibrarySerializer)},
+ summary="Rename a library or replace its sources and repositories",
+ description=(
+ "Send only the fields you want to change. `source_ids` replaces every source in the library. "
+ "`repos` replaces this environment's repositories and leaves repositories that only another environment allows."
+ ),
+ operation_id="business_knowledge_libraries_partial_update",
+ )
+ def partial_update(self, request: ValidatedRequest, pk: str, **kwargs: Any) -> Response:
+ library_id = _parse_library_id(pk)
+ data = request.validated_data
+ if "repos" in data:
+ user = cast(User, request.user)
+ if not has_github_repos_feature_flag(self.team, str(user.distinct_id)):
+ raise exceptions.PermissionDenied(detail="GitHub repositories are not available for this project.")
+ allowlist = self._allowlist() if "repos" in data else set()
+ try:
+ with transaction.atomic():
+ library = get_library(self.team_id, library_id)
+ if "name" in data:
+ library = rename_library(self.team_id, library.id, data["name"])
+ if "source_ids" in data:
+ library = replace_library_sources(self.team_id, library.id, data["source_ids"])
+ if "repos" in data:
+ library = replace_library_repos(
+ self.team_id,
+ library.id,
+ data["repos"],
+ environment_allowlist=allowlist,
+ )
+ except LibraryNotFound:
+ raise exceptions.NotFound() from None
+ except LibraryRejected as exc:
+ raise exceptions.ValidationError(exc.errors) from exc
+ return Response(self._one(library))
+
+ @extend_schema(
+ responses={204: None},
+ summary="Delete a business knowledge library",
+ description="Removes the library and its links. Sources, documents, and selected repositories stay.",
+ operation_id="business_knowledge_libraries_destroy",
+ )
+ def destroy(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ try:
+ delete_library(self.team_id, _parse_library_id(pk))
+ except LibraryNotFound:
+ raise exceptions.NotFound() from None
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ def _get(self, pk: str) -> KnowledgeLibrary:
+ try:
+ return get_library(self.team_id, _parse_library_id(pk))
+ except LibraryNotFound:
+ raise exceptions.NotFound() from None
+
+ def _one(self, library: KnowledgeLibrary) -> dict[str, Any]:
+ repos = visible_repos(self.team_id, [library.id], self._allowlist()).get(library.id, [])
+ return KnowledgeLibrarySerializer(_library_payload(library, repos)).data
+
+ def _allowlist(self) -> set[str]:
+ _, repos = selected_repositories(self.team)
+ return set(repos)
+
+
+def _parse_library_id(pk: str) -> UUID:
+ try:
+ return UUID(pk)
+ except (ValueError, DjangoValidationError):
+ raise exceptions.NotFound() from None
+
+
+def _library_payload(library: KnowledgeLibrary, repos: list[str]) -> dict[str, Any]:
+ return {
+ "id": library.id,
+ "name": library.name,
+ "is_default": library.is_default,
+ "source_count": getattr(library, "source_count", 0),
+ "repos": repos,
+ }
diff --git a/products/business_knowledge/backend/api/library_serializers.py b/products/business_knowledge/backend/api/library_serializers.py
new file mode 100644
index 000000000000..a6fe56b87bc4
--- /dev/null
+++ b/products/business_knowledge/backend/api/library_serializers.py
@@ -0,0 +1,40 @@
+from rest_framework import serializers
+
+
+class KnowledgeLibrarySerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Library id.")
+ name = serializers.CharField(help_text="Library name. Unique in this project, ignoring case.")
+ is_default = serializers.BooleanField(
+ help_text="True for the library new learned sources join. There is at most one."
+ )
+ source_count = serializers.IntegerField(help_text="How many sources are in this library.")
+ repos = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Selected repositories in this library that this environment is allowed to read.",
+ )
+
+
+class KnowledgeLibraryCreateSerializer(serializers.Serializer):
+ name = serializers.CharField(max_length=255, help_text="Name for the new library.")
+
+
+class KnowledgeLibraryUpdateSerializer(serializers.Serializer):
+ name = serializers.CharField(max_length=255, required=False, help_text="New name. Omit to keep the current name.")
+ source_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ help_text="Replaces every source in this library. Omit to leave sources unchanged. An empty list removes them all.",
+ )
+ repos = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ help_text=(
+ "Replaces this environment's repositories in the library. "
+ "Omit to leave them unchanged. Repositories only another environment allows stay."
+ ),
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ if not attrs:
+ raise serializers.ValidationError("Provide at least one of `name`, `source_ids`, or `repos`.")
+ return attrs
diff --git a/products/business_knowledge/backend/api/repositories.py b/products/business_knowledge/backend/api/repositories.py
index 78c9b63a7661..52333247f40f 100644
--- a/products/business_knowledge/backend/api/repositories.py
+++ b/products/business_knowledge/backend/api/repositories.py
@@ -26,6 +26,7 @@ from products.business_knowledge.backend.github_repos import (
search_repositories,
select_github_repos,
)
+from products.business_knowledge.backend.libraries import LibraryNotFound, get_library
from .repository_serializers import (
RepositoryConnectionSerializer,
@@ -163,11 +164,14 @@ class BusinessKnowledgeRepositoriesViewSet(TeamAndOrgViewSetMixin, ViewSet):
required_scopes=["business_knowledge:read"],
)
def search(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ library_id = request.validated_query_data.get("library_id")
+ self._require_library(library_id)
outcome = search_repositories(
self.team,
cast(User, request.user),
request.validated_query_data["query"],
request.validated_query_data.get("repo") or None,
+ library_id=library_id,
)
return Response(RepositorySearchResponseSerializer(_search_payload(outcome)).data)
@@ -189,14 +193,25 @@ class BusinessKnowledgeRepositoriesViewSet(TeamAndOrgViewSetMixin, ViewSet):
required_scopes=["business_knowledge:read"],
)
def read_file(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ library_id = request.validated_query_data.get("library_id")
+ self._require_library(library_id)
loaded = read_repository_file(
self.team,
cast(User, request.user),
request.validated_query_data["repo"],
request.validated_query_data["path"],
+ library_id=library_id,
)
return Response(RepositoryFileSerializer(_file_payload(loaded)).data)
+ def _require_library(self, library_id: Any) -> None:
+ if library_id is None:
+ return
+ try:
+ get_library(self.team_id, library_id)
+ except LibraryNotFound:
+ raise exceptions.NotFound() from None
+
def handle_exception(self, exc: Exception) -> Response:
if isinstance(exc, GithubReposError):
exc = exceptions.ValidationError(str(exc))
diff --git a/products/business_knowledge/backend/api/repository_serializers.py b/products/business_knowledge/backend/api/repository_serializers.py
index 7733f34fed37..9e6df1e0cb6d 100644
--- a/products/business_knowledge/backend/api/repository_serializers.py
+++ b/products/business_knowledge/backend/api/repository_serializers.py
@@ -38,11 +38,25 @@ class RepositorySearchQuerySerializer(serializers.Serializer):
allow_blank=True,
help_text="Limit the search to this owner/repo. It must already be selected. Omit to search every selected repository.",
)
+ library_id = serializers.UUIDField(
+ required=False,
+ help_text=(
+ "Limit the search to repositories in this library. "
+ "Pass the same id to document search and file read. Omit to search every selected repository."
+ ),
+ )
class RepositoryFileQuerySerializer(serializers.Serializer):
repo = serializers.CharField(help_text="owner/repo to read. It must already be selected.")
path = serializers.CharField(help_text="File path returned by the repository search.")
+ library_id = serializers.UUIDField(
+ required=False,
+ help_text=(
+ "Require the repository to be in this library. "
+ "Pass the same id used for document search and repository search. Omit to read any selected repository."
+ ),
+ )
class RepositorySearchHitSerializer(serializers.Serializer):
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.py
index eda9a64d75c7..584926d5bc8f 100644
--- a/products/business_knowledge/backend/api/serializers.py
+++ b/products/business_knowledge/backend/api/serializers.py
@@ -24,6 +24,7 @@ from ..models import (
REFRESH_INTERVAL_TIMEDELTAS,
CrawlMode,
EmbeddingStatus,
+ KnowledgeLibrarySource,
KnowledgeSource,
RefreshInterval,
SafetyVerdict,
@@ -117,6 +118,9 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):
learned_from_ticket_url = serializers.SerializerMethodField(
help_text="App URL of the originating support ticket. Null for sources you added yourself.",
)
+ library_ids = serializers.SerializerMethodField(
+ help_text="Libraries this source belongs to. Empty when the source is in none.",
+ )
class Meta:
model = KnowledgeSource
@@ -148,6 +152,7 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):
"file_content_type",
"file_size_bytes",
"always_include",
+ "library_ids",
]
read_only_fields = fields
@@ -175,6 +180,21 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):
team_id = source_team_id if source_team_id is not None else obj.team_id
return f"{settings.SITE_URL}/project/{team_id}/support/tickets/{ticket_number}"
+ @extend_schema_field(serializers.ListField(child=serializers.UUIDField()))
+ def get_library_ids(self, obj: KnowledgeSource) -> list[str]:
+ # The list annotation is NULL when a source is in no library, and
+ # missing entirely when a create or update returns the row directly.
+ if "_library_ids" in obj.__dict__:
+ raw = obj.__dict__["_library_ids"] or []
+ else:
+ raw = (
+ KnowledgeLibrarySource.objects.for_team(obj.team_id)
+ .filter(source_id=obj.id)
+ .order_by("library_id")
+ .values_list("library_id", flat=True)
+ )
+ return [str(item) for item in raw]
+
@extend_schema_field(serializers.ChoiceField(choices=EmbeddingStatus.choices))
def get_embedding_status(self, obj: KnowledgeSource) -> str:
# Both inputs are annotated by the logic layer (list_for_team /
@@ -251,6 +271,11 @@ class UpdateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
required=False,
help_text="When true, this source's content is injected into every support reply prompt as general context.",
)
+ library_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ help_text="Replaces the libraries this source belongs to. Omit to leave membership unchanged. An empty list removes it from every library.",
+ )
def validate_text(self, value: str) -> str:
if not value.strip():
@@ -262,8 +287,10 @@ class UpdateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
return value
def validate(self, attrs: dict) -> dict:
- if "name" not in attrs and "text" not in attrs and "always_include" not in attrs:
- raise serializers.ValidationError("Provide at least one of `name`, `text`, or `always_include`.")
+ if "name" not in attrs and "text" not in attrs and "always_include" not in attrs and "library_ids" not in attrs:
+ raise serializers.ValidationError(
+ "Provide at least one of `name`, `text`, `always_include`, or `library_ids`."
+ )
return attrs
diff --git a/products/business_knowledge/backend/api/settings.py b/products/business_knowledge/backend/api/settings.py
index b977acf8e711..7810ffe69a42 100644
--- a/products/business_knowledge/backend/api/settings.py
+++ b/products/business_knowledge/backend/api/settings.py
@@ -20,20 +20,26 @@ from .. import learning_settings
from .serializers import BusinessKnowledgeSettingsSerializer, BusinessKnowledgeSettingsUpdateSerializer
+def canonical_user_access_control(view: TeamAndOrgViewSetMixin) -> UserAccessControl:
+ """Access control for rows the parent project owns, so a child environment's own grant does not apply."""
+ team = view.team.parent_team or view.team
+ return UserAccessControl(user=cast(User, view.request.user), team=team, organization_id=view.organization_id)
+
+
class CanonicalTeamTokenPermission(BasePermission):
- """A token scoped only to a child environment cannot touch the parent-owned setting."""
+ """A child environment reaches parent-owned rows only when the caller can reach the parent project."""
def has_permission(self, request: Request, view: Any) -> bool:
- authenticator = getattr(request, "successful_authenticator", None)
- if authenticator is None:
- return True
- scoped_teams = get_authenticator_scoped_team_ids(authenticator)
- if not scoped_teams:
- return True
canonical_id = view.team.parent_team_id or view.team.id
- if canonical_id not in scoped_teams:
+ authenticator = getattr(request, "successful_authenticator", None)
+ scoped_teams = get_authenticator_scoped_team_ids(authenticator) if authenticator is not None else None
+ if scoped_teams and canonical_id not in scoped_teams:
self.message = f"API key does not have access to the requested project: ID {canonical_id}."
return False
+ # Core permissions check membership of the child only, and resource rules fall back to a default grant.
+ if view.team.parent_team_id and not canonical_user_access_control(view).has_project_access:
+ self.message = "You don't have access to the project."
+ return False
return True
@@ -62,8 +68,7 @@ class BusinessKnowledgeSettingsViewSet(TeamAndOrgViewSetMixin, ViewSet):
# AccessControlPermission reads its resource-level check from here. Bind it to the
# canonical team: the config row belongs to the parent project, so a child environment's
# own `business_knowledge` grant must not read or change it when the parent grants `none`.
- team = self.team.parent_team or self.team
- return UserAccessControl(user=cast(User, self.request.user), team=team, organization_id=self.organization_id)
+ return canonical_user_access_control(self)
def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
# Combined GET+PATCH is neither list nor partial_update, so the default
diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.py
index 0cfbb6719534..45c807c3949d 100644
--- a/products/business_knowledge/backend/api/views.py
+++ b/products/business_knowledge/backend/api/views.py
@@ -26,7 +26,7 @@ from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission
from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottle
from posthog.temporal.common.client import sync_connect
-from .. import logic
+from .. import libraries, logic
from ..constants import (
BK_DRILLDOWN_DEFAULT_RADIUS,
BK_DRILLDOWN_MAX_RADIUS,
@@ -34,6 +34,7 @@ from ..constants import (
BK_SEARCH_MAX_LIMIT,
)
from ..file_parse import FileParseError
+from ..libraries import LibraryNotFound
from ..llm_telemetry import RetrievalTrace
from ..models import AddedBy, GapStatus, KnowledgeDocument, KnowledgeGapSuggestion, KnowledgeSource, SourceType
from ..models.constants import CrawlMode
@@ -55,6 +56,7 @@ from .serializers import (
UpdateTextSourceSerializer,
UpdateUrlSourceSerializer,
)
+from .settings import CanonicalTeamTokenPermission, canonical_user_access_control
logger = structlog.get_logger(__name__)
@@ -64,6 +66,25 @@ def _ensure_user_managed_source(source: KnowledgeSource) -> None:
raise exceptions.PermissionDenied(detail="Generated sources are read-only.")
+def _requested_library_ids(team_id: int, request: Request) -> list[UUID] | None:
+ if "library_ids" not in request.data:
+ return None
+ raw_ids = request.data.get("library_ids")
+ if not isinstance(raw_ids, list):
+ raise exceptions.ValidationError({"library_ids": "Must be a list of library ids."})
+ parsed: list[UUID] = []
+ for raw in raw_ids:
+ try:
+ parsed.append(UUID(str(raw)))
+ except (ValueError, DjangoValidationError):
+ raise exceptions.ValidationError({"library_ids": "Must be a list of library ids."})
+ try:
+ libraries.require_libraries(team_id, parsed)
+ except libraries.LibraryRejected as exc:
+ raise exceptions.ValidationError(exc.errors) from None
+ return parsed
+
+
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
@@ -110,6 +131,20 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
enum=[choice.value for choice in AddedBy],
description="Filter by who added the source: human (you added it) or learned (from a resolved support ticket).",
),
+ OpenApiParameter(
+ "library_id",
+ OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Return only sources in this library. Do not combine with unfiled.",
+ ),
+ OpenApiParameter(
+ "unfiled",
+ OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="When true, return only sources that are in no library. Do not combine with library_id.",
+ ),
],
responses={200: KnowledgeSourceSerializer(many=True)},
)
@@ -120,11 +155,14 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
added_by = request.query_params.get("added_by") or None
if added_by is not None and added_by not in AddedBy.values:
raise exceptions.ValidationError({"added_by": "Must be one of: human, learned."})
+ library_id, unfiled = self._library_list_filter(request)
sources = logic.list_for_team(
self.team_id,
search=request.query_params.get("search") or None,
source_type=source_type,
added_by=added_by,
+ library_id=library_id,
+ unfiled=unfiled,
)
page = self.paginate_queryset(sources)
if page is not None:
@@ -293,6 +331,42 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
except KnowledgeSource.DoesNotExist:
raise exceptions.NotFound()
+ # Libraries belong to the parent project, so a grant on one source or one environment is not enough.
+ if "library_ids" in request.data and not (
+ CanonicalTeamTokenPermission().has_permission(request, self)
+ and canonical_user_access_control(self).check_access_level_for_resource("business_knowledge", "editor")
+ ):
+ raise exceptions.PermissionDenied(
+ detail="You need editor access to business knowledge to change libraries."
+ )
+ # Validate before the type update runs, so a bad id cannot leave a half-applied PATCH.
+ library_ids = _requested_library_ids(self.team_id, request)
+ if library_ids is None:
+ return self._dispatch_source_update(source, request)
+ if not set(request.data.keys()) <= {"library_ids"}:
+ self._dispatch_source_update(source, request)
+ libraries.replace_source_libraries(self.team_id, source, library_ids, skip_missing=True)
+ fresh = logic.get_for_team(source.id, self.team_id) or source
+ return Response(KnowledgeSourceSerializer(instance=fresh).data)
+
+ def _library_list_filter(self, request: Request) -> tuple[UUID | None, bool]:
+ raw_library = request.query_params.get("library_id") or None
+ unfiled = request.query_params.get("unfiled", "").lower() in {"1", "true", "yes"}
+ if raw_library and unfiled:
+ raise exceptions.ValidationError({"unfiled": "Do not combine library_id and unfiled."})
+ if raw_library is None:
+ return None, unfiled
+ try:
+ library_id = UUID(str(raw_library))
+ except (ValueError, DjangoValidationError):
+ raise exceptions.ValidationError({"library_id": "Must be a UUID."})
+ try:
+ libraries.get_library(self.team_id, library_id)
+ except LibraryNotFound:
+ raise exceptions.NotFound()
+ return library_id, False
+
+ def _dispatch_source_update(self, source: KnowledgeSource, request: Request) -> Response:
if source.is_generated:
if source.source_type != SourceType.TEXT:
_ensure_user_managed_source(source)
@@ -580,6 +654,16 @@ class KnowledgeDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"Defaults to false (RRF order only). Falls back to RRF order on rerank failure."
),
),
+ OpenApiParameter(
+ "library_id",
+ OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Limit retrieval to sources in this library. "
+ "Pass the same id to repository search and file read. Omit to search every ready source."
+ ),
+ ),
],
responses={200: KnowledgeSearchResultSerializer(many=True)},
)
@@ -597,9 +681,20 @@ class KnowledgeDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
limit = self._parse_int_param(request, "limit", required=False, default=BK_SEARCH_DEFAULT_LIMIT)
limit = max(1, min(limit, BK_SEARCH_MAX_LIMIT))
rerank = self._parse_bool_param(request, "rerank", default=False)
+ # Search reads the parent project's rows, so a child environment's own token scope and grant are not enough.
+ if self.team.parent_team_id and not (
+ CanonicalTeamTokenPermission().has_permission(request, self)
+ and canonical_user_access_control(self).check_access_level_for_resource("business_knowledge", "viewer")
+ ):
+ raise exceptions.PermissionDenied(
+ detail="You need access to business knowledge in this project to search it."
+ )
+ library_id = self._search_library_id(request)
search_limit = limit * 2 if rerank else limit
trace = RetrievalTrace(surface="api")
- results = logic.search_knowledge_for_team(self.team, query.strip(), limit=search_limit, trace=trace)
+ results = logic.search_knowledge_for_team(
+ self.team, query.strip(), limit=search_limit, trace=trace, library_id=library_id
+ )
if rerank:
results = logic.rerank_chunks(self.team, query.strip(), results, top_k=limit, trace=trace)
# `search_knowledge` expands each anchor with its ordinal neighbours, so it
@@ -609,13 +704,34 @@ class KnowledgeDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
posthoganalytics.capture(
distinct_id=str(self.team.uuid),
event="business knowledge searched",
- properties={"result_count": len(results), "surface": "api"},
+ properties={
+ "result_count": len(results),
+ "surface": "api",
+ "library_scoped": library_id is not None,
+ },
groups=groups(team=self.team),
)
except Exception:
logger.warning("business_knowledge_search_capture_failed", team_id=self.team_id, exc_info=True)
return Response(KnowledgeSearchResultSerializer(instance=results, many=True).data)
+ def _search_library_id(self, request: Request) -> UUID | None:
+ raw = request.query_params.get("library_id")
+ if not raw:
+ return None
+ return self._existing_library_id(raw)
+
+ def _existing_library_id(self, raw: str) -> UUID:
+ try:
+ library_id = UUID(raw)
+ except (ValueError, DjangoValidationError):
+ raise exceptions.ValidationError({"library_id": "Must be a library id."}) from None
+ try:
+ libraries.get_library(self.team_id, library_id)
+ except LibraryNotFound:
+ raise exceptions.NotFound() from None
+ return library_id
+
def _parse_bool_param(self, request: Request, name: str, *, default: bool) -> bool:
raw = request.query_params.get(name)
if raw is None:
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index 2040fee6384a..3e7d0591b9da 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -10,6 +10,8 @@ MAX_SOURCES_PER_TEAM = 500
# Generated sources are excluded from MAX_SOURCES_PER_TEAM. This bounds the
# sources list when learning publishes one text source per accepted topic.
MAX_LEARNED_SOURCES_PER_TEAM = 10000
+MAX_LIBRARIES_PER_TEAM = 100
+DEFAULT_LIBRARY_NAME = "Learned"
MAX_CHUNKS_PER_TEAM = 250_000
# 1 MB of raw text. Above this Stage 1 refuses the create; for longer docs the
# customer is expected to split them or wait for Stage 2/3.
@@ -195,6 +197,13 @@ BK_QUERY_EMBEDDING_TIMEOUT = 5.0
# `search_knowledge` also clamps its anchor count to the max.
BK_SEARCH_DEFAULT_LIMIT = 10
BK_SEARCH_MAX_LIMIT = 20
+# A library-scoped semantic query filters ClickHouse by document id. The query
+# already carries a 1,536-float embedding (~30 KB). Past this many ids the IN
+# list is dropped and the Postgres rejoin does the filter instead.
+BK_LIBRARY_SEMANTIC_DOCUMENT_CAP = 2_000
+# Fixed upper bound on that unfiltered ClickHouse pull. The rejoin then drops
+# chunks whose source is outside the library.
+BK_LIBRARY_SEMANTIC_UNFILTERED_LIMIT = 200
# --- Always-on context cap ---
# Hard char cap for always-on sources injected into every support prompt.
diff --git a/products/business_knowledge/backend/github_repos.py b/products/business_knowledge/backend/github_repos.py
index 0b8756bc58c2..aec31a3350c1 100644
--- a/products/business_knowledge/backend/github_repos.py
+++ b/products/business_knowledge/backend/github_repos.py
@@ -12,6 +12,7 @@ import dataclasses
from datetime import timedelta
from typing import Any
from urllib.parse import quote
+from uuid import UUID
from django.conf import settings
from django.core.cache import cache
@@ -176,7 +177,7 @@ def connect_github(team: Team, integration_id: int) -> dict[str, Any]:
if config.github_integration_id != integration.id:
config.github_repos = []
config.github_integration_id = integration.id
- config.save(update_fields=["github_integration_id", "github_repos"])
+ _save_allowlist(team, config, ["github_integration_id", "github_repos"])
return connection_status(team)
@@ -185,7 +186,7 @@ def disconnect_github(team: Team) -> dict[str, Any]:
if config is not None:
config.github_integration_id = None
config.github_repos = []
- config.save(update_fields=["github_integration_id", "github_repos"])
+ _save_allowlist(team, config, ["github_integration_id", "github_repos"])
return connection_status(team)
@@ -195,7 +196,7 @@ def select_github_repos(team: Team, repos: list[str]) -> dict[str, Any]:
raise GithubReposError("Connect GitHub before choosing repositories.")
validated = _validate_against_installation(team.id, config.github_integration_id, repos)
config.github_repos = validated
- config.save(update_fields=["github_repos"])
+ _save_allowlist(team, config, ["github_repos"])
integration_id = config.github_integration_id
def enqueue() -> None:
@@ -206,8 +207,21 @@ def select_github_repos(team: Team, repos: list[str]) -> dict[str, Any]:
return connection_status(team)
-def search_repositories(team: Team, user: User, query: str, repo: str | None) -> RepositorySearchOutcome:
+def search_repositories(
+ team: Team,
+ user: User,
+ query: str,
+ repo: str | None,
+ library_id: UUID | None = None,
+) -> RepositorySearchOutcome:
integration, allowed = _require_allowlist(team)
+ allowed = _restrict_to_library(team, allowed, library_id, repo)
+ if not allowed:
+ outcome = RepositorySearchOutcome(hits=[], repositories=[])
+ _capture_tool(
+ team, user, "search", 0, [], result_chars=_serialized_chars(outcome), library_scoped=library_id is not None
+ )
+ return outcome
targets = _targets(allowed, repo)
terms = search_terms(query)
if not terms:
@@ -216,13 +230,24 @@ def search_repositories(team: Team, user: User, query: str, repo: str | None) ->
hits = _search_paths(team.id, integration.id, targets, terms)
hits.extend(_search_readmes(team.id, integration.id, targets, terms))
outcome = RepositorySearchOutcome(hits=hits, repositories=states)
- _capture_tool(team, user, "search", len(hits), states, result_chars=_serialized_chars(outcome))
+ _capture_tool(
+ team,
+ user,
+ "search",
+ len(hits),
+ states,
+ result_chars=_serialized_chars(outcome),
+ library_scoped=library_id is not None,
+ )
return outcome
-def read_repository_file(team: Team, user: User, repo: str, path: str) -> RepositoryFile:
+def read_repository_file(
+ team: Team, user: User, repo: str, path: str, library_id: UUID | None = None
+) -> RepositoryFile:
integration, allowed = _require_allowlist(team)
full_name = repo.lower()
+ allowed = _restrict_to_library(team, allowed, library_id, full_name)
if full_name not in allowed:
raise GithubReposError("That repository is not selected for business knowledge.")
safe_path = _safe_blob_path(path)
@@ -235,9 +260,11 @@ def read_repository_file(team: Team, user: User, repo: str, path: str) -> Reposi
raise GithubReposError("That path is not a file in the cached tree.")
loaded = _fetch_file(team, integration, full_name, safe_path, sha)
except GithubReposError:
- _capture_tool(team, user, "file", 0, states, result_chars=0)
+ _capture_tool(team, user, "file", 0, states, result_chars=0, library_scoped=library_id is not None)
raise
- _capture_tool(team, user, "file", 1, states, result_chars=_serialized_chars(loaded))
+ _capture_tool(
+ team, user, "file", 1, states, result_chars=_serialized_chars(loaded), library_scoped=library_id is not None
+ )
return loaded
@@ -356,6 +383,39 @@ def _installation_repo_names(integration: Integration) -> set[str]:
}
+def _restrict_to_library(team: Team, allowed: list[str], library_id: UUID | None, repo: str | None) -> list[str]:
+ """Intersect the allowlist with a library. An empty result means search should return no hits."""
+ if library_id is None:
+ return allowed
+ from .libraries import LibraryNotFound, library_repo_names # noqa: PLC0415 — libraries imports this module's models
+
+ try:
+ members = library_repo_names(team.id, library_id)
+ except LibraryNotFound:
+ raise GithubReposError("That library was not found.") from None
+ if repo:
+ full_name = repo.lower()
+ if full_name not in members:
+ raise GithubReposError("That repository is not selected for business knowledge.")
+ return [full_name for full_name in allowed if full_name in members]
+
+
+def _save_allowlist(team: Team, config: TeamBusinessKnowledgeConfig | None, update_fields: list[str]) -> None:
+ from .libraries import ( # noqa: PLC0415 — libraries is not on the import path
+ lock_libraries,
+ project_allowed_repos,
+ prune_repository_links,
+ )
+
+ # Environments of a project share library links. Without one lock, a prune can read another environment's
+ # allowlist before that environment saves it and delete links the new allowlist keeps.
+ with transaction.atomic():
+ lock_libraries(team.id)
+ if config is not None:
+ config.save(update_fields=update_fields)
+ prune_repository_links(team.id, project_allowed_repos(team))
+
+
def _targets(allowed: list[str], repo: str | None) -> list[str]:
if repo is None or repo == "":
return allowed
@@ -577,6 +637,7 @@ def _capture_tool(
states: list[RepositoryCacheState],
*,
result_chars: int,
+ library_scoped: bool = False,
) -> None:
cache_status = (
RepositoryCacheStatus.WARMING
@@ -591,6 +652,7 @@ def _capture_tool(
"tool": tool,
"result_count": result_count,
"cache_status": str(cache_status),
+ "library_scoped": library_scoped,
# The tools call no model. Their cost is the text they add to the calling agent's context.
"result_chars": result_chars,
},
diff --git a/products/business_knowledge/backend/libraries.py b/products/business_knowledge/backend/libraries.py
new file mode 100644
index 000000000000..b19417f713d8
--- /dev/null
+++ b/products/business_knowledge/backend/libraries.py
@@ -0,0 +1,408 @@
+"""Library membership. A library does not own sources or repositories. Deleting it drops the links only."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.db import IntegrityError, connection, transaction
+from django.db.models import Count
+
+import structlog
+
+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated
+from posthog.models.scoping import with_team_scope
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team.team import Team
+
+from .constants import DEFAULT_LIBRARY_NAME, MAX_LIBRARIES_PER_TEAM
+from .models import (
+ KnowledgeLibrary,
+ KnowledgeLibraryRepository,
+ KnowledgeLibrarySource,
+ KnowledgeSource,
+ TeamBusinessKnowledgeConfig,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+class LibraryNotFound(Exception):
+ """The library id is missing on this project."""
+
+
+class LibraryRejected(Exception):
+ """A field the caller sent cannot be saved. `errors` is a DRF validation map."""
+
+ def __init__(self, errors: dict[str, str]) -> None:
+ self.errors = errors
+ super().__init__(next(iter(errors.values()), "Invalid library."))
+
+
+def _clean_name(name: str) -> str:
+ cleaned = name.strip()
+ if not cleaned:
+ raise LibraryRejected({"name": "Enter a name."})
+ if len(cleaned) > 255:
+ raise LibraryRejected({"name": "Name must be 255 characters or fewer."})
+ return cleaned
+
+
+def _normalize_repo(repo: str) -> str:
+ return repo.strip().lower()
+
+
+def _lock_libraries(team_id: int) -> None:
+ # Transaction-scoped. Every library write takes it before any row lock, so two writes never lock rows in opposite
+ # orders, and the library count check cannot race another create.
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",
+ [f"business_knowledge_libraries:{team_id}"],
+ )
+
+
+def lock_libraries(team_id: int) -> None:
+ """Take the project's library lock for a write outside this module. Call it inside `transaction.atomic()`."""
+ _lock_libraries(resolve_effective_team_id(team_id))
+
+
+def _require_library_locked(team_id: int, library_id: UUID) -> None:
+ if not KnowledgeLibrary.objects.filter(team_id=team_id, id=library_id).exists():
+ raise LibraryNotFound()
+
+
+@with_team_scope()
+def list_libraries(team_id: int) -> list[KnowledgeLibrary]:
+ team_id = resolve_effective_team_id(team_id)
+ return list(
+ KnowledgeLibrary.objects.filter(team_id=team_id)
+ .annotate(source_count=Count("source_links"))
+ .order_by("-is_default", "name", "id")
+ )
+
+
+@with_team_scope()
+def get_library(team_id: int, library_id: UUID) -> KnowledgeLibrary:
+ team_id = resolve_effective_team_id(team_id)
+ try:
+ return KnowledgeLibrary.objects.annotate(source_count=Count("source_links")).get(id=library_id, team_id=team_id)
+ except KnowledgeLibrary.DoesNotExist:
+ raise LibraryNotFound() from None
+
+
+def visible_repos(team_id: int, library_ids: list[UUID], allowlist: set[str]) -> dict[UUID, list[str]]:
+ """Repo names on these libraries that this environment's allowlist still permits."""
+ if not library_ids or not allowlist:
+ return {library_id: [] for library_id in library_ids}
+ canonical_team_id = resolve_effective_team_id(team_id)
+ grouped: dict[UUID, list[str]] = {library_id: [] for library_id in library_ids}
+ rows = (
+ KnowledgeLibraryRepository.objects.filter(
+ team_id=canonical_team_id,
+ library_id__in=library_ids,
+ repo__in=allowlist,
+ )
+ .order_by("repo")
+ .values_list("library_id", "repo")
+ )
+ for library_id, repo in rows:
+ grouped[library_id].append(repo)
+ return grouped
+
+
+@with_team_scope()
+def create_library(team_id: int, name: str) -> KnowledgeLibrary:
+ team_id = resolve_effective_team_id(team_id)
+ cleaned = _clean_name(name)
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ if KnowledgeLibrary.objects.filter(team_id=team_id).count() >= MAX_LIBRARIES_PER_TEAM:
+ raise LibraryRejected({"name": f"This project already has {MAX_LIBRARIES_PER_TEAM} libraries."})
+ if KnowledgeLibrary.objects.filter(team_id=team_id, name__iexact=cleaned).exists():
+ raise LibraryRejected({"name": "A library with this name already exists."})
+ try:
+ with transaction.atomic():
+ library = KnowledgeLibrary.objects.create(team_id=team_id, name=cleaned, is_default=False)
+ except IntegrityError:
+ raise LibraryRejected({"name": "A library with this name already exists."}) from None
+ library.source_count = 0 # type: ignore[attr-defined]
+ return library
+
+
+@with_team_scope()
+def rename_library(team_id: int, library_id: UUID, name: str) -> KnowledgeLibrary:
+ team_id = resolve_effective_team_id(team_id)
+ cleaned = _clean_name(name)
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ library = get_library(team_id, library_id)
+ if cleaned == library.name:
+ return library
+ if KnowledgeLibrary.objects.filter(team_id=team_id, name__iexact=cleaned).exclude(id=library.id).exists():
+ raise LibraryRejected({"name": "A library with this name already exists."})
+ library.name = cleaned
+ try:
+ with transaction.atomic():
+ library.save(update_fields=["name", "updated_at"])
+ except IntegrityError:
+ raise LibraryRejected({"name": "A library with this name already exists."}) from None
+ return library
+
+
+@with_team_scope()
+def delete_library(team_id: int, library_id: UUID) -> None:
+ team_id = resolve_effective_team_id(team_id)
+ library = get_library(team_id, library_id)
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ library.delete()
+
+
+def _source_ids_for_library(team_id: int, library_id: UUID) -> list[str]:
+ return [
+ str(source_id)
+ for source_id in KnowledgeLibrarySource.objects.filter(team_id=team_id, library_id=library_id)
+ .order_by("source_id")
+ .values_list("source_id", flat=True)
+ ]
+
+
+def _log_membership(
+ *,
+ team_id: int,
+ item_id: UUID,
+ scope: str,
+ name: str,
+ field: str,
+ before: list[str],
+ after: list[str],
+) -> None:
+ if before == after:
+ return
+ log_activity(
+ organization_id=None,
+ team_id=team_id,
+ user=get_current_user(),
+ was_impersonated=bool(get_was_impersonated()),
+ item_id=item_id,
+ scope=scope,
+ activity="updated",
+ detail=Detail(
+ name=name,
+ changes=[Change(type=scope, action="changed", field=field, before=before, after=after)],
+ ),
+ )
+
+
+@with_team_scope()
+def replace_library_sources(team_id: int, library_id: UUID, source_ids: list[UUID]) -> KnowledgeLibrary:
+ team_id = resolve_effective_team_id(team_id)
+ library = get_library(team_id, library_id)
+ requested = list(dict.fromkeys(source_ids))
+ found = set(KnowledgeSource.objects.filter(team_id=team_id, id__in=requested).values_list("id", flat=True))
+ if set(requested) != found:
+ raise LibraryRejected({"source_ids": "One or more sources were not found."})
+ after = [str(source_id) for source_id in requested]
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ _require_library_locked(team_id, library.id)
+ before = _source_ids_for_library(team_id, library.id)
+ if before == sorted(after):
+ return library
+ KnowledgeLibrarySource.objects.filter(team_id=team_id, library=library).delete()
+ KnowledgeLibrarySource.objects.bulk_create(
+ [KnowledgeLibrarySource(team_id=team_id, library=library, source_id=source_id) for source_id in requested]
+ )
+ _log_membership(
+ team_id=team_id,
+ item_id=library.id,
+ scope="KnowledgeLibrary",
+ name=f"Library '{library.name}' updated",
+ field="sources",
+ before=before,
+ after=sorted(after),
+ )
+ return get_library(team_id, library.id)
+
+
+@with_team_scope()
+def replace_library_repos(
+ team_id: int,
+ library_id: UUID,
+ repos: list[str],
+ *,
+ environment_allowlist: set[str],
+) -> KnowledgeLibrary:
+ """Replace this environment's repo links. Links for repos only another environment allows stay."""
+ team_id = resolve_effective_team_id(team_id)
+ library = get_library(team_id, library_id)
+ requested: list[str] = []
+ for repo in repos:
+ normalized = _normalize_repo(repo)
+ if not normalized or normalized not in environment_allowlist:
+ raise LibraryRejected({"repos": "Choose repositories that are selected for this environment."})
+ if normalized not in requested:
+ requested.append(normalized)
+ requested_set = set(requested)
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ _require_library_locked(team_id, library.id)
+ current_visible = set(
+ KnowledgeLibraryRepository.objects.filter(
+ team_id=team_id,
+ library=library,
+ repo__in=environment_allowlist,
+ ).values_list("repo", flat=True)
+ )
+ if current_visible == requested_set:
+ return library
+ KnowledgeLibraryRepository.objects.filter(
+ team_id=team_id,
+ library=library,
+ repo__in=environment_allowlist,
+ ).exclude(repo__in=requested_set).delete()
+ already = set(
+ KnowledgeLibraryRepository.objects.filter(team_id=team_id, library=library).values_list("repo", flat=True)
+ )
+ KnowledgeLibraryRepository.objects.bulk_create(
+ [
+ KnowledgeLibraryRepository(team_id=team_id, library=library, repo=repo)
+ for repo in sorted(requested_set - already)
+ ]
+ )
+ _log_membership(
+ team_id=team_id,
+ item_id=library.id,
+ scope="KnowledgeLibrary",
+ name=f"Library '{library.name}' updated",
+ field="repos",
+ before=sorted(current_visible),
+ after=sorted(requested_set),
+ )
+ return get_library(team_id, library.id)
+
+
+def _library_ids_for_source(team_id: int, source_id: UUID) -> list[str]:
+ return [
+ str(library_id)
+ for library_id in KnowledgeLibrarySource.objects.filter(team_id=team_id, source_id=source_id)
+ .order_by("library_id")
+ .values_list("library_id", flat=True)
+ ]
+
+
+@with_team_scope()
+def require_libraries(team_id: int, library_ids: list[UUID]) -> None:
+ team_id = resolve_effective_team_id(team_id)
+ requested = set(library_ids)
+ found = set(KnowledgeLibrary.objects.filter(team_id=team_id, id__in=requested).values_list("id", flat=True))
+ if requested != found:
+ raise LibraryRejected({"library_ids": "One or more libraries were not found."})
+
+
+@with_team_scope()
+def replace_source_libraries(
+ team_id: int, source: KnowledgeSource, library_ids: list[UUID], *, skip_missing: bool = False
+) -> None:
+ """`skip_missing` drops a library deleted since the caller validated it, as if the delete ran after this call."""
+ team_id = resolve_effective_team_id(team_id)
+ requested = list(dict.fromkeys(library_ids))
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ if skip_missing:
+ existing = set(
+ KnowledgeLibrary.objects.filter(team_id=team_id, id__in=requested).values_list("id", flat=True)
+ )
+ requested = [library_id for library_id in requested if library_id in existing]
+ else:
+ require_libraries(team_id, requested)
+ before = _library_ids_for_source(team_id, source.id)
+ after = sorted(str(library_id) for library_id in requested)
+ if before == after:
+ return
+ KnowledgeLibrarySource.objects.filter(team_id=team_id, source=source).delete()
+ KnowledgeLibrarySource.objects.bulk_create(
+ [KnowledgeLibrarySource(team_id=team_id, library_id=library_id, source=source) for library_id in requested]
+ )
+ _log_membership(
+ team_id=team_id,
+ item_id=source.id,
+ scope="KnowledgeSource",
+ name=f"Knowledge source '{source.name}' updated",
+ field="library_ids",
+ before=before,
+ after=after,
+ )
+
+
+@with_team_scope()
+def ensure_default_library(team_id: int) -> KnowledgeLibrary | None:
+ """The library new learned sources join. None when the project is already at the library cap and has no default."""
+ team_id = resolve_effective_team_id(team_id)
+ existing = KnowledgeLibrary.objects.filter(team_id=team_id, is_default=True).first()
+ if existing is not None:
+ return existing
+ with transaction.atomic():
+ _lock_libraries(team_id)
+ existing = KnowledgeLibrary.objects.filter(team_id=team_id, is_default=True).first()
+ if existing is not None:
+ return existing
+ named = KnowledgeLibrary.objects.filter(team_id=team_id, name__iexact=DEFAULT_LIBRARY_NAME).first()
+ if named is not None:
+ named.is_default = True
+ named.save(update_fields=["is_default", "updated_at"])
+ return named
+ if KnowledgeLibrary.objects.filter(team_id=team_id).count() >= MAX_LIBRARIES_PER_TEAM:
+ # A learned document must still land. It stays unfiled until a library is removed.
+ logger.warning("business_knowledge.default_library_skipped_at_cap", team_id=team_id)
+ return None
+ return KnowledgeLibrary.objects.create(team_id=team_id, name=DEFAULT_LIBRARY_NAME, is_default=True)
+
+
+@with_team_scope()
+def file_new_learned_source(*, team_id: int, source_id: UUID) -> None:
+ """Link a learned source the first time it is inserted. A later call is not made, so removing the link sticks."""
+ team_id = resolve_effective_team_id(team_id)
+ library = ensure_default_library(team_id)
+ if library is None:
+ return
+ if KnowledgeLibrarySource.objects.filter(team_id=team_id, library=library, source_id=source_id).exists():
+ return
+ KnowledgeLibrarySource.objects.create(team_id=team_id, library=library, source_id=source_id)
+
+
+@with_team_scope()
+def library_repo_names(team_id: int, library_id: UUID) -> set[str]:
+ team_id = resolve_effective_team_id(team_id)
+ if not KnowledgeLibrary.objects.filter(team_id=team_id, id=library_id).exists():
+ raise LibraryNotFound()
+ return set(
+ KnowledgeLibraryRepository.objects.filter(team_id=team_id, library_id=library_id).values_list("repo", flat=True)
+ )
+
+
+def project_allowed_repos(team: Team) -> set[str]:
+ """Repos any environment of this project still allows. Used when one environment's allowlist changes."""
+ canonical_id = team.parent_team_id or team.id
+ team_ids = list(Team.objects.filter(id=canonical_id).values_list("id", flat=True)) + list(
+ Team.objects.filter(parent_team_id=canonical_id).values_list("id", flat=True)
+ )
+ allowed: set[str] = set()
+ for config in TeamBusinessKnowledgeConfig.objects.filter(team_id__in=team_ids).only("github_repos"):
+ repos = config.github_repos
+ if not isinstance(repos, list):
+ continue
+ for repo in repos:
+ if isinstance(repo, str) and repo.strip():
+ allowed.add(repo.strip().lower())
+ return allowed
+
+
+@with_team_scope()
+def prune_repository_links(team_id: int, allowed_repos: set[str]) -> None:
+ team_id = resolve_effective_team_id(team_id)
+ stale = KnowledgeLibraryRepository.objects.filter(team_id=team_id)
+ if allowed_repos:
+ stale = stale.exclude(repo__in=allowed_repos)
+ stale.delete()
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 12979ba9eb81..d5ce81a9f008 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -18,6 +18,7 @@ from urllib.parse import urlsplit
from uuid import UUID
from django.conf import settings
+from django.contrib.postgres.aggregates import ArrayAgg
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.db import (
connection as db_connection,
@@ -52,6 +53,8 @@ from .constants import (
BK_EMBEDDING_DOCUMENT_TYPE,
BK_EMBEDDING_MODEL,
BK_EMBEDDING_PRODUCT,
+ BK_LIBRARY_SEMANTIC_DOCUMENT_CAP,
+ BK_LIBRARY_SEMANTIC_UNFILTERED_LIMIT,
BK_QUERY_EMBEDDING_TIMEOUT,
BK_RERANK_MODEL,
BK_RERANK_SNIPPET_CHARS,
@@ -83,6 +86,7 @@ from .constants import (
TRIAL_MAX_CHUNKS,
TRIAL_QUIET_PERIOD,
)
+from .libraries import file_new_learned_source
from .llm_telemetry import RetrievalTrace
from .models import (
REFRESH_INTERVAL_TIMEDELTAS,
@@ -92,6 +96,7 @@ from .models import (
KnowledgeChunk,
KnowledgeDocument,
KnowledgeGapSuggestion,
+ KnowledgeLibrarySource,
KnowledgeSource,
RefreshInterval,
SafetyVerdict,
@@ -555,9 +560,19 @@ def _source_list_annotations() -> dict[str, object]:
"_ai_processing_approved": F("team__organization__is_ai_data_processing_approved"),
"_learned_ticket_number": _learned_ticket_number_subquery(),
"_learned_source_team_id": _learned_source_team_id_subquery(),
+ "_library_ids": _library_ids_subquery(),
}
+def _library_ids_subquery() -> Subquery:
+ return Subquery(
+ KnowledgeLibrarySource.objects.filter(source_id=OuterRef("pk"))
+ .values("source_id")
+ .annotate(_ids=ArrayAgg("library_id", ordering="library_id"))
+ .values("_ids")[:1]
+ )
+
+
@with_team_scope(canonical=True)
def list_for_team(
team_id: int,
@@ -565,9 +580,15 @@ def list_for_team(
search: str | None = None,
source_type: str | None = None,
added_by: str | None = None,
+ library_id: UUID | None = None,
+ unfiled: bool = False,
) -> list[KnowledgeSource]:
# Annotate counts in one round-trip so the serializer doesn't N+1.
queryset = KnowledgeSource.objects.filter(team_id=team_id)
+ if library_id is not None:
+ queryset = queryset.filter(library_links__library_id=library_id)
+ elif unfiled:
+ queryset = queryset.filter(library_links__isnull=True)
if source_type:
queryset = queryset.filter(source_type=source_type)
if added_by == AddedBy.HUMAN:
@@ -863,6 +884,8 @@ def _create_generated_knowledge_document(
status=create_status.status,
error_message=create_status.error_message,
)
+ # First insert only. A retry returns the existing document above, so a removed link stays removed.
+ file_new_learned_source(team_id=team_id, source_id=source.id)
elif not source.is_generated or source.source_type != SourceType.TEXT:
raise InvalidGeneratedKnowledgeDocument("generated source identity is already in use")
else:
@@ -2461,6 +2484,8 @@ def _semantic_chunk_candidates(
query_embedding: list[float],
*,
limit: int,
+ document_ids: list[str] | None = None,
+ ch_limit: int | None = None,
) -> list[_SemanticCandidate]:
"""
Vector search over document_embeddings for BK chunks.
@@ -2468,6 +2493,9 @@ def _semantic_chunk_candidates(
Returns up to ``limit * BK_SEMANTIC_OVERFETCH`` candidates under the
distance cutoff, ordered by cosineDistance ASC. The caller re-joins to
Postgres for safety filters and trims to ``limit``.
+
+ ``document_ids`` filters ``metadata.document_id`` (the knowledge document),
+ not the embedding row's ``document_id`` column, which stores the chunk id.
"""
from posthog.hogql import ast # noqa: PLC0415 — keeps HogQL compiler off the import path
from posthog.hogql.query import execute_hogql_query # noqa: PLC0415
@@ -2475,26 +2503,30 @@ def _semantic_chunk_candidates(
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries # noqa: PLC0415
from posthog.models.team.team import Team # noqa: PLC0415
- ch_limit = limit * BK_SEMANTIC_OVERFETCH
+ resolved_limit = ch_limit if ch_limit is not None else limit * BK_SEMANTIC_OVERFETCH
+ document_filter = ""
+ if document_ids is not None:
+ document_filter = "AND JSONExtractString(metadata, 'document_id') IN {document_ids}"
# Distance is computed in the inner SELECT and filtered in the outer WHERE
# so cosineDistance runs once per row (ClickHouse can't reuse a SELECT alias
# in the same level's WHERE — WHERE is evaluated first). Matters at 1536 dims.
- hogql_query = """
+ hogql_query = f"""
SELECT document_id, distance
FROM (
SELECT
document_id,
- cosineDistance(embedding, {embedding}) AS distance
+ cosineDistance(embedding, {{embedding}}) AS distance
FROM document_embeddings
- WHERE model_name = {model_name}
- AND product = {product}
- AND document_type = {document_type}
- AND team_id = {team_id}
+ WHERE model_name = {{model_name}}
+ AND product = {{product}}
+ AND document_type = {{document_type}}
+ AND team_id = {{team_id}}
+ {document_filter}
)
- WHERE distance < {cutoff}
+ WHERE distance < {{cutoff}}
ORDER BY distance ASC
- LIMIT {limit}
+ LIMIT {{limit}}
"""
placeholders: dict[str, ast.Expr] = {
@@ -2504,8 +2536,10 @@ def _semantic_chunk_candidates(
"document_type": ast.Constant(value=BK_EMBEDDING_DOCUMENT_TYPE),
"team_id": ast.Constant(value=team_id),
"cutoff": ast.Constant(value=BK_SEMANTIC_DISTANCE_CUTOFF),
- "limit": ast.Constant(value=ch_limit),
+ "limit": ast.Constant(value=resolved_limit),
}
+ if document_ids is not None:
+ placeholders["document_ids"] = ast.Constant(value=document_ids)
team = Team.objects.get(pk=team_id)
tag_queries(product=Product.CONVERSATIONS, feature=Feature.SEMANTIC_SEARCH)
@@ -2568,14 +2602,45 @@ def _rrf_fuse(
return [cid for cid, _score in fused]
-def _safe_chunks_qs(team_id: int) -> QuerySet[KnowledgeChunk]:
+def _safe_chunks_qs(team_id: int, *, library_id: UUID | None = None) -> QuerySet[KnowledgeChunk]:
"""Base queryset for searchable/readable chunks: team-scoped + all safety gates."""
- return KnowledgeChunk.objects.filter(
+ queryset = KnowledgeChunk.objects.filter(
team_id=team_id,
source__status=SourceStatus.READY,
document__tombstoned_at__isnull=True,
document__safety_verdict=SafetyVerdict.SAFE,
)
+ if library_id is not None:
+ # Subquery, not a Python list: a learned library can hold every generated source.
+ queryset = queryset.filter(
+ source_id__in=KnowledgeLibrarySource.objects.filter(team_id=team_id, library_id=library_id).values(
+ "source_id"
+ )
+ )
+ return queryset
+
+
+def _library_has_sources(team_id: int, library_id: UUID) -> bool:
+ return KnowledgeLibrarySource.objects.filter(team_id=team_id, library_id=library_id).exists()
+
+
+def _library_document_ids(team_id: int, library_id: UUID) -> list[str] | None:
+ """Document ids for a library-scoped semantic query.
+
+ None means the library is over the ClickHouse IN cap, so the caller skips the predicate.
+ """
+ ids = list(
+ KnowledgeDocument.objects.filter(
+ team_id=team_id,
+ tombstoned_at__isnull=True,
+ source_id__in=KnowledgeLibrarySource.objects.filter(team_id=team_id, library_id=library_id).values(
+ "source_id"
+ ),
+ ).values_list("id", flat=True)[: BK_LIBRARY_SEMANTIC_DOCUMENT_CAP + 1]
+ )
+ if len(ids) > BK_LIBRARY_SEMANTIC_DOCUMENT_CAP:
+ return None
+ return [str(document_id) for document_id in ids]
@dataclass(frozen=True)
@@ -2619,6 +2684,7 @@ def search_knowledge(
limit: int = 10,
use_semantic: bool = False,
query_embedding: list[float] | None = None,
+ library_id: UUID | None = None,
) -> list[KnowledgeSearchResult]:
"""
Hybrid (lexical + semantic) relevance search over BK chunks.
@@ -2633,6 +2699,18 @@ def search_knowledge(
"""
limit = max(1, min(limit, BK_SEARCH_MAX_LIMIT))
+ if library_id is not None and not _library_has_sources(team_id, library_id):
+ return []
+
+ semantic_document_ids: list[str] | None = None
+ semantic_ch_limit: int | None = None
+ if library_id is not None and use_semantic and query_embedding:
+ semantic_document_ids = _library_document_ids(team_id, library_id)
+ if semantic_document_ids is None:
+ semantic_ch_limit = BK_LIBRARY_SEMANTIC_UNFILTERED_LIMIT
+ elif not semantic_document_ids:
+ use_semantic = False
+
# --- FTS anchors (always computed) ---
processed = process_query(query)
fts_anchors: list[KnowledgeChunk] = []
@@ -2640,7 +2718,7 @@ def search_knowledge(
processed = processed.replace(" & ", " | ")
search_query = SearchQuery(processed, config="english", search_type="raw")
fts_anchors = list(
- _safe_chunks_qs(team_id)
+ _safe_chunks_qs(team_id, library_id=library_id)
.filter(content_search_vector=search_query)
.annotate(rank=SearchRank(F("content_search_vector"), search_query))
.only("id", "document_id", "ordinal", "char_count")
@@ -2651,7 +2729,21 @@ def search_knowledge(
# --- Semantic candidates (hybrid path only) ---
semantic_candidates: list[_SemanticCandidate] = []
if use_semantic and query_embedding:
- semantic_candidates = _semantic_chunk_candidates(team_id, query_embedding, limit=limit)
+ semantic_candidates = _semantic_chunk_candidates(
+ team_id,
+ query_embedding,
+ limit=limit,
+ document_ids=semantic_document_ids,
+ ch_limit=semantic_ch_limit,
+ )
+ if library_id is not None and semantic_document_ids is None and semantic_candidates:
+ # Drop non-members before RRF: they take semantic ranks and push members under the score floor.
+ member_ids = set(
+ _safe_chunks_qs(team_id, library_id=library_id)
+ .filter(id__in=[candidate.chunk_id for candidate in semantic_candidates])
+ .values_list("id", flat=True)
+ )
+ semantic_candidates = [c for c in semantic_candidates if c.chunk_id in member_ids]
# --- Fusion or FTS-only ---
# Fusion requires an actual embedding; when it's None (e.g. embedding-service
@@ -2665,7 +2757,9 @@ def search_knowledge(
# re-join against Postgres with all safety filters and trim after.
fetch_limit = limit * BK_SEMANTIC_OVERFETCH
anchor_chunks = list(
- _safe_chunks_qs(team_id).filter(id__in=fused_ids[:fetch_limit]).only("id", "document_id", "ordinal")
+ _safe_chunks_qs(team_id, library_id=library_id)
+ .filter(id__in=fused_ids[:fetch_limit])
+ .only("id", "document_id", "ordinal")
)
if not anchor_chunks:
return []
@@ -2694,7 +2788,7 @@ def search_knowledge(
)
chunks = (
- _safe_chunks_qs(team_id)
+ _safe_chunks_qs(team_id, library_id=library_id)
.filter(window_filter)
.select_related("source", "document")
.only(
@@ -2734,6 +2828,7 @@ def search_knowledge_for_team(
*,
trace: RetrievalTrace,
limit: int = 10,
+ library_id: UUID | None = None,
) -> list[KnowledgeSearchResult]:
"""
Sync orchestration of hybrid BK search: embed the query, then call
@@ -2742,6 +2837,12 @@ def search_knowledge_for_team(
Used by the DRF search endpoint (sync view). The async path is
``async_search_knowledge_for_team``. Both share ``search_knowledge``.
"""
+ # Rows are stored under the parent team, and a child environment can reach this through an environment token.
+ canonical_team_id = resolve_effective_team_id(team.id)
+ if library_id is not None:
+ with team_scope(canonical_team_id, canonical=True):
+ if not _library_has_sources(canonical_team_id, library_id):
+ return []
embedding: list[float] | None = None
try:
response = generate_embedding(team, query, model=BK_EMBEDDING_MODEL, timeout=BK_QUERY_EMBEDDING_TIMEOUT)
@@ -2749,7 +2850,14 @@ def search_knowledge_for_team(
_capture_query_embedding(team.id, response, trace)
except Exception:
logger.warning("bk_query_embedding_failed", team_id=team.id, exc_info=True)
- return search_knowledge(team.id, query, limit=limit, use_semantic=embedding is not None, query_embedding=embedding)
+ return search_knowledge(
+ canonical_team_id,
+ query,
+ limit=limit,
+ use_semantic=embedding is not None,
+ query_embedding=embedding,
+ library_id=library_id,
+ )
async def async_search_knowledge_for_team(
diff --git a/products/business_knowledge/backend/migrations/0024_knowledge_libraries.py b/products/business_knowledge/backend/migrations/0024_knowledge_libraries.py
new file mode 100644
index 000000000000..1a4effe230d7
--- /dev/null
+++ b/products/business_knowledge/backend/migrations/0024_knowledge_libraries.py
@@ -0,0 +1,140 @@
+# Generated by Django 5.2.17 on 2026-10-14 14:35
+
+import django.db.models.deletion
+import django.db.models.functions.text
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("business_knowledge", "0023_knowledgesource_processing_claim_id"),
+ ("posthog", "1397_uploaded_media_dimensions_and_archive"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="KnowledgeLibrary",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("is_default", models.BooleanField(db_default=False, default=False)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_business_knowledge_knowledgelibrary",
+ },
+ ),
+ migrations.CreateModel(
+ name="KnowledgeLibraryRepository",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("repo", models.CharField(max_length=255)),
+ (
+ "library",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="repository_links",
+ to="business_knowledge.knowledgelibrary",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_business_knowledge_knowledgelibraryrepository",
+ },
+ ),
+ migrations.CreateModel(
+ name="KnowledgeLibrarySource",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ (
+ "library",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="source_links",
+ to="business_knowledge.knowledgelibrary",
+ ),
+ ),
+ (
+ "source",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="library_links",
+ to="business_knowledge.knowledgesource",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_business_knowledge_knowledgelibrarysource",
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="knowledgelibrary",
+ constraint=models.UniqueConstraint(
+ models.F("team"), django.db.models.functions.text.Lower("name"), name="bk_library_team_name_ci"
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="knowledgelibrary",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("is_default", True)), fields=("team",), name="bk_library_one_default"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="knowledgelibraryrepository",
+ index=models.Index(fields=["team", "repo"], name="bk_lib_repo_team_repo"),
+ ),
+ migrations.AddConstraint(
+ model_name="knowledgelibraryrepository",
+ constraint=models.UniqueConstraint(fields=("library", "repo"), name="bk_lib_repo_unique"),
+ ),
+ migrations.AddIndex(
+ model_name="knowledgelibrarysource",
+ index=models.Index(fields=["team", "source"], name="bk_lib_source_team_source"),
+ ),
+ migrations.AddConstraint(
+ model_name="knowledgelibrarysource",
+ constraint=models.UniqueConstraint(fields=("library", "source"), name="bk_lib_source_unique"),
+ ),
+ ]
diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txt
index 31b7ebe8d4b6..41cc182df651 100644
--- a/products/business_knowledge/backend/migrations/max_migration.txt
+++ b/products/business_knowledge/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0023_knowledgesource_processing_claim_id
+0024_knowledge_libraries
diff --git a/products/business_knowledge/backend/models/__init__.py b/products/business_knowledge/backend/models/__init__.py
index b92426d27026..69244e1ddba1 100644
--- a/products/business_knowledge/backend/models/__init__.py
+++ b/products/business_knowledge/backend/models/__init__.py
@@ -17,6 +17,9 @@ from .knowledge_chunk import KnowledgeChunk
from .knowledge_document import KnowledgeDocument
from .knowledge_gap_suggestion import KnowledgeGapSuggestion
from .knowledge_learning_run import KnowledgeLearningRun
+from .knowledge_library import KnowledgeLibrary
+from .knowledge_library_repository import KnowledgeLibraryRepository
+from .knowledge_library_source import KnowledgeLibrarySource
from .knowledge_source import KnowledgeSource
from .playground_chat import PlaygroundChat
from .playground_turn import PlaygroundTurn
@@ -32,6 +35,9 @@ __all__ = [
"KnowledgeDocument",
"KnowledgeGapSuggestion",
"KnowledgeLearningRun",
+ "KnowledgeLibrary",
+ "KnowledgeLibraryRepository",
+ "KnowledgeLibrarySource",
"KnowledgeSource",
"LearningProvider",
"PlaygroundChat",
diff --git a/products/business_knowledge/backend/models/knowledge_library.py b/products/business_knowledge/backend/models/knowledge_library.py
new file mode 100644
index 000000000000..083c1a7016fc
--- /dev/null
+++ b/products/business_knowledge/backend/models/knowledge_library.py
@@ -0,0 +1,40 @@
+from django.db import models
+from django.db.models.functions import Lower
+
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class KnowledgeLibrary(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
+ """A retrieval scope. Sources and repositories belong to it through link rows, so deleting it drops those links only."""
+
+ activity_logging_on_delete = True
+
+ team = models.ForeignKey(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ # Creating a real FK takes SHARE ROW EXCLUSIVE on posthog_team.
+ db_constraint=False,
+ db_index=False,
+ related_name="+",
+ )
+ name = models.CharField(max_length=255)
+ # Set only when learning files a new source. A person can rename the row. Deleting it unlinks members.
+ is_default = models.BooleanField(default=False, db_default=False)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_business_knowledge_knowledgelibrary"
+ constraints = [
+ models.UniqueConstraint("team", Lower("name"), name="bk_library_team_name_ci"),
+ models.UniqueConstraint(
+ fields=["team"],
+ condition=models.Q(is_default=True),
+ name="bk_library_one_default",
+ ),
+ ]
+
+ def __str__(self) -> str:
+ return self.name
diff --git a/products/business_knowledge/backend/models/knowledge_library_repository.py b/products/business_knowledge/backend/models/knowledge_library_repository.py
new file mode 100644
index 000000000000..3487a7f9f039
--- /dev/null
+++ b/products/business_knowledge/backend/models/knowledge_library_repository.py
@@ -0,0 +1,29 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+from .knowledge_library import KnowledgeLibrary
+
+
+class KnowledgeLibraryRepository(TeamScopedRootMixin, UUIDModel):
+ """Membership of one selected GitHub repository in one library. The allowlist, not this row, decides what can be read."""
+
+ team = models.ForeignKey(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ db_constraint=False,
+ db_index=False,
+ related_name="+",
+ )
+ library = models.ForeignKey(KnowledgeLibrary, on_delete=models.CASCADE, related_name="repository_links")
+ repo = models.CharField(max_length=255)
+
+ class Meta:
+ db_table = "posthog_business_knowledge_knowledgelibraryrepository"
+ constraints = [
+ models.UniqueConstraint(fields=["library", "repo"], name="bk_lib_repo_unique"),
+ ]
+ indexes = [
+ models.Index(fields=["team", "repo"], name="bk_lib_repo_team_repo"),
+ ]
diff --git a/products/business_knowledge/backend/models/knowledge_library_source.py b/products/business_knowledge/backend/models/knowledge_library_source.py
new file mode 100644
index 000000000000..4086fab6c0a3
--- /dev/null
+++ b/products/business_knowledge/backend/models/knowledge_library_source.py
@@ -0,0 +1,30 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+from .knowledge_library import KnowledgeLibrary
+from .knowledge_source import KnowledgeSource
+
+
+class KnowledgeLibrarySource(TeamScopedRootMixin, UUIDModel):
+ """Membership of one source in one library. Deleting either side deletes this row and leaves the other in place."""
+
+ team = models.ForeignKey(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ db_constraint=False,
+ db_index=False,
+ related_name="+",
+ )
+ library = models.ForeignKey(KnowledgeLibrary, on_delete=models.CASCADE, related_name="source_links")
+ source = models.ForeignKey(KnowledgeSource, on_delete=models.CASCADE, related_name="library_links")
+
+ class Meta:
+ db_table = "posthog_business_knowledge_knowledgelibrarysource"
+ constraints = [
+ models.UniqueConstraint(fields=["library", "source"], name="bk_lib_source_unique"),
+ ]
+ indexes = [
+ models.Index(fields=["team", "source"], name="bk_lib_source_team_source"),
+ ]
diff --git a/products/business_knowledge/backend/routes.py b/products/business_knowledge/backend/routes.py
index 07deb6bd3449..6b0db05d33f3 100644
--- a/products/business_knowledge/backend/routes.py
+++ b/products/business_knowledge/backend/routes.py
@@ -7,6 +7,7 @@ from products.business_knowledge.backend.api import (
BusinessKnowledgeSettingsViewSet,
KnowledgeDocumentViewSet,
KnowledgeGapSuggestionViewSet,
+ KnowledgeLibraryViewSet,
KnowledgeSourceViewSet,
)
@@ -51,6 +52,13 @@ def register_routes(routers: RouterRegistry) -> None:
"project_business_knowledge_repositories",
["team_id"],
)
+ # Before the settings viewset so `libraries` is not captured as that viewset's detail pk.
+ routers.projects.register(
+ r"business_knowledge/libraries",
+ KnowledgeLibraryViewSet,
+ "project_business_knowledge_libraries",
+ ["team_id"],
+ )
# After the nested resource prefixes so `sources`/`documents`/`gap_suggestions`
# are not captured as a detail pk of this viewset.
routers.projects.register(
diff --git a/products/business_knowledge/backend/signals.py b/products/business_knowledge/backend/signals.py
index bfc5e251ee3e..d41edbc68d17 100644
--- a/products/business_knowledge/backend/signals.py
+++ b/products/business_knowledge/backend/signals.py
@@ -1,4 +1,4 @@
-"""Activity-log hook for KnowledgeSource create/update/delete."""
+"""Activity-log hooks for business knowledge sources and libraries."""
import dataclasses
from typing import Any
@@ -16,7 +16,7 @@ from posthog.models.activity_logging.model_activity import get_current_trigger
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.user import User
-from .models import KnowledgeSource
+from .models import KnowledgeLibrary, KnowledgeSource
logger = structlog.get_logger(__name__)
@@ -72,3 +72,48 @@ def handle_knowledge_source_change(
context=context,
),
)
+
+
[email protected](frozen=True)
+class KnowledgeLibraryContext(ActivityContextBase):
+ team_id: int
+ name: str
+
+
+@mutable_receiver(model_activity_signal, sender=KnowledgeLibrary)
+def handle_knowledge_library_change(
+ sender: type[KnowledgeLibrary],
+ scope: ActivityScope,
+ before_update: KnowledgeLibrary | None,
+ after_update: KnowledgeLibrary | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance: KnowledgeLibrary | None = after_update or before_update
+ if instance is None:
+ return
+
+ if activity == "created":
+ detail_name = f"Library '{instance.name}' added"
+ elif activity == "deleted":
+ detail_name = f"Library '{instance.name}' deleted"
+ else:
+ detail_name = f"Library '{instance.name}' updated"
+
+ log_activity(
+ organization_id=None,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.id,
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ changes=changes_between(scope, previous=before_update, current=after_update),
+ name=detail_name,
+ trigger=get_current_trigger(),
+ context=KnowledgeLibraryContext(team_id=instance.team_id, name=instance.name),
+ ),
+ )
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index e8acf55d524e..f7fc7d18afa7 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -14,7 +14,17 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from products.business_knowledge.backend import logic
from products.business_knowledge.backend.api.serializers import _derive_scope_globs
from products.business_knowledge.backend.constants import CLASSIFY_MAX_ATTEMPTS
-from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SafetyVerdict
+from products.business_knowledge.backend.models import (
+ KnowledgeChunk,
+ KnowledgeDocument,
+ KnowledgeLibrary,
+ KnowledgeLibraryRepository,
+ KnowledgeLibrarySource,
+ KnowledgeSource,
+ SafetyVerdict,
+ SourceStatus,
+ SourceType,
+)
@patch("posthoganalytics.feature_enabled", return_value=True)
@@ -360,6 +370,133 @@ class TestKnowledgeSourceAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def test_deleting_a_library_keeps_the_source(self, _ff) -> None:
+ created = self.client.post(self.url, {"name": "Docs", "text": "Pricing is public."}, format="json")
+ assert created.status_code == status.HTTP_201_CREATED, created.content
+ source_id = created.json()["id"]
+ library = self.client.post(self._libraries_url(), {"name": "Docs"}, format="json")
+ assert library.status_code == status.HTTP_201_CREATED, library.content
+ library_id = library.json()["id"]
+ patched = self.client.patch(f"{self.url}{source_id}/", {"library_ids": [library_id]}, format="json")
+ assert patched.status_code == status.HTTP_200_OK, patched.content
+ assert patched.json()["library_ids"] == [library_id]
+
+ deleted = self.client.delete(f"{self._libraries_url()}{library_id}/")
+
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ assert KnowledgeSource.objects.unscoped().filter(id=source_id).exists()
+ assert KnowledgeDocument.objects.unscoped().filter(source_id=source_id).exists()
+ assert KnowledgeChunk.objects.unscoped().filter(source_id=source_id).exists()
+ assert not KnowledgeLibrary.objects.unscoped().filter(id=library_id).exists()
+ assert not KnowledgeLibrarySource.objects.unscoped().filter(source_id=source_id).exists()
+
+ def test_library_ids_patch_succeeds_while_a_url_source_is_refreshing(self, _ff) -> None:
+ created = self.client.post(self.url, {"name": "Docs", "text": "Pricing is public."}, format="json")
+ source_id = created.json()["id"]
+ KnowledgeSource.objects.unscoped().filter(id=source_id).update(
+ source_type=SourceType.URL, status=SourceStatus.PROCESSING
+ )
+ library = self.client.post(self._libraries_url(), {"name": "Docs"}, format="json")
+ library_id = library.json()["id"]
+
+ patched = self.client.patch(f"{self.url}{source_id}/", {"library_ids": [library_id]}, format="json")
+
+ assert patched.status_code == status.HTTP_200_OK, patched.content
+ assert patched.json()["library_ids"] == [library_id]
+
+ @parameterized.expand([("source",), ("library",)])
+ def test_a_rejected_patch_keeps_the_old_name(self, _ff, target: str) -> None:
+ created = self.client.post(self.url, {"name": "Docs", "text": "Pricing is public."}, format="json")
+ library = self.client.post(self._libraries_url(), {"name": "Docs"}, format="json")
+ unknown_id = "11111111-1111-1111-1111-111111111111"
+ if target == "source":
+ url = f"{self.url}{created.json()['id']}/"
+ payload = {"name": "Renamed", "library_ids": [unknown_id]}
+ else:
+ url = f"{self._libraries_url()}{library.json()['id']}/"
+ payload = {"name": "Renamed", "source_ids": [unknown_id]}
+
+ response = self.client.patch(url, payload, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert self.client.get(url).json()["name"] == "Docs"
+
+ def test_list_rejects_library_and_unfiled_together(self, _ff) -> None:
+ response = self.client.get(self.url, {"library_id": "11111111-1111-1111-1111-111111111111", "unfiled": "true"})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_library_from_another_team_is_not_found(self, _ff) -> None:
+ from posthog.models.organization import Organization
+ from posthog.models.project import Project
+ from posthog.models.team import Team
+
+ from products.business_knowledge.backend.libraries import create_library
+
+ 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)
+ library = create_library(other_team.id, "Theirs")
+
+ retrieve = self.client.get(f"{self._libraries_url()}{library.id}/")
+ search = self.client.get(
+ f"/api/projects/{self.team.id}/business_knowledge/documents/search/",
+ {"query": "pricing", "library_id": str(library.id)},
+ )
+
+ assert retrieve.status_code == status.HTTP_404_NOT_FOUND
+ assert search.status_code == status.HTTP_404_NOT_FOUND
+
+ @patch("products.business_knowledge.backend.api.libraries.has_github_repos_feature_flag", return_value=True)
+ def test_parent_repo_replace_keeps_a_child_only_link(self, _ff, _repos_flag) -> None:
+ from posthog.models.integration import Integration
+ from posthog.models.scoping import team_scope
+ from posthog.models.team import Team
+ from posthog.models.team.extensions import get_or_create_team_extension
+
+ from products.business_knowledge.backend.models import TeamBusinessKnowledgeConfig
+
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="inst-parent",
+ config={"account": {"name": "Acme"}},
+ created_by=self.user,
+ )
+ parent_config = get_or_create_team_extension(self.team, TeamBusinessKnowledgeConfig)
+ parent_config.github_integration_id = integration.id
+ parent_config.github_repos = ["acme/parent", "acme/shared"]
+ parent_config.save(update_fields=["github_integration_id", "github_repos"])
+ child = Team.objects.create(
+ organization=self.organization,
+ parent_team=self.team,
+ project=self.team.project,
+ name="Child environment",
+ )
+ child_config = get_or_create_team_extension(child, TeamBusinessKnowledgeConfig)
+ child_config.github_repos = ["acme/child-only"]
+ child_config.save(update_fields=["github_repos"])
+ library = self.client.post(self._libraries_url(), {"name": "Repos"}, format="json")
+ library_id = library.json()["id"]
+ with team_scope(self.team.id, canonical=True):
+ KnowledgeLibraryRepository.objects.create(
+ team_id=self.team.id, library_id=library_id, repo="acme/child-only"
+ )
+
+ replaced = self.client.patch(
+ f"{self._libraries_url()}{library_id}/",
+ {"repos": ["acme/parent"]},
+ format="json",
+ )
+
+ assert replaced.status_code == status.HTTP_200_OK, replaced.content
+ assert replaced.json()["repos"] == ["acme/parent"]
+ assert set(
+ KnowledgeLibraryRepository.objects.unscoped().filter(library_id=library_id).values_list("repo", flat=True)
+ ) == {"acme/parent", "acme/child-only"}
+
+ def _libraries_url(self) -> str:
+ return f"/api/projects/{self.team.id}/business_knowledge/libraries/"
+
def test_lists_live_indexed_urls(self, _ff) -> None:
from posthog.models.team import Team
diff --git a/products/business_knowledge/backend/tests/test_cross_team_isolation.py b/products/business_knowledge/backend/tests/test_cross_team_isolation.py
index d49120f6416d..28835029693b 100644
--- a/products/business_knowledge/backend/tests/test_cross_team_isolation.py
+++ b/products/business_knowledge/backend/tests/test_cross_team_isolation.py
@@ -6,8 +6,16 @@ from posthog.models.scoping import team_scope
from posthog.models.team import Team
from products.business_knowledge.backend import logic
+from products.business_knowledge.backend.libraries import create_library, list_libraries
from products.business_knowledge.backend.logic import create_text_source
-from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SafetyVerdict
+from products.business_knowledge.backend.models import (
+ KnowledgeChunk,
+ KnowledgeDocument,
+ KnowledgeLibrary,
+ KnowledgeLibrarySource,
+ KnowledgeSource,
+ SafetyVerdict,
+)
class TestCrossTeamIsolation(BaseTest):
@@ -62,3 +70,14 @@ class TestCrossTeamIsolation(BaseTest):
KnowledgeDocument.objects.unscoped().filter(team=self.team).update(safety_verdict=SafetyVerdict.UNKNOWN)
assert logic.has_ready_sources(self.team.id) is False
+
+ def test_library_and_link_reads_do_not_cross_teams(self) -> None:
+ source = KnowledgeSource.objects.unscoped().get(team=self.team, name="Team A Docs")
+ library = create_library(self.team.id, "Docs")
+ with team_scope(self.team.id, canonical=True):
+ KnowledgeLibrarySource.objects.create(team_id=self.team.id, library=library, source=source)
+
+ assert list_libraries(self.other_team.id) == []
+ assert not KnowledgeLibrary.objects.unscoped().filter(team=self.other_team).exists()
+ assert not KnowledgeLibrarySource.objects.unscoped().filter(team=self.other_team).exists()
+ assert KnowledgeLibrarySource.objects.unscoped().filter(team=self.team, library=library).exists()
diff --git a/products/business_knowledge/backend/tests/test_generated_documents.py b/products/business_knowledge/backend/tests/test_generated_documents.py
index d7d311fcce41..299d8ee256a6 100644
--- a/products/business_knowledge/backend/tests/test_generated_documents.py
+++ b/products/business_knowledge/backend/tests/test_generated_documents.py
@@ -15,6 +15,8 @@ from products.business_knowledge.backend import logic
from products.business_knowledge.backend.models import (
KnowledgeChunk,
KnowledgeDocument,
+ KnowledgeLibrary,
+ KnowledgeLibrarySource,
KnowledgeSource,
SafetyVerdict,
SourceStatus,
@@ -71,6 +73,9 @@ class TestGeneratedKnowledgeDocuments(BaseTest):
}
assert result.created is True
+ library = KnowledgeLibrary.objects.unscoped().get(team_id=self.team.id, is_default=True)
+ assert library.name == "Learned"
+ assert KnowledgeLibrarySource.objects.unscoped().filter(library=library, source_id=result.source_id).exists()
assert source.team_id == self.team.id
assert source.name == "Refund policy"
assert source.id == logic.learned_source_id_for(
@@ -140,6 +145,40 @@ class TestGeneratedKnowledgeDocuments(BaseTest):
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
+ def test_removing_a_learned_source_from_learned_sticks_across_a_retry(self) -> None:
+ first = logic.create_generated_knowledge_document(self._input())
+ KnowledgeLibrarySource.objects.unscoped().filter(source_id=first.source_id).delete()
+
+ logic.create_generated_knowledge_document(self._input())
+
+ assert not KnowledgeLibrarySource.objects.unscoped().filter(source_id=first.source_id).exists()
+
+ def test_deleting_learned_unlinks_members_and_the_next_source_recreates_it(self) -> None:
+ first = logic.create_generated_knowledge_document(self._input())
+ KnowledgeLibrary.objects.unscoped().get(team_id=self.team.id, is_default=True).delete()
+ assert not KnowledgeLibrarySource.objects.unscoped().filter(source_id=first.source_id).exists()
+
+ second = logic.create_generated_knowledge_document(
+ self._input(resolution_comment_id=uuid.UUID("30000000-0000-0000-0000-000000000003"))
+ )
+
+ library = KnowledgeLibrary.objects.unscoped().get(team_id=self.team.id, is_default=True)
+ member_ids = set(
+ KnowledgeLibrarySource.objects.unscoped().filter(library=library).values_list("source_id", flat=True)
+ )
+ assert member_ids == {second.source_id}
+
+ def test_a_library_named_learned_is_adopted_as_the_default(self) -> None:
+ with team_scope(self.team.id, canonical=True):
+ existing = KnowledgeLibrary.objects.create(team_id=self.team.id, name="learned", is_default=False)
+
+ result = logic.create_generated_knowledge_document(self._input())
+
+ existing.refresh_from_db()
+ assert existing.is_default is True
+ assert KnowledgeLibrary.objects.unscoped().filter(team_id=self.team.id).count() == 1
+ assert KnowledgeLibrarySource.objects.unscoped().filter(library=existing, source_id=result.source_id).exists()
+
@parameterized.expand(
[
("analysis_version", "conversations", "post_resolution_v2"),
diff --git a/products/business_knowledge/backend/tests/test_github_repos.py b/products/business_knowledge/backend/tests/test_github_repos.py
index 1fd6daf54136..a7e3080d5fa0 100644
--- a/products/business_knowledge/backend/tests/test_github_repos.py
+++ b/products/business_knowledge/backend/tests/test_github_repos.py
@@ -212,5 +212,86 @@ class TestBusinessKnowledgeGithubRepos(APIBaseTest):
assert found.json()["url"] == "https://github.com/acme/billing/blob/abc123/src/billing.py"
read.assert_called_once_with(BILLING, "src/billing.py", ref="abc123")
+ def test_library_search_and_file_read_use_the_allowlist_intersection(self, _capture, _flag) -> None:
+ self._connect()
+ assert self._select([BILLING, OTHER]).status_code == 200
+ self._cache(self.team, self.integration, BILLING, tree_paths="src/billing.py", readme="Billing prorates.")
+ self._cache(self.team, self.integration, OTHER, tree_paths="src/other.py", readme="Other notes.")
+ library = self._library("Billing")
+ assert (
+ self.client.patch(f"{self._libraries_url()}{library}/", {"repos": [BILLING]}, format="json").status_code
+ == 200
+ )
+
+ search = self.client.get(f"{self.base}/search/", {"query": "billing", "library_id": library})
+ outside = self.client.get(f"{self.base}/search/", {"query": "other", "repo": OTHER, "library_id": library})
+ read = self.client.get(f"{self.base}/file/", {"repo": OTHER, "path": "src/other.py", "library_id": library})
+ empty = self._library("Empty")
+
+ assert search.status_code == 200, search.json()
+ assert {hit["repo"] for hit in search.json()["results"]} == {BILLING}
+ assert outside.status_code == 400
+ assert read.status_code == 400
+ no_hits = self.client.get(f"{self.base}/search/", {"query": "billing", "library_id": empty})
+ assert no_hits.status_code == 200, no_hits.json()
+ assert no_hits.json()["results"] == []
+
+ def test_a_repo_removed_from_every_environment_loses_its_library_link(self, _capture, _flag) -> None:
+ from products.business_knowledge.backend.models import KnowledgeLibraryRepository
+
+ self._connect()
+ assert self._select([BILLING, OTHER]).status_code == 200
+ library = self._library("Repos")
+ assert (
+ self.client.patch(
+ f"{self._libraries_url()}{library}/", {"repos": [BILLING, OTHER]}, format="json"
+ ).status_code
+ == 200
+ )
+
+ assert self._select([OTHER]).status_code == 200
+
+ assert set(
+ KnowledgeLibraryRepository.objects.unscoped().filter(library_id=library).values_list("repo", flat=True)
+ ) == {OTHER}
+
+ def test_a_repo_another_environment_still_allows_keeps_its_link(self, _capture, _flag) -> None:
+ from posthog.models.team.extensions import get_or_create_team_extension
+
+ from products.business_knowledge.backend.models import KnowledgeLibraryRepository, TeamBusinessKnowledgeConfig
+
+ self._connect()
+ assert self._select([BILLING, OTHER]).status_code == 200
+ child = Team.objects.create(
+ organization=self.organization,
+ parent_team=self.team,
+ project=self.team.project,
+ name="Child environment",
+ )
+ child_config = get_or_create_team_extension(child, TeamBusinessKnowledgeConfig)
+ child_config.github_repos = [BILLING]
+ child_config.save(update_fields=["github_repos"])
+ library = self._library("Repos")
+ assert (
+ self.client.patch(
+ f"{self._libraries_url()}{library}/", {"repos": [BILLING, OTHER]}, format="json"
+ ).status_code
+ == 200
+ )
+
+ assert self._select([OTHER]).status_code == 200
+
+ assert set(
+ KnowledgeLibraryRepository.objects.unscoped().filter(library_id=library).values_list("repo", flat=True)
+ ) == {BILLING, OTHER}
+
+ def _libraries_url(self) -> str:
+ return f"/api/projects/{self.team.id}/business_knowledge/libraries/"
+
+ def _library(self, name: str) -> str:
+ response = self.client.post(self._libraries_url(), {"name": name}, format="json")
+ assert response.status_code == 201, response.content
+ return response.json()["id"]
+
def _other_team(self) -> Team:
return Team.objects.create(organization=self.organization, name="Other environment")
diff --git a/products/business_knowledge/backend/tests/test_hybrid_search.py b/products/business_knowledge/backend/tests/test_hybrid_search.py
index 76e344fe0a60..53f7aedbc4bb 100644
--- a/products/business_knowledge/backend/tests/test_hybrid_search.py
+++ b/products/business_knowledge/backend/tests/test_hybrid_search.py
@@ -1,7 +1,7 @@
import uuid
from uuid import UUID
-from posthog.test.base import BaseTest
+from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
@@ -10,18 +10,24 @@ from django.utils import timezone
from parameterized import parameterized
from posthog.models.scoping import team_scope
+from posthog.models.team import Team
from products.business_knowledge.backend import logic
from products.business_knowledge.backend.constants import BK_DRILLDOWN_MAX_RADIUS, BK_RRF_SCORE_FLOOR
+from products.business_knowledge.backend.libraries import create_library
+from products.business_knowledge.backend.llm_telemetry import RetrievalTrace
from products.business_knowledge.backend.logic import (
_rrf_fuse,
+ _semantic_chunk_candidates,
_SemanticCandidate,
get_document_window,
search_knowledge,
+ search_knowledge_for_team,
)
from products.business_knowledge.backend.models import (
KnowledgeChunk,
KnowledgeDocument,
+ KnowledgeLibrarySource,
KnowledgeSource,
SafetyVerdict,
SourceStatus,
@@ -178,6 +184,109 @@ class TestHybridSearch(BaseTest):
# FTS also finds nothing for "quantum physics experiments" so result is empty
assert results == []
+ def _file_source(self, library_id: UUID, source_id: UUID) -> None:
+ with team_scope(self.team.id, canonical=True):
+ KnowledgeLibrarySource.objects.create(team_id=self.team.id, library_id=library_id, source_id=source_id)
+
+ def test_a_source_in_two_libraries_is_returned_once_for_either(self) -> None:
+ source = self._ready_source_with_chunks(["The refund policy states thirty day returns."], name="refund")
+ other = self._ready_source_with_chunks(["Warranty covers manufacturing defects only."], name="warranty")
+ docs = create_library(self.team.id, "Docs")
+ support = create_library(self.team.id, "Support")
+ self._file_source(docs.id, source.id)
+ self._file_source(support.id, source.id)
+
+ for library_id in (docs.id, support.id):
+ results = search_knowledge(self.team.id, "refund policy", use_semantic=False, library_id=library_id)
+ names = [result.source_name for result in results]
+ assert names.count("refund") == 1
+ assert "warranty" not in names
+ assert other.name == "warranty"
+
+ def test_an_unfiled_source_is_absent_from_library_search(self) -> None:
+ self._ready_source_with_chunks(["The refund policy states thirty day returns."], name="unfiled")
+ filed = self._ready_source_with_chunks(["Warranty covers manufacturing defects only."], name="filed")
+ library = create_library(self.team.id, "Docs")
+ self._file_source(library.id, filed.id)
+
+ scoped = search_knowledge(self.team.id, "refund warranty", use_semantic=False, library_id=library.id)
+ unscoped = search_knowledge(self.team.id, "refund warranty", use_semantic=False)
+ assert {result.source_name for result in scoped} == {"filed"}
+ assert {result.source_name for result in unscoped} == {"unfiled", "filed"}
+
+ @patch("products.business_knowledge.backend.logic.generate_embedding", side_effect=RuntimeError("no gateway"))
+ def test_a_child_environment_searches_the_parent_library(self, _embed: MagicMock) -> None:
+ child = Team.objects.create(
+ organization=self.organization,
+ parent_team=self.team,
+ project=self.team.project,
+ name="Child environment",
+ )
+ self._ready_source_with_chunks(["The refund policy states thirty day returns."], name="unfiled")
+ filed = self._ready_source_with_chunks(["Warranty covers manufacturing defects only."], name="filed")
+ library = create_library(self.team.id, "Docs")
+ self._file_source(library.id, filed.id)
+
+ results = search_knowledge_for_team(
+ child, "refund warranty", trace=RetrievalTrace(surface="api"), library_id=library.id
+ )
+
+ assert {result.source_name for result in results} == {"filed"}
+
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_library_scoped_semantic_search_drops_other_sources(self, mock_semantic: MagicMock) -> None:
+ filed = self._ready_source_with_chunks(["The refund policy states thirty day returns."], name="refund")
+ outsider = self._ready_source_with_chunks(["Warranty covers manufacturing defects only."], name="warranty")
+ library = create_library(self.team.id, "Docs")
+ self._file_source(library.id, filed.id)
+ mock_semantic.return_value = [_SemanticCandidate(chunk_id=self._get_chunk_ids(outsider)[0], distance=0.1)]
+
+ results = search_knowledge(
+ self.team.id,
+ "refund policy",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ library_id=library.id,
+ )
+
+ assert {result.source_name for result in results} == {"refund"}
+
+ @patch("products.business_knowledge.backend.logic.BK_LIBRARY_SEMANTIC_DOCUMENT_CAP", 0)
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_an_oversized_library_keeps_a_member_ranked_behind_other_sources(self, mock_semantic: MagicMock) -> None:
+ member = self._ready_source_with_chunks(["The refund policy states thirty day returns."], name="refund")
+ library = create_library(self.team.id, "Docs")
+ self._file_source(library.id, member.id)
+ others = [_SemanticCandidate(chunk_id=uuid.uuid4(), distance=0.1) for _ in range(8)]
+ member_candidate = _SemanticCandidate(chunk_id=self._get_chunk_ids(member)[0], distance=0.2)
+ mock_semantic.return_value = [*others, member_candidate]
+
+ results = search_knowledge(
+ self.team.id,
+ "how long can customers send items back",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ library_id=library.id,
+ )
+
+ assert {result.source_name for result in results} == {"refund"}
+
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_an_empty_library_returns_nothing_and_skips_clickhouse(self, mock_semantic: MagicMock) -> None:
+ self._ready_source_with_chunks(["The refund policy states thirty day returns."])
+ library = create_library(self.team.id, "Empty")
+
+ results = search_knowledge(
+ self.team.id,
+ "refund policy",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ library_id=library.id,
+ )
+
+ assert results == []
+ mock_semantic.assert_not_called()
+
@parameterized.expand(
[
(
@@ -372,3 +481,76 @@ class TestDocumentWindow(BaseTest):
assert r.document_id == doc.id
assert r.source_name == "my_source"
assert "Content of chunk 0" in r.content
+
+
+class TestLibrarySemanticDocumentPredicate(ClickhouseTestMixin, BaseTest):
+ """The embedding row's document_id column is the chunk id. The knowledge document id is only in metadata."""
+
+ def test_library_filter_uses_metadata_document_id(self) -> None:
+ from datetime import UTC, datetime
+
+ from posthog.clickhouse.client import sync_execute
+
+ from products.business_knowledge.backend.constants import (
+ BK_EMBEDDING_DOCUMENT_TYPE,
+ BK_EMBEDDING_PRODUCT,
+ BK_EMBEDDING_RENDERING,
+ )
+
+ chunk_id = uuid.uuid4()
+ document_id = uuid.uuid4()
+ decoy_document_id = uuid.uuid4()
+ embedding = [0.0] * 1536
+ embedding[0] = 1.0
+ now = datetime.now(tz=UTC)
+ sync_execute(
+ """
+ INSERT INTO distributed_posthog_document_embeddings_text_embedding_3_small_1536 (
+ team_id, product, document_type, rendering, document_id, timestamp, inserted_at,
+ content, metadata, embedding, _timestamp, _offset, _partition
+ ) VALUES
+ """,
+ [
+ (
+ self.team.id,
+ BK_EMBEDDING_PRODUCT,
+ BK_EMBEDDING_DOCUMENT_TYPE,
+ BK_EMBEDDING_RENDERING,
+ str(chunk_id),
+ now,
+ now,
+ "",
+ f'{{"document_id": "{document_id}"}}',
+ embedding,
+ now,
+ 0,
+ 0,
+ ),
+ (
+ self.team.id,
+ BK_EMBEDDING_PRODUCT,
+ BK_EMBEDDING_DOCUMENT_TYPE,
+ BK_EMBEDDING_RENDERING,
+ str(document_id),
+ now,
+ now,
+ "",
+ f'{{"document_id": "{decoy_document_id}"}}',
+ embedding,
+ now,
+ 1,
+ 0,
+ ),
+ ],
+ flush=True,
+ team_id=self.team.pk,
+ )
+
+ candidates = _semantic_chunk_candidates(
+ self.team.id,
+ embedding,
+ limit=10,
+ document_ids=[str(document_id)],
+ )
+
+ assert [candidate.chunk_id for candidate in candidates] == [chunk_id]
diff --git a/products/business_knowledge/backend/tests/test_settings_api.py b/products/business_knowledge/backend/tests/test_settings_api.py
index c0c9cd076868..5643c9e5c66e 100644
--- a/products/business_knowledge/backend/tests/test_settings_api.py
+++ b/products/business_knowledge/backend/tests/test_settings_api.py
@@ -20,7 +20,13 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.models.access_control import AccessControl
from products.business_knowledge.backend.api.serializers import BusinessKnowledgeSettingsUpdateSerializer
from products.business_knowledge.backend.api.settings import BusinessKnowledgeSettingsViewSet
-from products.business_knowledge.backend.models import KnowledgeSource, TeamBusinessKnowledgeConfig
+from products.business_knowledge.backend.libraries import create_library, replace_library_sources
+from products.business_knowledge.backend.models import (
+ KnowledgeLibrary,
+ KnowledgeLibrarySource,
+ KnowledgeSource,
+ TeamBusinessKnowledgeConfig,
+)
SUPPORT_OFF_ERROR = "Turn on Support to learn from resolved tickets."
@@ -300,6 +306,7 @@ class TestBusinessKnowledgeSettingsResourceLevelAccess(APIBaseTest):
organization_member=membership,
)
self.membership = membership
+ self.source = source
self.client.force_login(member)
@parameterized.expand([("get", "GET"), ("patch", "PATCH")])
@@ -312,6 +319,21 @@ class TestBusinessKnowledgeSettingsResourceLevelAccess(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
assert get_or_create_team_extension(self.team, TeamBusinessKnowledgeConfig).learn_from_support_enabled is False
+ def test_a_grant_on_one_source_does_not_change_its_libraries(self, _ff) -> None:
+ library = create_library(self.team.id, "Docs")
+ replace_library_sources(self.team.id, library.id, [self.source.id])
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/business_knowledge/sources/{self.source.id}/",
+ {"library_ids": []},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert (
+ KnowledgeLibrarySource.objects.unscoped().filter(library_id=library.id, source_id=self.source.id).exists()
+ )
+
@parameterized.expand([("get", "GET"), ("patch", "PATCH")])
def test_a_child_environment_grant_does_not_open_the_parent_setting(self, _ff, _name: str, method: str) -> None:
# The config row is the parent project's, so RBAC on the child environment's URL must
@@ -339,6 +361,47 @@ class TestBusinessKnowledgeSettingsResourceLevelAccess(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
assert get_or_create_team_extension(self.team, TeamBusinessKnowledgeConfig).learn_from_support_enabled is False
+ @parameterized.expand(
+ [
+ ("create_library", "post", "libraries/", {"name": "Docs"}),
+ ("search_documents", "get", "documents/search/", {"query": "refund"}),
+ ]
+ )
+ def test_a_child_environment_grant_does_not_open_project_knowledge(
+ self, _ff, _name: str, method: str, path: str, data: dict[str, str]
+ ) -> None:
+ environment = Team.objects.create(
+ organization=self.organization, parent_team=self.team, project=self.team.project, name="Child environment"
+ )
+ AccessControl.objects.create(
+ team=environment, resource="business_knowledge", access_level="editor", organization_member=self.membership
+ )
+
+ url = f"/api/projects/{environment.id}/business_knowledge/{path}"
+ response = self.client.post(url, data, format="json") if method == "post" else self.client.get(url, data)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert not KnowledgeLibrary.objects.unscoped().filter(team_id=self.team.id).exists()
+
+ @parameterized.expand([("list_libraries", "libraries/"), ("search_documents", "documents/search/?query=refund")])
+ def test_a_member_denied_the_parent_project_cannot_reach_it_from_a_child(self, _ff, _name: str, path: str) -> None:
+ environment = Team.objects.create(
+ organization=self.organization, parent_team=self.team, project=self.team.project, name="Child environment"
+ )
+ outsider = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=outsider, organization=self.organization),
+ )
+ self.client.force_login(outsider)
+
+ response = self.client.get(f"/api/projects/{environment.id}/business_knowledge/{path}")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+
@patch("posthoganalytics.feature_enabled", return_value=True)
class TestBusinessKnowledgeResourceLevelRule(APIBaseTest):
diff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.ts
index c590199a204a..861038121a47 100644
--- a/products/business_knowledge/frontend/api.ts
+++ b/products/business_knowledge/frontend/api.ts
@@ -2,6 +2,10 @@ import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { apiMutator } from '../../../frontend/src/lib/api-orval-mutator'
import {
+ businessKnowledgeLibrariesCreate,
+ businessKnowledgeLibrariesDestroy,
+ businessKnowledgeLibrariesList,
+ businessKnowledgeLibrariesPartialUpdate,
businessKnowledgePlaygroundChatsAskCreate,
businessKnowledgePlaygroundChatsCreate,
businessKnowledgePlaygroundChatsDestroy,
@@ -21,6 +25,7 @@ import type {
BusinessKnowledgeSourcesListParams,
BusinessKnowledgeSourcesListSourceType,
CrawlModeEnumApi,
+ KnowledgeLibraryApi,
KnowledgeSourceApi,
PlaygroundChatApi,
PlaygroundChatListApi,
@@ -58,12 +63,15 @@ export interface UpdateSourcePayload {
max_depth?: number
refresh_interval?: RefreshIntervalValue
always_include?: boolean
+ library_ids?: string[]
}
export async function listSources(params?: {
search?: string
sourceType?: string
addedBy?: string
+ libraryId?: string
+ unfiled?: boolean
}): Promise<KnowledgeSourceApi[]> {
const search = params?.search?.trim()
const sourceType =
@@ -79,6 +87,8 @@ export async function listSources(params?: {
...(search ? { search } : {}),
...(sourceType ? { source_type: sourceType } : {}),
...(addedBy ? { added_by: addedBy } : {}),
+ ...(params?.libraryId ? { library_id: params.libraryId } : {}),
+ ...(params?.unfiled ? { unfiled: true } : {}),
}
const response = await businessKnowledgeSourcesList(String(getCurrentTeamId()), query)
return response.results
@@ -157,3 +167,24 @@ export async function deletePlaygroundChat(chatId: string): Promise<void> {
export async function refreshSource(id: string): Promise<KnowledgeSourceApi> {
return await businessKnowledgeSourcesRefreshCreate(String(getCurrentTeamId()), id)
}
+
+export type KnowledgeLibrary = KnowledgeLibraryApi
+
+export async function listLibraries(): Promise<KnowledgeLibrary[]> {
+ return await businessKnowledgeLibrariesList(String(getCurrentTeamId()))
+}
+
+export async function createLibrary(name: string): Promise<KnowledgeLibrary> {
+ return await businessKnowledgeLibrariesCreate(String(getCurrentTeamId()), { name })
+}
+
+export async function updateLibrary(
+ id: string,
+ payload: { name?: string; source_ids?: string[]; repos?: string[] }
+): Promise<KnowledgeLibrary> {
+ return await businessKnowledgeLibrariesPartialUpdate(String(getCurrentTeamId()), id, payload)
+}
+
+export async function deleteLibrary(id: string): Promise<void> {
+ await businessKnowledgeLibrariesDestroy(String(getCurrentTeamId()), id)
+}
diff --git a/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.test.tsx b/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.test.tsx
index 6663078f6f19..bb984870eba7 100644
--- a/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.test.tsx
+++ b/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.test.tsx
@@ -12,7 +12,7 @@ describe('BusinessKnowledgeTabs', () => {
it('links Settings to the in-product settings scene', () => {
render(<BusinessKnowledgeTabs activeTab="sources" />)
- expect(screen.getByText('Sources').closest('a')).toHaveAttribute('href', '/business-knowledge')
+ expect(screen.getByText('Libraries').closest('a')).toHaveAttribute('href', '/business-knowledge')
expect(screen.getByText('Playground').closest('a')).toHaveAttribute('href', '/business-knowledge/playground')
expect(screen.getByText('Settings').closest('a')).toHaveAttribute('href', '/business-knowledge/settings')
})
diff --git a/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.tsx b/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.tsx
index 5a9c722374e8..2a6889fee4c0 100644
--- a/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.tsx
+++ b/products/business_knowledge/frontend/components/BusinessKnowledgeTabs/BusinessKnowledgeTabs.tsx
@@ -12,7 +12,7 @@ export function BusinessKnowledgeTabs({ activeTab }: { activeTab: BusinessKnowle
tabs={[
{
key: 'sources',
- label: 'Sources',
+ label: 'Libraries',
link: urls.businessKnowledge(),
// pinned: autocapture / Playwright key. Do not rename.
'data-attr': 'business-knowledge-tab-sources',
diff --git a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx
index e5ecbbe040d7..f01b8fbe872a 100644
--- a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx
+++ b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { LemonButton, LemonModal, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
@@ -27,9 +27,18 @@ export function CreateKnowledgeSourceModal({
isUrlSourceSubmitting,
isFileSourceSubmitting,
urlSource,
+ libraries,
+ createLibraryIds,
} = useValues(businessKnowledgeLogic)
- const { closeCreateModal, setCreateTab, submitTextSource, submitUrlSource, submitFileSource, setFileSourceValue } =
- useActions(businessKnowledgeLogic)
+ const {
+ closeCreateModal,
+ setCreateTab,
+ submitTextSource,
+ submitUrlSource,
+ submitFileSource,
+ setFileSourceValue,
+ setCreateLibraryIds,
+ } = useActions(businessKnowledgeLogic)
return (
<LemonModal
@@ -162,6 +171,18 @@ export function CreateKnowledgeSourceModal({
},
]}
/>
+ {libraries.length > 0 && (
+ <LemonField.Pure label="Libraries" className="mt-2">
+ <LemonInputSelect
+ mode="multiple"
+ value={createLibraryIds}
+ options={libraries.map((library) => ({ key: library.id, label: library.name }))}
+ onChange={setCreateLibraryIds}
+ placeholder="No library"
+ data-attr="business-knowledge-create-libraries"
+ />
+ </LemonField.Pure>
+ )}
</LemonModal>
)
}
diff --git a/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.test.tsx b/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.test.tsx
index 8f0c3a1c4b3e..3300e8b9fcf9 100644
--- a/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.test.tsx
+++ b/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.test.tsx
@@ -9,14 +9,14 @@ describe('businessKnowledgeEmptyState', () => {
cleanup()
})
- it('keeps Sources and Settings reachable before any source exists', () => {
+ it('keeps Libraries and Settings reachable before any source exists', () => {
const SceneNav = businessKnowledgeEmptyState.SceneNav
if (!SceneNav) {
throw new Error('SceneNav is missing')
}
render(<SceneNav />)
- expect(screen.getByText('Sources').closest('a')).toHaveAttribute('href', '/business-knowledge')
+ expect(screen.getByText('Libraries').closest('a')).toHaveAttribute('href', '/business-knowledge')
expect(screen.getByText('Settings').closest('a')).toHaveAttribute('href', '/business-knowledge/settings')
})
})
diff --git a/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.tsx b/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.tsx
index f588f9624368..cdd80470ccdf 100644
--- a/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.tsx
+++ b/products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState.tsx
@@ -18,7 +18,7 @@ export const businessKnowledgeEmptyState: SceneProductEmptyState = {
statusLogic: businessKnowledgeSetupLogic,
// The scene already shows "not found" when the flag is off, so keep the gate behind it.
featureFlag: FEATURE_FLAGS.PRODUCT_BUSINESS_KNOWLEDGE,
- // The gate replaces the scene, so the Sources / Settings tab bar inside it never mounts.
+ // The gate replaces the scene, so the Libraries / Settings tab bar inside it never mounts.
// Keep it on the frame so Settings stays reachable with no sources yet.
SceneNav: function BusinessKnowledgeEmptyStateNav(): JSX.Element {
return <BusinessKnowledgeTabs activeTab="sources" />
diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.ts
index 33ffebae32b6..713f86a8c1ce 100644
--- a/products/business_knowledge/frontend/generated/api.schemas.ts
+++ b/products/business_knowledge/frontend/generated/api.schemas.ts
@@ -120,6 +120,39 @@ export interface GapTopicActionResultApi {
readonly updated: number
}
+export interface KnowledgeLibraryApi {
+ /** Library id. */
+ id: string
+ /** Library name. Unique in this project, ignoring case. */
+ name: string
+ /** True for the library new learned sources join. There is at most one. */
+ is_default: boolean
+ /** How many sources are in this library. */
+ source_count: number
+ /** Selected repositories in this library that this environment is allowed to read. */
+ repos: string[]
+}
+
+export interface KnowledgeLibraryCreateApi {
+ /**
+ * Name for the new library.
+ * @maxLength 255
+ */
+ name: string
+}
+
+export interface PatchedKnowledgeLibraryUpdateApi {
+ /**
+ * New name. Omit to keep the current name.
+ * @maxLength 255
+ */
+ name?: string
+ /** Replaces every source in this library. Omit to leave sources unchanged. An empty list removes them all. */
+ source_ids?: string[]
+ /** Replaces this environment's repositories in the library. Omit to leave them unchanged. Repositories only another environment allows stay. */
+ repos?: string[]
+}
+
export interface PlaygroundChatListApi {
/** Playground chat id. */
id: string
@@ -501,6 +534,8 @@ export interface KnowledgeSourceApi {
/** @nullable */
readonly file_size_bytes: number | null
readonly always_include: boolean
+ /** Libraries this source belongs to. Empty when the source is in none. */
+ readonly library_ids: readonly string[]
}
export interface PaginatedKnowledgeSourceListApi {
@@ -538,6 +573,8 @@ export interface PatchedUpdateTextSourceApi {
text?: string
/** When true, this source's content is injected into every support reply prompt as general context. */
always_include?: boolean
+ /** Replaces the libraries this source belongs to. Omit to leave membership unchanged. An empty list removes it from every library. */
+ library_ids?: string[]
}
/**
@@ -589,6 +626,10 @@ export type BusinessKnowledgeDocumentsWindowListParams = {
}
export type BusinessKnowledgeDocumentsSearchListParams = {
+ /**
+ * Limit retrieval to sources in this library. Pass the same id to repository search and file read. Omit to search every ready source.
+ */
+ library_id?: string
/**
* Maximum number of ranked chunks to return. Defaults to 10, capped at 20.
*/
@@ -619,6 +660,10 @@ export type BusinessKnowledgeGapSuggestionsListParams = {
}
export type BusinessKnowledgeRepositoriesFileRetrieveParams = {
+ /**
+ * Require the repository to be in this library. Pass the same id used for document search and repository search. Omit to read any selected repository.
+ */
+ library_id?: string
/**
* File path returned by the repository search.
* @minLength 1
@@ -632,6 +677,10 @@ export type BusinessKnowledgeRepositoriesFileRetrieveParams = {
}
export type BusinessKnowledgeRepositoriesSearchParams = {
+ /**
+ * Limit the search to repositories in this library. Pass the same id to document search and file read. Omit to search every selected repository.
+ */
+ library_id?: string
/**
* File names, path fragments, or identifiers to match. Not a full sentence.
* @minLength 1
@@ -648,6 +697,10 @@ export type BusinessKnowledgeSourcesListParams = {
* Filter by who added the source: human (you added it) or learned (from a resolved support ticket).
*/
added_by?: BusinessKnowledgeSourcesListAddedBy
+ /**
+ * Return only sources in this library. Do not combine with unfiled.
+ */
+ library_id?: string
/**
* Number of results to return per page.
*/
@@ -664,6 +717,10 @@ export type BusinessKnowledgeSourcesListParams = {
* Filter to a single source type (text, url, or file).
*/
source_type?: BusinessKnowledgeSourcesListSourceType
+ /**
+ * When true, return only sources that are in no library. Do not combine with library_id.
+ */
+ unfiled?: boolean
}
export type BusinessKnowledgeSourcesListAddedBy =
diff --git a/products/business_knowledge/frontend/generated/api.ts b/products/business_knowledge/frontend/generated/api.ts
index d5f70b6fccf4..67caeaf17a79 100644
--- a/products/business_knowledge/frontend/generated/api.ts
+++ b/products/business_knowledge/frontend/generated/api.ts
@@ -24,12 +24,15 @@ import type {
GapTopicActionResultApi,
KnowledgeDocumentWindowApi,
KnowledgeGapSuggestionApi,
+ KnowledgeLibraryApi,
+ KnowledgeLibraryCreateApi,
KnowledgeSearchResultApi,
KnowledgeSourceApi,
PaginatedKnowledgeGapSuggestionListApi,
PaginatedKnowledgeSourceDocumentListApi,
PaginatedKnowledgeSourceListApi,
PatchedBusinessKnowledgeSettingsUpdateApi,
+ PatchedKnowledgeLibraryUpdateApi,
PatchedUpdateTextSourceApi,
PlaygroundChatApi,
PlaygroundChatListApi,
@@ -262,6 +265,103 @@ export const businessKnowledgeGapSuggestionsDismissTopicCreate = async (
})
}
+export const getBusinessKnowledgeLibrariesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/business_knowledge/libraries/`
+}
+
+/**
+ * Libraries in this project. The default library is first.
+ * @summary List business knowledge libraries
+ */
+export const businessKnowledgeLibrariesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<KnowledgeLibraryApi[]> => {
+ return apiMutator<KnowledgeLibraryApi[]>(getBusinessKnowledgeLibrariesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getBusinessKnowledgeLibrariesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/business_knowledge/libraries/`
+}
+
+/**
+ * @summary Create a business knowledge library
+ */
+export const businessKnowledgeLibrariesCreate = async (
+ projectId: string,
+ knowledgeLibraryCreateApi: KnowledgeLibraryCreateApi,
+ options?: RequestInit
+): Promise<KnowledgeLibraryApi> => {
+ return apiMutator<KnowledgeLibraryApi>(getBusinessKnowledgeLibrariesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(knowledgeLibraryCreateApi),
+ })
+}
+
+export const getBusinessKnowledgeLibrariesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/business_knowledge/libraries/${id}/`
+}
+
+/**
+ * @summary Get a business knowledge library
+ */
+export const businessKnowledgeLibrariesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<KnowledgeLibraryApi> => {
+ return apiMutator<KnowledgeLibraryApi>(getBusinessKnowledgeLibrariesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getBusinessKnowledgeLibrariesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/business_knowledge/libraries/${id}/`
+}
+
+/**
+ * Send only the fields you want to change. `source_ids` replaces every source in the library. `repos` replaces this environment's repositories and leaves repositories that only another environment allows.
+ * @summary Rename a library or replace its sources and repositories
+ */
+export const businessKnowledgeLibrariesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedKnowledgeLibraryUpdateApi?: PatchedKnowledgeLibraryUpdateApi,
+ options?: RequestInit
+): Promise<KnowledgeLibraryApi> => {
+ return apiMutator<KnowledgeLibraryApi>(getBusinessKnowledgeLibrariesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedKnowledgeLibraryUpdateApi),
+ })
+}
+
+export const getBusinessKnowledgeLibrariesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/business_knowledge/libraries/${id}/`
+}
+
+/**
+ * Removes the library and its links. Sources, documents, and selected repositories stay.
+ * @summary Delete a business knowledge library
+ */
+export const businessKnowledgeLibrariesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getBusinessKnowledgeLibrariesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getBusinessKnowledgePlaygroundChatsListUrl = (projectId: string) => {
return `/api/projects/${projectId}/business_knowledge/playground/chats/`
}
diff --git a/products/business_knowledge/frontend/generated/api.zod.ts b/products/business_knowledge/frontend/generated/api.zod.ts
index 3cff400245cf..21d8f81bf3ef 100644
--- a/products/business_knowledge/frontend/generated/api.zod.ts
+++ b/products/business_knowledge/frontend/generated/api.zod.ts
@@ -37,6 +37,41 @@ export const BusinessKnowledgeGapSuggestionsDismissTopicCreateBody = /* @__PURE_
resolved_source_id: zod.uuid().nullish().describe('Optional knowledge source to link when accepting.'),
})
+/**
+ * @summary Create a business knowledge library
+ */
+export const businessKnowledgeLibrariesCreateBodyNameMax = 255
+
+export const BusinessKnowledgeLibrariesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(businessKnowledgeLibrariesCreateBodyNameMax).describe('Name for the new library.'),
+})
+
+/**
+ * Send only the fields you want to change. `source_ids` replaces every source in the library. `repos` replaces this environment's repositories and leaves repositories that only another environment allows.
+ * @summary Rename a library or replace its sources and repositories
+ */
+export const businessKnowledgeLibrariesPartialUpdateBodyNameMax = 255
+
+export const BusinessKnowledgeLibrariesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(businessKnowledgeLibrariesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('New name. Omit to keep the current name.'),
+ source_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe(
+ 'Replaces every source in this library. Omit to leave sources unchanged. An empty list removes them all.'
+ ),
+ repos: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "Replaces this environment's repositories in the library. Omit to leave them unchanged. Repositories only another environment allows stay."
+ ),
+})
+
/**
* Append a turn and start a sandbox run. A second question in the same chat while its answer is still open returns 409. Other chats can run at the same time, up to 3 open answers per person.
* @summary Ask a question in a playground chat
@@ -139,6 +174,12 @@ export const BusinessKnowledgeSourcesPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"When true, this source's content is injected into every support reply prompt as general context."
),
+ library_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe(
+ 'Replaces the libraries this source belongs to. Omit to leave membership unchanged. An empty list removes it from every library.'
+ ),
})
.describe(
'PATCH payload for text sources. All fields optional, at least one\nrequired. `text` triggers a re-chunk; `name` or `always_include` alone does not.'
diff --git a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.stories.tsx b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.stories.tsx
index 5e9dc73dc621..7e16cfd662a6 100644
--- a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.stories.tsx
+++ b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.stories.tsx
@@ -1,17 +1,28 @@
import type { Meta, StoryObj } from '@storybook/react'
+import type { KnowledgeLibrary } from '../../api'
import type { KnowledgeSource } from '../sources/businessKnowledgeLogic'
import { KnowledgeSourceDetails } from './KnowledgeSourceDetails'
+const LEARNED_LIBRARY_ID = '22222222-2222-2222-2222-222222222222'
+
+const LIBRARIES: KnowledgeLibrary[] = [
+ { id: LEARNED_LIBRARY_ID, name: 'Learned', is_default: true, source_count: 4, repos: [] },
+ { id: '33333333-3333-3333-3333-333333333333', name: 'Product docs', is_default: false, source_count: 2, repos: [] },
+]
+
const meta: Meta<typeof KnowledgeSourceDetails> = {
title: 'Scenes-App/BusinessKnowledge/KnowledgeSourceDetails',
component: KnowledgeSourceDetails,
parameters: { layout: 'padded', viewMode: 'story', mockDate: '2026-09-24' },
args: {
+ libraries: LIBRARIES,
isRefreshing: false,
isDeleting: false,
+ isSavingLibraries: false,
onRefresh: () => undefined,
onDelete: () => undefined,
+ onLibrariesChange: () => undefined,
},
decorators: [
(Story) => (
@@ -55,6 +66,7 @@ function makeSource(overrides: Partial<KnowledgeSource> = {}): KnowledgeSource {
file_content_type: '',
file_size_bytes: null,
always_include: false,
+ library_ids: [],
...overrides,
}
}
@@ -94,6 +106,7 @@ export const Learned: Story = {
is_generated: true,
learned_from_ticket_number: 42,
learned_from_ticket_url: 'https://us.posthog.com/project/1/support/tickets/42',
+ library_ids: [LEARNED_LIBRARY_ID],
}),
},
}
diff --git a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx
index 231acbf7c45c..d63cc52a77eb 100644
--- a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx
+++ b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx
@@ -5,8 +5,10 @@ import { LemonButton, LemonCard, LemonDialog, LemonTag, Link } from '@posthog/le
import { TZLabel } from 'lib/components/TZLabel'
+import type { KnowledgeLibrary } from '../../api'
import { StatusTag } from '../../components/StatusTag/StatusTag'
import type { KnowledgeSource } from '../sources/businessKnowledgeLogic'
+import { SourceLibraries } from './SourceLibraries'
const SOURCE_TYPE_LABELS: Record<KnowledgeSource['source_type'], string> = {
text: 'Text',
@@ -46,18 +48,24 @@ function DetailRow({ label, children }: { label: string; children: ReactNode }):
export interface KnowledgeSourceDetailsProps {
source: KnowledgeSource
+ libraries: KnowledgeLibrary[]
isRefreshing: boolean
isDeleting: boolean
+ isSavingLibraries: boolean
onRefresh: () => void
onDelete: () => void
+ onLibrariesChange: (libraryIds: string[]) => void
}
export function KnowledgeSourceDetails({
source,
+ libraries,
isRefreshing,
isDeleting,
+ isSavingLibraries,
onRefresh,
onDelete,
+ onLibrariesChange,
}: KnowledgeSourceDetailsProps): JSX.Element {
const canRefresh = source.source_type === 'url' && !source.is_generated
@@ -146,6 +154,12 @@ export function KnowledgeSourceDetails({
<span translate="no">{formatFileSize(source.file_size_bytes)}</span>
</DetailRow>
) : null}
+ <SourceLibraries
+ libraries={libraries}
+ selectedIds={source.library_ids}
+ saving={isSavingLibraries}
+ onChange={onLibrariesChange}
+ />
</div>
<div className="mt-3 flex flex-wrap justify-end gap-2 border-t pt-3">
{canRefresh ? (
diff --git a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceScene.tsx b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceScene.tsx
index 31e38ed479ca..ad70265c8fdb 100644
--- a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceScene.tsx
+++ b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceScene.tsx
@@ -58,9 +58,18 @@ export function KnowledgeSourceScene(): JSX.Element {
sourceDocuments,
sourceDocumentsLoaded,
sourceDocumentsFailed,
+ libraries,
+ savingLibraries,
} = useValues(knowledgeSourceLogic)
- const { loadSource, loadSourceDocuments, submitEditSource, submitEditUrlSource, refreshSource, deleteSource } =
- useActions(knowledgeSourceLogic)
+ const {
+ loadSource,
+ loadSourceDocuments,
+ submitEditSource,
+ submitEditUrlSource,
+ refreshSource,
+ deleteSource,
+ saveSourceLibraries,
+ } = useActions(knowledgeSourceLogic)
if (!isEnabled) {
return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />
@@ -85,7 +94,7 @@ export function KnowledgeSourceScene(): JSX.Element {
if (!source) {
return (
<SceneContent>
- <LemonBanner type="error" action={{ children: 'Try again', onClick: loadSource }}>
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadSource() }}>
Couldn't load this knowledge source. Try again.
</LemonBanner>
</SceneContent>
@@ -207,10 +216,13 @@ export function KnowledgeSourceScene(): JSX.Element {
<div className="min-w-0 @min-[48rem]/main-content:w-80 @min-[48rem]/main-content:shrink-0">
<KnowledgeSourceDetails
source={source}
+ libraries={libraries}
isRefreshing={isRefreshing}
isDeleting={isDeleting}
+ isSavingLibraries={savingLibraries}
onRefresh={() => refreshSource()}
onDelete={() => deleteSource()}
+ onLibrariesChange={saveSourceLibraries}
/>
</div>
</div>
diff --git a/products/business_knowledge/frontend/scenes/source/SourceLibraries.tsx b/products/business_knowledge/frontend/scenes/source/SourceLibraries.tsx
new file mode 100644
index 000000000000..82f7f11533e7
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/source/SourceLibraries.tsx
@@ -0,0 +1,34 @@
+import { LemonInputSelect } from '@posthog/lemon-ui'
+
+import type { KnowledgeLibrary } from '../../api'
+
+export function SourceLibraries({
+ libraries,
+ selectedIds,
+ saving,
+ onChange,
+}: {
+ libraries: KnowledgeLibrary[]
+ selectedIds: readonly string[]
+ saving: boolean
+ onChange: (libraryIds: string[]) => void
+}): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-muted-alt">Libraries</span>
+ <LemonInputSelect
+ mode="multiple"
+ value={[...selectedIds]}
+ options={libraries.map((library) => ({ key: library.id, label: library.name }))}
+ onChange={(libraryIds) => {
+ if (saving) {
+ return
+ }
+ onChange(libraryIds)
+ }}
+ loading={saving}
+ placeholder="No library"
+ />
+ </div>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.test.ts b/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.test.ts
index 1b840cfba19d..da86422dbd26 100644
--- a/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.test.ts
+++ b/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.test.ts
@@ -14,6 +14,7 @@ jest.mock('../../api', () => ({
updateSource: jest.fn(),
deleteSource: jest.fn(),
refreshSource: jest.fn(),
+ listLibraries: jest.fn(),
}))
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
@@ -54,6 +55,7 @@ const MOCK_SOURCE: KnowledgeSourceApi = {
file_content_type: '',
file_size_bytes: null,
always_include: false,
+ library_ids: [],
}
const mockedApi = api as jest.Mocked<typeof api>
@@ -69,6 +71,7 @@ describe('knowledgeSourceLogic', () => {
mockedApi.getSourceDocuments.mockResolvedValue([])
mockedApi.updateSource.mockResolvedValue({ ...MOCK_SOURCE, name: 'Updated policy', chunk_count: 4 })
mockedApi.deleteSource.mockResolvedValue(undefined)
+ mockedApi.listLibraries.mockResolvedValue([])
logic = knowledgeSourceLogic({ id: SOURCE_ID })
logic.mount()
})
@@ -177,6 +180,24 @@ describe('knowledgeSourceLogic', () => {
expect(logic.values.sourceDocumentsLoaded).toBe(true)
})
+ it('keeps saved libraries when an older source read lands after the save', async () => {
+ const libraryId = '22222222-2222-2222-2222-222222222222'
+ await expectLogic(logic).toFinishAllListeners()
+ let resolveRead: (source: KnowledgeSourceApi) => void = () => {}
+ mockedApi.getSource.mockReturnValue(new Promise((resolve) => (resolveRead = resolve)))
+ mockedApi.updateSource.mockResolvedValue({ ...MOCK_SOURCE, library_ids: [libraryId] })
+
+ logic.actions.loadSource()
+ await expectLogic(logic, () => {
+ logic.actions.saveSourceLibraries([libraryId])
+ }).toDispatchActions(['finishLibrarySave'])
+ expect(logic.values.source?.library_ids).toEqual([libraryId])
+ resolveRead(MOCK_SOURCE)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.source?.library_ids).toEqual([libraryId])
+ })
+
it('keeps the source when the indexed page list fails', async () => {
logic.unmount()
mockedApi.getSource.mockResolvedValue({
diff --git a/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.ts b/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.ts
index fca799610063..21f482d8ba8b 100644
--- a/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.ts
+++ b/products/business_knowledge/frontend/scenes/source/knowledgeSourceLogic.ts
@@ -15,6 +15,7 @@ import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
@@ -23,9 +24,17 @@ import { urls } from 'scenes/urls'
import type { Breadcrumb } from '~/types'
-import { deleteSource, getSource, getSourceDocuments, getSourceText, refreshSource, updateSource } from '../../api'
-import type { UpdateSourcePayload } from '../../api'
-import type { KnowledgeSourceApi, KnowledgeSourceDocumentApi } from '../../generated/api.schemas'
+import {
+ deleteSource,
+ getSource,
+ getSourceDocuments,
+ getSourceText,
+ listLibraries,
+ refreshSource,
+ updateSource,
+} from '../../api'
+import type { KnowledgeLibrary, UpdateSourcePayload } from '../../api'
+import type { KnowledgeLibraryApi, KnowledgeSourceApi, KnowledgeSourceDocumentApi } from '../../generated/api.schemas'
import {
DEFAULT_URL_SOURCE_FORM,
type CrawlMode,
@@ -89,6 +98,9 @@ export interface knowledgeSourceLogicValues {
isEditUrlSourceValid: boolean
isRefreshing: boolean
isSourceTextReady: boolean
+ libraries: KnowledgeLibrary[]
+ librariesLoading: boolean
+ savingLibraries: boolean
showEditSourceErrors: boolean
showEditUrlSourceErrors: boolean
source: KnowledgeSource | null
@@ -114,7 +126,25 @@ export interface knowledgeSourceLogicActions {
deleteSourceDone: () => {
value: true
}
- loadSource: () => any
+ finishLibrarySave: () => {
+ value: true
+ }
+ loadLibraries: () => any
+ loadLibrariesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadLibrariesSuccess: (
+ libraries: KnowledgeLibraryApi[],
+ payload?: any
+ ) => {
+ libraries: KnowledgeLibraryApi[]
+ payload?: any
+ }
+ loadSource: (_: void) => void
loadSourceDocuments: (_: void) => void
loadSourceDocumentsFailure: (
error: string,
@@ -139,10 +169,10 @@ export interface knowledgeSourceLogicActions {
}
loadSourceSuccess: (
source: KnowledgeSourceApi | null,
- payload?: any
+ payload?: void
) => {
source: KnowledgeSourceApi | null
- payload?: any
+ payload?: void
}
loadSourceText: () => any
loadSourceTextFailure: (
@@ -180,6 +210,9 @@ export interface knowledgeSourceLogicActions {
resetEditUrlSource: (values?: UrlSourceFormValues) => {
values?: UrlSourceFormValues
}
+ saveSourceLibraries: (libraryIds: string[]) => {
+ libraryIds: string[]
+ }
setEditSourceManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -279,6 +312,8 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
deleteSourceDone: true,
refreshSource: true,
refreshSourceDone: true,
+ saveSourceLibraries: (libraryIds: string[]) => ({ libraryIds }),
+ finishLibrarySave: true,
}),
reducers({
sourceNotFound: [
@@ -302,6 +337,13 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
refreshSourceDone: () => false,
},
],
+ savingLibraries: [
+ false,
+ {
+ saveSourceLibraries: () => true,
+ finishLibrarySave: () => false,
+ },
+ ],
sourceTextFailed: [
false,
{
@@ -327,13 +369,20 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
},
],
}),
- loaders(({ actions, props }) => ({
+ loaders(({ actions, props, values, cache }) => ({
source: [
null as KnowledgeSource | null,
{
- loadSource: async () => {
+ loadSource: async (_: void, breakpoint) => {
+ const librarySaves = cache.librarySaves ?? 0
try {
- return await getSource(props.id)
+ const source = await getSource(props.id)
+ breakpoint()
+ // A library save publishes its own response, which is newer than a read that started before it.
+ if ((cache.librarySaves ?? 0) !== librarySaves) {
+ return values.source
+ }
+ return source
} catch (error: unknown) {
// Catch 404 here so initKea does not toast. The scene renders NotFound.
if ((error as { status?: number } | null)?.status === 404) {
@@ -364,6 +413,12 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
},
},
],
+ libraries: [
+ [] as KnowledgeLibrary[],
+ {
+ loadLibraries: async () => await listLibraries(),
+ },
+ ],
})),
forms(({ actions, values, props }) => ({
editSource: {
@@ -447,6 +502,18 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
},
})),
listeners(({ actions, values, props, cache }) => ({
+ saveSourceLibraries: async ({ libraryIds }) => {
+ try {
+ const source = await updateSource(props.id, { library_ids: libraryIds })
+ cache.librarySaves = (cache.librarySaves ?? 0) + 1
+ actions.loadSourceSuccess(source)
+ posthog.capture('business knowledge source libraries changed', { library_count: libraryIds.length })
+ } catch (error: any) {
+ lemonToast.error(error?.detail || error?.data?.library_ids?.[0] || 'Could not update libraries.')
+ } finally {
+ actions.finishLibrarySave()
+ }
+ },
loadSourceSuccess: ({ source }) => {
if (!source) {
cache.disposables.dispose('pollProcessing')
@@ -550,5 +617,6 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
}),
afterMount(({ actions }) => {
actions.loadSource()
+ actions.loadLibraries()
}),
])
diff --git a/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.test.tsx b/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.test.tsx
index 3ede81616d05..ba0bdfc5d6d8 100644
--- a/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.test.tsx
+++ b/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.test.tsx
@@ -83,6 +83,7 @@ function makeSource(overrides: Partial<KnowledgeSource> = {}): KnowledgeSource {
file_content_type: '',
file_size_bytes: null,
always_include: false,
+ library_ids: [],
...overrides,
}
}
@@ -108,6 +109,10 @@ describe('BusinessKnowledgeScene', () => {
searchTerm: '',
sourceTypeFilter: 'all',
addedByFilter: 'all',
+ libraries: [],
+ libraryScope: 'all',
+ savingLibrary: false,
+ libraryDialog: null,
})
})
@@ -135,6 +140,10 @@ describe('BusinessKnowledgeScene', () => {
searchTerm: '',
sourceTypeFilter: 'all',
addedByFilter: 'all',
+ libraries: [],
+ libraryScope: 'all',
+ savingLibrary: false,
+ libraryDialog: null,
})
render(<BusinessKnowledgeScene />)
diff --git a/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.tsx
index d04371b47d61..f35bf4dd9490 100644
--- a/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.tsx
+++ b/products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene.tsx
@@ -8,10 +8,13 @@ import { NotFound } from 'lib/components/NotFound'
import { TZLabel } from 'lib/components/TZLabel'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { newInternalTab } from 'lib/utils/newInternalTab'
+import { pluralize } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneDivider } from '~/layout/scenes/components/SceneDivider'
+import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
@@ -19,9 +22,19 @@ import { BusinessKnowledgeTabs } from '../../components/BusinessKnowledgeTabs/Bu
import { CreateKnowledgeSourceModal } from '../../components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal'
import { StatusTag } from '../../components/StatusTag/StatusTag'
import { businessKnowledgeEmptyState } from '../../emptyState/businessKnowledgeEmptyState'
-import { KnowledgeSource, REFRESH_INTERVAL_OPTIONS, businessKnowledgeLogic } from './businessKnowledgeLogic'
+import {
+ KnowledgeSource,
+ REFRESH_INTERVAL_OPTIONS,
+ LIBRARY_SCOPE_ALL,
+ LIBRARY_SCOPE_UNFILED,
+ businessKnowledgeLogic,
+} from './businessKnowledgeLogic'
import { KnowledgeSourceNameCell } from './KnowledgeSourceNameCell'
+import { LibraryDialog } from './LibraryDialog'
+import { LibraryRow } from './LibraryRow'
+import { LibrarySummary } from './LibrarySummary'
import { RefreshStatusCell } from './RefreshStatusCell'
+import { SourceLibrariesCell } from './SourceLibrariesCell'
export const scene: SceneExport = {
component: BusinessKnowledgeScene,
@@ -41,6 +54,8 @@ export function BusinessKnowledgeScene(): JSX.Element {
searchTerm,
sourceTypeFilter,
addedByFilter,
+ libraryScope,
+ selectedLibrary,
} = useValues(businessKnowledgeLogic)
const { openCreateModal, deleteSource, refreshSource, setSearchTerm, setSourceTypeFilter, setAddedByFilter } =
useActions(businessKnowledgeLogic)
@@ -63,155 +78,187 @@ export function BusinessKnowledgeScene(): JSX.Element {
}
/>
<BusinessKnowledgeTabs activeTab="sources" />
+ <SceneSection title="Libraries" className="gap-y-2">
+ <LibraryRow />
+ <LibrarySummary />
+ </SceneSection>
+ <SceneDivider />
+ <SceneSection
+ title={
+ selectedLibrary
+ ? `Sources in ${selectedLibrary.name}`
+ : libraryScope === LIBRARY_SCOPE_UNFILED
+ ? 'Sources with no library'
+ : 'Sources'
+ }
+ description={`${readyCount} ready · ${pluralize(totalChunks, 'chunk')} indexed`}
+ className="gap-y-2"
+ >
+ <div className="flex flex-wrap gap-2 items-center">
+ <LemonInput
+ type="search"
+ placeholder="Search by name or URL"
+ value={searchTerm}
+ onChange={setSearchTerm}
+ className="max-w-80"
+ />
+ <LemonSelect
+ value={sourceTypeFilter}
+ onChange={setSourceTypeFilter}
+ options={[
+ { value: 'all', label: 'All types' },
+ { value: 'text', label: 'Text' },
+ { value: 'url', label: 'URL' },
+ { value: 'file', label: 'File' },
+ ]}
+ />
+ <LemonSelect
+ value={addedByFilter}
+ onChange={setAddedByFilter}
+ options={[
+ { value: 'all', label: 'All sources' },
+ { value: 'human', label: 'Human' },
+ { value: 'learned', label: 'Learned' },
+ ]}
+ data-attr="business-knowledge-added-by-filter"
+ />
+ </div>
- <div className="flex gap-4 text-sm text-muted mb-2">
- <span>{readyCount} ready</span>
- <span>•</span>
- <span>{totalChunks.toLocaleString()} chunks indexed</span>
- </div>
-
- <div className="flex gap-2 items-center mb-2">
- <LemonInput
- type="search"
- placeholder="Search by name or URL"
- value={searchTerm}
- onChange={setSearchTerm}
- className="max-w-80"
- />
- <LemonSelect
- value={sourceTypeFilter}
- onChange={setSourceTypeFilter}
- options={[
- { value: 'all', label: 'All types' },
- { value: 'text', label: 'Text' },
- { value: 'url', label: 'URL' },
- { value: 'file', label: 'File' },
- ]}
- />
- <LemonSelect
- value={addedByFilter}
- onChange={setAddedByFilter}
- options={[
- { value: 'all', label: 'All sources' },
- { value: 'human', label: 'Human' },
- { value: 'learned', label: 'Learned' },
- ]}
- data-attr="business-knowledge-added-by-filter"
- />
- </div>
-
- <LemonTable<KnowledgeSource>
- dataSource={sources}
- loading={sourcesLoading}
- pagination={{ pageSize: 20 }}
- rowKey={(row) => row.id}
- onRow={(row) => {
- const sourceUrl = urls.businessKnowledgeSource(row.id)
- return {
- style: { cursor: 'pointer' },
- onClick: (e: React.MouseEvent) => {
- if (e.metaKey || e.ctrlKey) {
- e.preventDefault()
- e.stopPropagation()
- newInternalTab(sourceUrl)
- } else {
- push(sourceUrl)
- }
+ <LemonTable<KnowledgeSource>
+ dataSource={sources}
+ loading={sourcesLoading}
+ pagination={{ pageSize: 20 }}
+ rowKey={(row) => row.id}
+ onRow={(row) => {
+ const sourceUrl = urls.businessKnowledgeSource(row.id)
+ return {
+ style: { cursor: 'pointer' },
+ onClick: (e: React.MouseEvent) => {
+ if (e.metaKey || e.ctrlKey) {
+ e.preventDefault()
+ e.stopPropagation()
+ newInternalTab(sourceUrl)
+ } else {
+ push(sourceUrl)
+ }
+ },
+ onAuxClick: (e: React.MouseEvent) => {
+ if (e.button === 1) {
+ e.preventDefault()
+ e.stopPropagation()
+ newInternalTab(sourceUrl)
+ }
+ },
+ }
+ }}
+ columns={[
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, row) => <KnowledgeSourceNameCell source={row} />,
},
- onAuxClick: (e: React.MouseEvent) => {
- if (e.button === 1) {
- e.preventDefault()
- e.stopPropagation()
- newInternalTab(sourceUrl)
- }
+ {
+ title: 'Type',
+ key: 'source_type',
+ render: (_, row) => <LemonTag>{row.source_type}</LemonTag>,
},
- }
- }}
- columns={[
- {
- title: 'Name',
- key: 'name',
- render: (_, row) => <KnowledgeSourceNameCell source={row} />,
- },
- {
- title: 'Type',
- key: 'source_type',
- render: (_, row) => <LemonTag>{row.source_type}</LemonTag>,
- },
- {
- title: 'Status',
- key: 'status',
- render: (_, row) => <StatusTag source={row} />,
- },
- {
- title: 'Pages / chunks',
- key: 'chunk_count',
- render: (_, row) => {
- const pages = row.document_count
- return row.source_type === 'url' && row.crawl_mode && row.crawl_mode !== 'single'
- ? `${pages.toLocaleString()} / ${row.chunk_count.toLocaleString()}`
- : row.chunk_count.toLocaleString()
+ {
+ title: 'Libraries',
+ key: 'library_ids',
+ render: (_, row) => <SourceLibrariesCell source={row} />,
+ },
+ {
+ title: 'Status',
+ key: 'status',
+ render: (_, row) => <StatusTag source={row} />,
},
- },
- {
- title: 'Added',
- key: 'created_at',
- render: (_, row) => <TZLabel time={row.created_at} />,
- },
- {
- title: 'Last refresh',
- key: 'last_refresh_at',
- render: (_, row) => <RefreshStatusCell source={row} />,
- },
- {
- title: '',
- key: 'actions',
- width: 0,
- render: (_, row) => (
- <div className="flex gap-1 justify-end">
- {row.source_type === 'url' && !row.is_generated && (
+ {
+ title: 'Pages / chunks',
+ key: 'chunk_count',
+ render: (_, row) => {
+ const pages = row.document_count
+ return row.source_type === 'url' && row.crawl_mode && row.crawl_mode !== 'single'
+ ? `${pages.toLocaleString()} / ${row.chunk_count.toLocaleString()}`
+ : row.chunk_count.toLocaleString()
+ },
+ },
+ {
+ title: 'Added',
+ key: 'created_at',
+ render: (_, row) => <TZLabel time={row.created_at} />,
+ },
+ {
+ title: 'Last refresh',
+ key: 'last_refresh_at',
+ render: (_, row) => <RefreshStatusCell source={row} />,
+ },
+ {
+ title: '',
+ key: 'actions',
+ width: 0,
+ render: (_, row) => (
+ <div className="flex gap-1 justify-end">
+ {row.source_type === 'url' && !row.is_generated && (
+ <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={<IconTrash />}
+ status="danger"
size="small"
- tooltip="Re-fetch and re-index this URL"
- loading={refreshingIds.includes(row.id)}
+ tooltip="Delete"
onClick={(e) => {
e.stopPropagation()
- refreshSource(row.id)
+ 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={
+ searchTerm || sourceTypeFilter !== 'all' || addedByFilter !== 'all' ? (
+ 'No sources match your search or filter.'
+ ) : libraryScope === LIBRARY_SCOPE_UNFILED ? (
+ 'Every source is in a library.'
+ ) : libraryScope !== LIBRARY_SCOPE_ALL ? (
+ <div className="flex flex-col items-center gap-2 py-4">
+ <span>{selectedLibrary?.name ?? 'This library'} has no sources yet.</span>
<LemonButton
- icon={<IconTrash />}
- status="danger"
+ type="primary"
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' },
- })
- }}
- />
+ icon={<IconPlusSmall />}
+ onClick={() => openCreateModal()}
+ >
+ Add source
+ </LemonButton>
</div>
- ),
- },
- ]}
- emptyState={
- searchTerm || sourceTypeFilter !== 'all' || addedByFilter !== 'all'
- ? 'No sources match your search or filter.'
- : "No knowledge sources yet. Click 'Add source' to index your first."
- }
- />
+ ) : (
+ "No knowledge sources yet. Click 'Add source' to index your first."
+ )
+ }
+ />
+ </SceneSection>
<CreateKnowledgeSourceModal refreshIntervalOptions={REFRESH_INTERVAL_OPTIONS} />
+ <LibraryDialog />
</SceneContent>
)
}
diff --git a/products/business_knowledge/frontend/scenes/sources/KnowledgeSourceNameCell.stories.tsx b/products/business_knowledge/frontend/scenes/sources/KnowledgeSourceNameCell.stories.tsx
index ed1d6bb9235b..76e4a4b35e75 100644
--- a/products/business_knowledge/frontend/scenes/sources/KnowledgeSourceNameCell.stories.tsx
+++ b/products/business_knowledge/frontend/scenes/sources/KnowledgeSourceNameCell.stories.tsx
@@ -42,6 +42,7 @@ function makeSource(overrides: Partial<KnowledgeSource> = {}): KnowledgeSource {
file_content_type: '',
file_size_bytes: null,
always_include: false,
+ library_ids: [],
...overrides,
}
}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibraryButton.tsx b/products/business_knowledge/frontend/scenes/sources/LibraryButton.tsx
new file mode 100644
index 000000000000..9a9a1e035c92
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibraryButton.tsx
@@ -0,0 +1,27 @@
+import { IconFolder, IconFolderOpen } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import type { KnowledgeLibrary } from '../../api'
+
+export function LibraryButton({
+ library,
+ active,
+ onClick,
+}: {
+ library: KnowledgeLibrary
+ active: boolean
+ onClick: () => void
+}): JSX.Element {
+ return (
+ <LemonButton
+ size="small"
+ icon={active ? <IconFolderOpen /> : <IconFolder />}
+ active={active}
+ onClick={onClick}
+ data-attr="business-knowledge-library-select"
+ >
+ <span className="max-w-40 truncate">{library.name}</span>
+ <span className="ml-1.5 text-xs text-secondary">{library.source_count}</span>
+ </LemonButton>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibraryDialog.tsx b/products/business_knowledge/frontend/scenes/sources/LibraryDialog.tsx
new file mode 100644
index 000000000000..5766f0426c75
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibraryDialog.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonModal } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { businessKnowledgeLogic } from './businessKnowledgeLogic'
+import { LibraryNameForm } from './LibraryNameForm'
+import { LibraryRepoForm } from './LibraryRepoForm'
+
+export function LibraryDialog(): JSX.Element | null {
+ const githubEnabled = useFeatureFlag('BUSINESS_KNOWLEDGE_GITHUB_REPOS')
+ const { libraryDialog, libraryScope, libraries, savingLibrary } = useValues(businessKnowledgeLogic)
+ const { closeLibraryDialog, createLibrary, renameLibrary, saveLibraryRepos } = useActions(businessKnowledgeLogic)
+ const active = libraries.find((library) => library.id === libraryScope)
+
+ if (!libraryDialog) {
+ return null
+ }
+ if (libraryDialog !== 'create' && !active) {
+ return null
+ }
+
+ return (
+ <LemonModal
+ isOpen
+ onClose={closeLibraryDialog}
+ // Closing resets the saving state without cancelling the request, so a reopened dialog could submit twice.
+ closable={!savingLibrary}
+ title={
+ libraryDialog === 'create'
+ ? 'New library'
+ : libraryDialog === 'rename'
+ ? 'Rename library'
+ : `Repositories in ${active?.name ?? 'this library'}`
+ }
+ description={
+ libraryDialog === 'create'
+ ? 'A library groups sources and repositories. Add sources to it from a source page or when you add a new source.'
+ : libraryDialog === 'repos'
+ ? 'Searching this library reads only these repositories. Choose from the repositories selected in settings.'
+ : undefined
+ }
+ width={480}
+ footer={null}
+ >
+ {libraryDialog === 'repos' && githubEnabled && active ? (
+ <LibraryRepoForm
+ initialRepos={active.repos}
+ saving={savingLibrary}
+ onCancel={closeLibraryDialog}
+ onSave={saveLibraryRepos}
+ />
+ ) : (
+ <LibraryNameForm
+ initialName={libraryDialog === 'rename' && active ? active.name : ''}
+ saving={savingLibrary}
+ submitLabel={libraryDialog === 'create' ? 'Create library' : 'Save'}
+ onCancel={closeLibraryDialog}
+ onSubmit={(name) => (libraryDialog === 'create' ? createLibrary(name) : renameLibrary(name))}
+ />
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibraryNameForm.tsx b/products/business_knowledge/frontend/scenes/sources/LibraryNameForm.tsx
new file mode 100644
index 000000000000..26f22b1cb1da
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibraryNameForm.tsx
@@ -0,0 +1,46 @@
+import { useState } from 'react'
+
+import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+
+export function LibraryNameForm({
+ initialName,
+ saving,
+ submitLabel,
+ onCancel,
+ onSubmit,
+}: {
+ initialName: string
+ saving: boolean
+ submitLabel: string
+ onCancel: () => void
+ onSubmit: (name: string) => void
+}): JSX.Element {
+ const [name, setName] = useState(initialName)
+ return (
+ <form
+ className="flex flex-col gap-3"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (!name.trim() || saving) {
+ return
+ }
+ onSubmit(name.trim())
+ }}
+ >
+ <LemonInput value={name} onChange={setName} placeholder="Library name" autoFocus />
+ <div className="flex justify-end gap-2">
+ <LemonButton type="secondary" onClick={onCancel} disabledReason={saving ? 'Saving' : undefined}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={saving}
+ disabledReason={!name.trim() ? 'Enter a name' : undefined}
+ >
+ {submitLabel}
+ </LemonButton>
+ </div>
+ </form>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibraryRepoForm.tsx b/products/business_knowledge/frontend/scenes/sources/LibraryRepoForm.tsx
new file mode 100644
index 000000000000..944439bcbcad
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibraryRepoForm.tsx
@@ -0,0 +1,62 @@
+import { useMountedLogic, useValues } from 'kea'
+import { useState } from 'react'
+
+import { LemonButton, LemonInputSelect } from '@posthog/lemon-ui'
+
+import { githubReposLogic } from '../settings/githubReposLogic'
+
+export function LibraryRepoForm({
+ initialRepos,
+ saving,
+ onCancel,
+ onSave,
+}: {
+ initialRepos: string[]
+ saving: boolean
+ onCancel: () => void
+ onSave: (repos: string[]) => void
+}): JSX.Element {
+ useMountedLogic(githubReposLogic)
+ const { connection, connectionLoading } = useValues(githubReposLogic)
+ const [repos, setRepos] = useState(initialRepos)
+ const options = (connection?.repos ?? []).map((repo) => ({ key: repo, label: repo }))
+ return (
+ <form
+ className="flex flex-col gap-3"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (saving) {
+ return
+ }
+ onSave(repos)
+ }}
+ >
+ {connectionLoading && !connection ? (
+ <p className="m-0 text-muted">Loading repositories…</p>
+ ) : options.length === 0 ? (
+ <p className="m-0">Select repositories in business knowledge settings before adding them here.</p>
+ ) : (
+ <LemonInputSelect
+ mode="multiple"
+ value={repos}
+ options={options}
+ onChange={setRepos}
+ placeholder="Choose repositories"
+ />
+ )}
+ <div className="flex justify-end gap-2">
+ <LemonButton type="secondary" onClick={onCancel} disabledReason={saving ? 'Saving' : undefined}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={saving}
+ disabledReason={options.length === 0 ? 'No repositories selected' : undefined}
+ >
+ Save
+ </LemonButton>
+ </div>
+ </form>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibraryRow.tsx b/products/business_knowledge/frontend/scenes/sources/LibraryRow.tsx
new file mode 100644
index 000000000000..5f8723d3b32e
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibraryRow.tsx
@@ -0,0 +1,80 @@
+import { useActions, useValues } from 'kea'
+
+import { IconDocument, IconFolder, IconFolderOpen, IconPlusSmall, IconStack } from '@posthog/icons'
+import { LemonButton, LemonDivider, LemonMenu } from '@posthog/lemon-ui'
+
+import { LIBRARY_SCOPE_ALL, LIBRARY_SCOPE_UNFILED, businessKnowledgeLogic } from './businessKnowledgeLogic'
+import { LibraryButton } from './LibraryButton'
+
+const VISIBLE_LIBRARIES = 8
+
+export function LibraryRow(): JSX.Element {
+ const { libraries, libraryScope, selectedLibrary } = useValues(businessKnowledgeLogic)
+ const { setLibraryScope, openLibraryDialog } = useActions(businessKnowledgeLogic)
+ const visible = libraries.slice(0, VISIBLE_LIBRARIES)
+ const overflow = libraries.slice(VISIBLE_LIBRARIES)
+ const overflowSelected = overflow.some((library) => library.id === libraryScope)
+
+ return (
+ <div className="flex flex-wrap items-center gap-1" data-attr="business-knowledge-library-row">
+ <LemonButton
+ size="small"
+ icon={<IconStack />}
+ active={libraryScope === LIBRARY_SCOPE_ALL}
+ onClick={() => setLibraryScope(LIBRARY_SCOPE_ALL)}
+ data-attr="business-knowledge-library-all"
+ >
+ All
+ </LemonButton>
+ {libraries.length > 0 && <LemonDivider vertical className="h-5 mx-1" />}
+ {visible.map((library) => (
+ <LibraryButton
+ key={library.id}
+ library={library}
+ active={libraryScope === library.id}
+ onClick={() => setLibraryScope(library.id)}
+ />
+ ))}
+ {overflow.length > 0 && (
+ <LemonMenu
+ items={overflow.map((library) => ({
+ label: `${library.name} (${library.source_count})`,
+ active: libraryScope === library.id,
+ onClick: () => setLibraryScope(library.id),
+ }))}
+ >
+ <LemonButton
+ size="small"
+ icon={overflowSelected ? <IconFolderOpen /> : <IconFolder />}
+ active={overflowSelected}
+ >
+ <span className="max-w-40 truncate">
+ {overflowSelected && selectedLibrary ? selectedLibrary.name : `${overflow.length} more`}
+ </span>
+ </LemonButton>
+ </LemonMenu>
+ )}
+ {libraries.length > 0 && (
+ <LemonButton
+ size="small"
+ icon={<IconDocument />}
+ active={libraryScope === LIBRARY_SCOPE_UNFILED}
+ onClick={() => setLibraryScope(LIBRARY_SCOPE_UNFILED)}
+ tooltip="Sources that are not in any library"
+ data-attr="business-knowledge-library-unfiled"
+ >
+ No library
+ </LemonButton>
+ )}
+ <LemonButton
+ size="small"
+ type="tertiary"
+ icon={<IconPlusSmall />}
+ onClick={() => openLibraryDialog('create')}
+ data-attr="business-knowledge-library-new"
+ >
+ New library
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibrarySummary.tsx b/products/business_knowledge/frontend/scenes/sources/LibrarySummary.tsx
new file mode 100644
index 000000000000..5d72871d6bca
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibrarySummary.tsx
@@ -0,0 +1,125 @@
+import { useActions, useValues } from 'kea'
+
+import { IconDocument, IconFolder, IconFolderOpen, IconGithub, IconPencil, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'
+
+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { pluralize } from 'lib/utils/strings'
+
+import { LIBRARY_SCOPE_ALL, LIBRARY_SCOPE_UNFILED, businessKnowledgeLogic } from './businessKnowledgeLogic'
+import { LibrarySummaryPanel } from './LibrarySummaryPanel'
+
+export function LibrarySummary(): JSX.Element | null {
+ const githubEnabled = useFeatureFlag('BUSINESS_KNOWLEDGE_GITHUB_REPOS')
+ const { libraryScope, selectedLibrary, libraries, librariesLoading, savingLibrary } =
+ useValues(businessKnowledgeLogic)
+ const { openLibraryDialog, deleteSelectedLibrary } = useActions(businessKnowledgeLogic)
+
+ if (libraryScope === LIBRARY_SCOPE_UNFILED) {
+ return (
+ <LibrarySummaryPanel icon={<IconDocument />} title="No library">
+ <p className="m-0 text-sm text-secondary">
+ Sources that are not in any library. Open a source to add it to a library.
+ </p>
+ </LibrarySummaryPanel>
+ )
+ }
+
+ if (libraryScope === LIBRARY_SCOPE_ALL) {
+ if (librariesLoading || libraries.length > 0) {
+ return null
+ }
+ return (
+ <LibrarySummaryPanel icon={<IconFolder />} title="Libraries">
+ <p className="m-0 text-sm text-secondary">
+ Group sources into libraries to keep them organized. API and MCP search can then look in one library
+ instead of every source.
+ </p>
+ </LibrarySummaryPanel>
+ )
+ }
+
+ if (!selectedLibrary) {
+ return null
+ }
+
+ const counts = [pluralize(selectedLibrary.source_count, 'source')]
+ if (githubEnabled) {
+ counts.push(pluralize(selectedLibrary.repos.length, 'repository', 'repositories'))
+ }
+
+ return (
+ <LibrarySummaryPanel
+ icon={<IconFolderOpen />}
+ title={selectedLibrary.name}
+ tag={selectedLibrary.is_default ? <LemonTag type="highlight">Default</LemonTag> : null}
+ actions={
+ <>
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPencil />}
+ onClick={() => openLibraryDialog('rename')}
+ data-attr="business-knowledge-library-rename"
+ >
+ Rename
+ </LemonButton>
+ {githubEnabled && (
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconGithub />}
+ onClick={() => openLibraryDialog('repos')}
+ data-attr="business-knowledge-library-repos"
+ >
+ Repositories
+ </LemonButton>
+ )}
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ disabledReason={savingLibrary ? 'Saving' : undefined}
+ data-attr="business-knowledge-library-delete"
+ onClick={() =>
+ LemonDialog.open({
+ title: `Delete "${selectedLibrary.name}"?`,
+ description: 'Sources and repositories stay. Only this library is removed.',
+ primaryButton: {
+ children: 'Delete library',
+ status: 'danger',
+ onClick: () => deleteSelectedLibrary(),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ >
+ Delete
+ </LemonButton>
+ </>
+ }
+ >
+ <p className="m-0 text-sm text-secondary">
+ <span translate="no">{counts.join(' · ')}</span>
+ {selectedLibrary.is_default && <span>. Sources learned from support tickets join this library.</span>}
+ </p>
+ {githubEnabled && selectedLibrary.repos.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {selectedLibrary.repos.map((repo) => (
+ <LemonTag key={repo} icon={<IconGithub />}>
+ {repo}
+ </LemonTag>
+ ))}
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-1 text-xs text-secondary">
+ <span>ID for API and MCP search:</span>
+ <CopyToClipboardInline explicitValue={selectedLibrary.id} description="library ID" selectable>
+ {selectedLibrary.id}
+ </CopyToClipboardInline>
+ </div>
+ </LibrarySummaryPanel>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/LibrarySummaryPanel.tsx b/products/business_knowledge/frontend/scenes/sources/LibrarySummaryPanel.tsx
new file mode 100644
index 000000000000..f01cdc8d2845
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/LibrarySummaryPanel.tsx
@@ -0,0 +1,29 @@
+import { LemonCard } from '@posthog/lemon-ui'
+
+export function LibrarySummaryPanel({
+ icon,
+ title,
+ tag,
+ actions,
+ children,
+}: {
+ icon: JSX.Element
+ title: string
+ tag?: JSX.Element | null
+ actions?: JSX.Element
+ children: React.ReactNode
+}): JSX.Element {
+ return (
+ <LemonCard hoverEffect={false} className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2 p-3">
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="flex shrink-0 text-lg text-secondary">{icon}</span>
+ <h3 className="m-0 truncate text-base font-semibold">{title}</h3>
+ {tag}
+ </div>
+ {children}
+ </div>
+ {actions && <div className="flex shrink-0 flex-wrap gap-1">{actions}</div>}
+ </LemonCard>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/SourceLibrariesCell.tsx b/products/business_knowledge/frontend/scenes/sources/SourceLibrariesCell.tsx
new file mode 100644
index 000000000000..9fc9ca802f14
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sources/SourceLibrariesCell.tsx
@@ -0,0 +1,30 @@
+import { useValues } from 'kea'
+
+import { IconFolder } from '@posthog/icons'
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { businessKnowledgeLogic } from './businessKnowledgeLogic'
+import type { KnowledgeSource } from './businessKnowledgeLogic'
+
+const VISIBLE_TAGS = 2
+
+export function SourceLibrariesCell({ source }: { source: KnowledgeSource }): JSX.Element {
+ const { libraryNamesById } = useValues(businessKnowledgeLogic)
+ const names = source.library_ids.map((id) => libraryNamesById[id]).filter((name): name is string => !!name)
+
+ if (names.length === 0) {
+ return <span className="text-secondary">None</span>
+ }
+
+ const hidden = names.slice(VISIBLE_TAGS)
+ return (
+ <div className="flex flex-wrap gap-1">
+ {names.slice(0, VISIBLE_TAGS).map((name) => (
+ <LemonTag key={name} icon={<IconFolder />} className="max-w-40">
+ <span className="truncate">{name}</span>
+ </LemonTag>
+ ))}
+ {hidden.length > 0 && <LemonTag title={hidden.join(', ')}>+{hidden.length}</LemonTag>}
+ </div>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts
index fbe4b55b12d2..4fa58c7bbb77 100644
--- a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts
+++ b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts
@@ -1,3 +1,4 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
@@ -6,8 +7,17 @@ import * as api from '../../api'
import type { KnowledgeSourceApi } from '../../generated/api.schemas'
import { businessKnowledgeLogic } from './businessKnowledgeLogic'
+jest.mock('posthog-js', () => ({
+ capture: jest.fn(),
+}))
+
jest.mock('../../api', () => ({
listSources: jest.fn(),
+ listLibraries: jest.fn(),
+ createLibrary: jest.fn(),
+ updateLibrary: jest.fn(),
+ deleteLibrary: jest.fn(),
+ updateSource: jest.fn(),
createTextSource: jest.fn(),
createUrlSource: jest.fn(),
createFileSource: jest.fn(),
@@ -51,6 +61,7 @@ const MOCK_SOURCE: KnowledgeSourceApi = {
file_content_type: '',
file_size_bytes: null,
always_include: false,
+ library_ids: [],
}
const mockedApi = api as jest.Mocked<typeof api>
@@ -63,6 +74,7 @@ describe('businessKnowledgeLogic', () => {
initKeaTests()
jest.clearAllMocks()
mockedApi.listSources.mockResolvedValue([MOCK_SOURCE])
+ mockedApi.listLibraries.mockResolvedValue([])
logic = businessKnowledgeLogic()
logic.mount()
})
@@ -82,6 +94,8 @@ describe('businessKnowledgeLogic', () => {
search: '',
sourceType: 'all',
addedBy: 'learned',
+ libraryId: undefined,
+ unfiled: false,
})
await expectLogic(logic, () => {
@@ -92,9 +106,132 @@ describe('businessKnowledgeLogic', () => {
search: '',
sourceType: 'text',
addedBy: 'learned',
+ libraryId: undefined,
+ unfiled: false,
})
})
+ it('selects a library from the url and lists its sources', async () => {
+ const libraryId = '22222222-2222-2222-2222-222222222222'
+ logic.unmount()
+ mockedApi.listLibraries.mockResolvedValue([
+ { id: libraryId, name: 'Docs', is_default: false, source_count: 1, repos: [] },
+ ])
+ router.actions.push('/business-knowledge', { library: libraryId })
+ logic = businessKnowledgeLogic()
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.libraryScope).toEqual(libraryId)
+ expect(mockedApi.listSources).toHaveBeenLastCalledWith({
+ search: '',
+ sourceType: 'all',
+ addedBy: 'all',
+ libraryId,
+ unfiled: false,
+ })
+ })
+
+ it('falls back to all when the url library is unknown', async () => {
+ logic.unmount()
+ mockedApi.listLibraries.mockResolvedValue([
+ { id: '33333333-3333-3333-3333-333333333333', name: 'Docs', is_default: false, source_count: 0, repos: [] },
+ ])
+ router.actions.push('/business-knowledge', { library: '44444444-4444-4444-4444-444444444444' })
+ logic = businessKnowledgeLogic()
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.libraryScope).toEqual('all')
+ expect(mockedApi.listSources).toHaveBeenLastCalledWith({
+ search: '',
+ sourceType: 'all',
+ addedBy: 'all',
+ libraryId: undefined,
+ unfiled: false,
+ })
+ })
+
+ it('returns to all after the selected library is deleted', async () => {
+ const libraryId = '22222222-2222-2222-2222-222222222222'
+ mockedApi.listLibraries.mockResolvedValue([
+ { id: libraryId, name: 'Docs', is_default: false, source_count: 1, repos: [] },
+ ])
+ mockedApi.deleteLibrary.mockResolvedValue(undefined)
+ await expectLogic(logic, () => {
+ logic.actions.setLibraryScope(libraryId)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteSelectedLibrary()
+ }).toFinishAllListeners()
+
+ expect(logic.values.libraryScope).toEqual('all')
+ })
+
+ it('selects a new library while other libraries exist', async () => {
+ const existing = {
+ id: '22222222-2222-2222-2222-222222222222',
+ name: 'Docs',
+ is_default: false,
+ source_count: 1,
+ repos: [],
+ }
+ const created = {
+ id: '33333333-3333-3333-3333-333333333333',
+ name: 'Support',
+ is_default: false,
+ source_count: 0,
+ repos: [],
+ }
+ mockedApi.listLibraries.mockResolvedValue([existing])
+ await expectLogic(logic, () => {
+ logic.actions.loadLibraries()
+ }).toFinishAllListeners()
+ mockedApi.createLibrary.mockResolvedValue(created)
+ mockedApi.listLibraries.mockResolvedValue([existing, created])
+
+ await expectLogic(logic, () => {
+ logic.actions.createLibrary('Support')
+ }).toFinishAllListeners()
+
+ expect(logic.values.libraryScope).toEqual(created.id)
+ })
+
+ it('files a new source into the selected library when the modal closes mid-request', async () => {
+ const libraryId = '22222222-2222-2222-2222-222222222222'
+ mockedApi.listLibraries.mockResolvedValue([
+ { id: libraryId, name: 'Docs', is_default: false, source_count: 0, repos: [] },
+ ])
+ let resolveCreate: (source: KnowledgeSourceApi) => void = () => undefined
+ mockedApi.createTextSource.mockReturnValue(
+ new Promise((resolve) => {
+ resolveCreate = resolve
+ })
+ )
+ mockedApi.updateSource.mockResolvedValue({ ...MOCK_SOURCE, library_ids: [libraryId] })
+ await expectLogic(logic, () => {
+ logic.actions.setLibraryScope(libraryId)
+ logic.actions.openCreateModal()
+ }).toFinishAllListeners()
+ expect(logic.values.createLibraryIds).toEqual([libraryId])
+
+ logic.actions.setTextSourceValue('name', 'Policy')
+ logic.actions.setTextSourceValue('text', 'Refunds are available within 30 days.')
+ await expectLogic(logic, () => {
+ logic.actions.submitTextSource()
+ }).toDispatchActions(['submitTextSourceRequest'])
+ expect(mockedApi.createTextSource).toHaveBeenCalled()
+ logic.actions.closeCreateModal()
+ expect(logic.values.createLibraryIds).toEqual([])
+ resolveCreate(MOCK_SOURCE)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedApi.updateSource).toHaveBeenCalledWith(MOCK_SOURCE.id, { library_ids: [libraryId] })
+ })
+
it('keeps the persisted filters apart per team', () => {
logic.actions.setAddedByFilter('human')
logic.unmount()
diff --git a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts
index 2105e5635ca7..955f8c6e6c99 100644
--- a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts
+++ b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts
@@ -2,7 +2,7 @@ import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, sel
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
-import { router } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
@@ -11,14 +11,19 @@ import { urls } from 'scenes/urls'
import {
createFileSource,
+ createLibrary,
createTextSource,
createUrlSource,
+ deleteLibrary,
deleteSource,
+ listLibraries,
listSources,
refreshSource,
+ updateLibrary,
+ updateSource,
} from '../../api'
-import type { CreateUrlSourcePayload, RefreshIntervalOption } from '../../api'
-import type { KnowledgeSourceApi } from '../../generated/api.schemas'
+import type { CreateUrlSourcePayload, KnowledgeLibrary, RefreshIntervalOption } from '../../api'
+import type { KnowledgeLibraryApi, KnowledgeSourceApi } from '../../generated/api.schemas'
import {
DEFAULT_URL_SOURCE_FORM,
type CrawlMode,
@@ -33,6 +38,34 @@ import {
export type { KnowledgeSource, CrawlMode, TextSourceFormValues, UrlSourceFormValues }
export type SourceTypeFilter = 'all' | 'text' | 'url' | 'file'
export type AddedByFilter = 'all' | 'human' | 'learned'
+export type LibraryDialog = 'create' | 'rename' | 'repos'
+export const LIBRARY_SCOPE_ALL = 'all'
+export const LIBRARY_SCOPE_UNFILED = 'unfiled'
+
+function isLibraryScope(scope: string): boolean {
+ return scope !== LIBRARY_SCOPE_ALL && scope !== LIBRARY_SCOPE_UNFILED
+}
+
+async function fileCreatedSource(sourceId: string, libraryIds: string[]): Promise<void> {
+ if (libraryIds.length === 0) {
+ return
+ }
+ // The source already exists here. Throwing would keep the create modal open and invite a duplicate submit.
+ try {
+ await updateSource(sourceId, { library_ids: libraryIds })
+ posthog.capture('business knowledge source libraries changed', { library_count: libraryIds.length })
+ } catch {
+ lemonToast.warning('Source added, but it could not be added to its libraries. Add them from the source page.')
+ }
+}
+
+function scopeIsKnown(scope: string, libraries: KnowledgeLibrary[]): boolean {
+ return (
+ scope === LIBRARY_SCOPE_ALL ||
+ scope === LIBRARY_SCOPE_UNFILED ||
+ libraries.some((library) => library.id === scope)
+ )
+}
export interface FileSourceFormValues {
name: string
@@ -53,6 +86,7 @@ export const REFRESH_INTERVAL_OPTIONS: RefreshIntervalOption[] = [
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface businessKnowledgeLogicValues {
addedByFilter: AddedByFilter
+ createLibraryIds: string[]
createTab: CreateTab
fileSource: FileSourceFormValues
fileSourceAllErrors: Record<string, any>
@@ -70,9 +104,16 @@ export interface businessKnowledgeLogicValues {
isTextSourceValid: boolean
isUrlSourceSubmitting: boolean
isUrlSourceValid: boolean
+ libraries: KnowledgeLibrary[]
+ librariesLoading: boolean
+ libraryDialog: LibraryDialog | null
+ libraryNamesById: Record<string, string>
+ libraryScope: string
readyCount: number
refreshingIds: string[]
+ savingLibrary: boolean
searchTerm: string
+ selectedLibrary: KnowledgeLibrary | null
showFileSourceErrors: boolean
showTextSourceErrors: boolean
showUrlSourceErrors: boolean
@@ -105,9 +146,36 @@ export interface businessKnowledgeLogicActions {
closeCreateModal: () => {
value: true
}
+ closeLibraryDialog: () => {
+ value: true
+ }
+ createLibrary: (name: string) => {
+ name: string
+ }
+ deleteSelectedLibrary: () => {
+ value: true
+ }
deleteSource: (id: string) => {
id: string
}
+ finishLibrarySave: () => {
+ value: true
+ }
+ loadLibraries: (_: void) => void
+ loadLibrariesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadLibrariesSuccess: (
+ libraries: KnowledgeLibraryApi[],
+ payload?: void
+ ) => {
+ libraries: KnowledgeLibraryApi[]
+ payload?: void
+ }
loadSources: (_: void) => void
loadSourcesFailure: (
error: string,
@@ -126,6 +194,9 @@ export interface businessKnowledgeLogicActions {
openCreateModal: () => {
value: true
}
+ openLibraryDialog: (libraryDialog: LibraryDialog) => {
+ libraryDialog: LibraryDialog
+ }
refreshSource: (id: string) => {
id: string
}
@@ -153,6 +224,9 @@ export interface businessKnowledgeLogicActions {
id: string
}
}
+ renameLibrary: (name: string) => {
+ name: string
+ }
replaceSourceInList: ({ source }: { source: KnowledgeSource }) => {
source: KnowledgeSource
}
@@ -183,9 +257,15 @@ export interface businessKnowledgeLogicActions {
resetUrlSource: (values?: UrlSourceFormValues) => {
values?: UrlSourceFormValues
}
+ saveLibraryRepos: (repos: string[]) => {
+ repos: string[]
+ }
setAddedByFilter: (addedByFilter: AddedByFilter) => {
addedByFilter: AddedByFilter
}
+ setCreateLibraryIds: (libraryIds: string[]) => {
+ libraryIds: string[]
+ }
setCreateTab: (tab: CreateTab) => {
tab: CreateTab
}
@@ -202,6 +282,9 @@ export interface businessKnowledgeLogicActions {
setFileSourceValues: (values: DeepPartial<FileSourceFormValues>) => {
values: DeepPartial<FileSourceFormValues>
}
+ setLibraryScope: (libraryScope: string) => {
+ libraryScope: string
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -298,6 +381,8 @@ export interface businessKnowledgeLogicMeta {
__keaTypeGenInternalSelectorTypes: {
readyCount: (sources: KnowledgeSourceApi[]) => number
totalChunks: (sources: KnowledgeSourceApi[]) => number
+ selectedLibrary: (libraries: KnowledgeLibraryApi[], libraryScope: string) => KnowledgeLibrary | null
+ libraryNamesById: (libraries: KnowledgeLibraryApi[]) => Record<string, string>
}
}
@@ -317,6 +402,15 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setSourceTypeFilter: (sourceTypeFilter: SourceTypeFilter) => ({ sourceTypeFilter }),
setAddedByFilter: (addedByFilter: AddedByFilter) => ({ addedByFilter }),
+ setLibraryScope: (libraryScope: string) => ({ libraryScope }),
+ setCreateLibraryIds: (libraryIds: string[]) => ({ libraryIds }),
+ openLibraryDialog: (libraryDialog: LibraryDialog) => ({ libraryDialog }),
+ closeLibraryDialog: true,
+ createLibrary: (name: string) => ({ name }),
+ renameLibrary: (name: string) => ({ name }),
+ deleteSelectedLibrary: true,
+ saveLibraryRepos: (repos: string[]) => ({ repos }),
+ finishLibrarySave: true,
deleteSource: (id: string) => ({ id }),
refreshSource: (id: string) => ({ id }),
refreshSourceDone: (id: string) => ({ id }),
@@ -337,6 +431,13 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
closeCreateModal: () => 'text',
},
],
+ createLibraryIds: [
+ [] as string[],
+ {
+ setCreateLibraryIds: (_, { libraryIds }) => libraryIds,
+ closeCreateModal: () => [],
+ },
+ ],
refreshingIds: [
[] as string[],
{
@@ -365,16 +466,43 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
setAddedByFilter: (_, { addedByFilter }) => addedByFilter,
},
],
+ libraryScope: [
+ LIBRARY_SCOPE_ALL as string,
+ {
+ setLibraryScope: (_, { libraryScope }) => libraryScope,
+ },
+ ],
+ libraryDialog: [
+ null as LibraryDialog | null,
+ {
+ openLibraryDialog: (_, { libraryDialog }) => libraryDialog,
+ closeLibraryDialog: () => null,
+ },
+ ],
+ savingLibrary: [
+ false,
+ {
+ createLibrary: () => true,
+ renameLibrary: () => true,
+ deleteSelectedLibrary: () => true,
+ saveLibraryRepos: () => true,
+ closeLibraryDialog: () => false,
+ finishLibrarySave: () => false,
+ },
+ ],
})),
- loaders(({ values }) => ({
+ loaders(({ values, actions }) => ({
sources: [
[] as KnowledgeSource[],
{
loadSources: async (_: void, breakpoint) => {
+ const scope = values.libraryScope
const sources = await listSources({
search: values.searchTerm,
sourceType: values.sourceTypeFilter,
addedBy: values.addedByFilter,
+ libraryId: isLibraryScope(scope) ? scope : undefined,
+ unfiled: scope === LIBRARY_SCOPE_UNFILED,
})
// Drop a response a newer request has already superseded, so a
// slow-then-fast search/filter can't land out of order.
@@ -386,14 +514,30 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
values.sources.map((s) => (s.id === source.id ? source : s)),
},
],
+ libraries: [
+ [] as KnowledgeLibrary[],
+ {
+ loadLibraries: async (_: void, breakpoint) => {
+ const libraries = await listLibraries()
+ breakpoint()
+ if (!scopeIsKnown(values.libraryScope, libraries)) {
+ actions.setLibraryScope(LIBRARY_SCOPE_ALL)
+ }
+ return libraries
+ },
+ },
+ ],
})),
- forms(({ actions }) => ({
+ forms(({ actions, values }) => ({
textSource: {
defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,
errors: validateText,
submit: async ({ name, text, always_include }: TextSourceFormValues) => {
+ // Closing the modal mid-request clears the selection, so read it before the request.
+ const libraryIds = values.createLibraryIds
try {
const created = await createTextSource(name, text, always_include)
+ await fileCreatedSource(created.id, libraryIds)
lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
actions.closeCreateModal()
actions.resetTextSource()
@@ -429,8 +573,10 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
max_depth: formValues.max_depth,
}),
}
+ const libraryIds = values.createLibraryIds
try {
const created = await createUrlSource(payload)
+ await fileCreatedSource(created.id, libraryIds)
// Ingestion runs in the background; the source starts PROCESSING
// and the detail page polls until it flips to ready.
lemonToast.success(`"${created.name}" added — fetching and indexing in the background`)
@@ -467,8 +613,10 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
formData.append('file', file)
formData.append('source_type', 'file')
formData.append('always_include', String(always_include))
+ const libraryIds = values.createLibraryIds
try {
const created = await createFileSource(formData)
+ await fileCreatedSource(created.id, libraryIds)
lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
actions.closeCreateModal()
actions.resetFileSource()
@@ -485,15 +633,21 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
},
},
})),
- listeners(({ actions, cache }) => ({
+ listeners(({ actions, cache, values }) => ({
+ openCreateModal: () => {
+ actions.setCreateLibraryIds(isLibraryScope(values.libraryScope) ? [values.libraryScope] : [])
+ },
submitTextSourceSuccess: () => {
posthog.capture('business knowledge source created', { source_type: 'text' })
+ actions.loadLibraries()
},
submitUrlSourceSuccess: () => {
posthog.capture('business knowledge source created', { source_type: 'url' })
+ actions.loadLibraries()
},
submitFileSourceSuccess: () => {
posthog.capture('business knowledge source created', { source_type: 'file' })
+ actions.loadLibraries()
},
setSearchTerm: async (_, breakpoint) => {
await breakpoint(300)
@@ -505,6 +659,84 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
setAddedByFilter: () => {
actions.loadSources()
},
+ setLibraryScope: ({ libraryScope }) => {
+ if (values.libraries.length > 0 && !scopeIsKnown(libraryScope, values.libraries)) {
+ actions.setLibraryScope(LIBRARY_SCOPE_ALL)
+ return
+ }
+ const library = values.libraries.find((item) => item.id === libraryScope)
+ posthog.capture('business knowledge library selected', {
+ is_default: library?.is_default ?? false,
+ unfiled: libraryScope === LIBRARY_SCOPE_UNFILED,
+ })
+ actions.loadSources()
+ },
+ createLibrary: async ({ name }) => {
+ try {
+ const library = await createLibrary(name)
+ posthog.capture('business knowledge library created')
+ actions.closeLibraryDialog()
+ // The scope check rejects ids missing from the list, and the refresh lands after it.
+ actions.loadLibrariesSuccess([...values.libraries, library])
+ actions.setLibraryScope(library.id)
+ actions.loadLibraries()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || error?.data?.name?.[0] || 'Could not create the library.')
+ } finally {
+ actions.finishLibrarySave()
+ }
+ },
+ renameLibrary: async ({ name }) => {
+ const libraryId = values.libraryScope
+ if (!isLibraryScope(libraryId)) {
+ actions.finishLibrarySave()
+ return
+ }
+ try {
+ await updateLibrary(libraryId, { name })
+ posthog.capture('business knowledge library renamed')
+ actions.closeLibraryDialog()
+ actions.loadLibraries()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || error?.data?.name?.[0] || 'Could not rename the library.')
+ } finally {
+ actions.finishLibrarySave()
+ }
+ },
+ deleteSelectedLibrary: async () => {
+ const libraryId = values.libraryScope
+ if (!isLibraryScope(libraryId)) {
+ actions.finishLibrarySave()
+ return
+ }
+ try {
+ await deleteLibrary(libraryId)
+ posthog.capture('business knowledge library deleted')
+ actions.setLibraryScope(LIBRARY_SCOPE_ALL)
+ actions.loadLibraries()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not delete the library.')
+ } finally {
+ actions.finishLibrarySave()
+ }
+ },
+ saveLibraryRepos: async ({ repos }) => {
+ const libraryId = values.libraryScope
+ if (!isLibraryScope(libraryId)) {
+ actions.finishLibrarySave()
+ return
+ }
+ try {
+ await updateLibrary(libraryId, { repos })
+ posthog.capture('business knowledge library repos changed')
+ actions.closeLibraryDialog()
+ actions.loadLibraries()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || error?.data?.repos?.[0] || 'Could not save repositories.')
+ } finally {
+ actions.finishLibrarySave()
+ }
+ },
loadSourcesSuccess: ({ sources }) => {
// URL ingestion runs in the background — poll while anything is still
// processing so the row flips to ready (or error) without a manual reload.
@@ -525,6 +757,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
try {
await deleteSource(id)
actions.removeSourceFromList({ id })
+ actions.loadLibraries()
lemonToast.success('Knowledge source deleted')
} catch (error: any) {
lemonToast.error(error?.detail || 'Could not delete the source.')
@@ -557,8 +790,39 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
(s) => [s.sources],
(sources: KnowledgeSource[]) => sources.reduce((sum, s) => sum + (s.chunk_count || 0), 0),
],
+ selectedLibrary: [
+ (s) => [s.libraries, s.libraryScope],
+ (libraries: KnowledgeLibrary[], libraryScope: string): KnowledgeLibrary | null =>
+ libraries.find((library) => library.id === libraryScope) ?? null,
+ ],
+ libraryNamesById: [
+ (s) => [s.libraries],
+ (libraries: KnowledgeLibrary[]): Record<string, string> =>
+ Object.fromEntries(libraries.map((library) => [library.id, library.name])),
+ ],
}),
afterMount(({ actions }) => {
+ actions.loadLibraries()
actions.loadSources()
}),
+ actionToUrl(({ values }) => ({
+ setLibraryScope: () => {
+ const searchParams = { ...router.values.searchParams }
+ if (values.libraryScope === LIBRARY_SCOPE_ALL) {
+ delete searchParams.library
+ } else {
+ searchParams.library = values.libraryScope
+ }
+ return [urls.businessKnowledge(), searchParams, router.values.hashParams]
+ },
+ })),
+ urlToAction(({ actions, values }) => ({
+ [urls.businessKnowledge()]: (_, searchParams) => {
+ const raw = searchParams.library
+ const next = typeof raw === 'string' && raw.length > 0 ? raw : LIBRARY_SCOPE_ALL
+ if (next !== values.libraryScope) {
+ actions.setLibraryScope(next)
+ }
+ },
+ })),
])
diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yaml
index e5f67901bc4d..7f96d1651361 100644
--- a/products/business_knowledge/mcp/tools.yaml
+++ b/products/business_knowledge/mcp/tools.yaml
@@ -35,7 +35,81 @@ tools:
Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with
document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use
for any question about the team's own product, policies, domain knowledge, or internal docs. Set rerank=true
- for a listwise LLM rerank pass when top-result precision matters.
+ for a listwise LLM rerank pass when top-result precision matters. Pass library_id to search one library, and
+ pass that same id to repository search and file read. Omit library_id to search every ready source.
+ feature_flag: product-business-knowledge
+ business-knowledge-libraries-create:
+ operation: business_knowledge_libraries_create
+ enabled: true
+ scopes:
+ - business_knowledge:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create a business knowledge library
+ description: >
+ Create a library. It does not copy sources. Add sources with business-knowledge-sources-partial-update
+ library_ids, then pass the library id to document search, repository search, and file read.
+ feature_flag: product-business-knowledge
+ business-knowledge-libraries-destroy:
+ operation: business_knowledge_libraries_destroy
+ enabled: true
+ scopes:
+ - business_knowledge:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete a business knowledge library
+ description: >
+ Delete a library and its links. Sources, documents, chunks, and selected repositories stay. Search without a
+ library id still sees them.
+ feature_flag: product-business-knowledge
+ business-knowledge-libraries-list:
+ operation: business_knowledge_libraries_list
+ enabled: true
+ scopes:
+ - business_knowledge:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List business knowledge libraries
+ description: >
+ List libraries in this project. A library limits document search, repository search, and file read to its
+ members. Pass the same library id to all three. The default library is first. Omit a library id on those
+ tools to search everything.
+ feature_flag: product-business-knowledge
+ business-knowledge-libraries-partial-update:
+ operation: business_knowledge_libraries_partial_update
+ enabled: true
+ scopes:
+ - business_knowledge:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update a business knowledge library
+ description: >
+ Rename a library, replace its sources, or replace this environment's repositories in it. Send only the
+ fields to change. source_ids replaces every source. repos replaces repositories this environment allows and
+ leaves repositories that only another environment allows.
+ feature_flag: product-business-knowledge
+ business-knowledge-libraries-retrieve:
+ operation: business_knowledge_libraries_retrieve
+ enabled: true
+ scopes:
+ - business_knowledge:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a business knowledge library
+ description: >
+ Get one library by id, including how many sources it has and which selected repositories it includes for
+ this environment.
feature_flag: product-business-knowledge
business-knowledge-repositories-file-retrieve:
operation: business_knowledge_repositories_file_retrieve
@@ -50,7 +124,8 @@ tools:
description: >
Read one file from a GitHub repository selected for business knowledge. The path must come from
business-knowledge-repositories-search. Returns the file text and a permalink. Does not search file
- contents.
+ contents. Pass library_id to read a repository in that library, using the same id as document search and
+ repository search. Omit library_id to read any selected repository.
feature_flag: business-knowledge-github-repos
business-knowledge-repositories-search:
operation: business_knowledge_repositories_search
@@ -67,7 +142,8 @@ tools:
business knowledge document search returns nothing. Pass file names or identifiers, not a full sentence.
Each repository in the response includes its GitHub description. When a description says the repository
holds a handbook or docs, search that repository for those words and read the file. Does not search inside
- file contents and does not call GitHub code search.
+ file contents and does not call GitHub code search. Pass library_id to search repositories in that library,
+ using the same id as document search and file read. Omit library_id to search every selected repository.
feature_flag: business-knowledge-github-repos
business-knowledge-sources-list:
operation: business_knowledge_sources_list
@@ -101,6 +177,7 @@ tools:
- next_refresh_at
- created_at
- updated_at
+ - library_ids
business-knowledge-sources-partial-update:
operation: business_knowledge_sources_partial_update
enabled: true
@@ -115,7 +192,9 @@ tools:
Update an existing business knowledge source by ID. Change its name, replace the text content (text sources
only — triggers a re-chunk), or toggle `always_include`. Set `always_include: true` to inject this source's
content into every support reply as general guidance (tone, policies, company direction); set false to make
- it retrieval-only again. Only the fields you pass are changed.
+ it retrieval-only again. Pass library_ids to replace the libraries this source belongs to. An empty list
+ removes it from every library. Omit library_ids to leave membership unchanged. Only the fields you pass are
+ changed.
feature_flag: product-business-knowledge
business-knowledge-sources-retrieve:
operation: business_knowledge_sources_retrieve
diff --git a/products/conversations/backend/temporal/ai_reply/activities/retrieve.py b/products/conversations/backend/temporal/ai_reply/activities/retrieve.py
index 930797f74dd9..fdb059d26a3b 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/retrieve.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/retrieve.py
@@ -90,6 +90,7 @@ def _retrieve_sync(input: RetrieveInput) -> RetrieveOutput:
"surface": "support",
"query_count": len(input.queries),
"result_count": len(chunk_ids),
+ "library_scoped": False,
},
groups=groups(team=team),
)
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index d2966dfd8bfc..aae97f8ad0d9 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1468,6 +1468,8 @@ export type ActivityLogListParams = {
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
+ * * `KnowledgeSource` - KnowledgeSource
+ * * `KnowledgeLibrary` - KnowledgeLibrary
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
@@ -1576,6 +1578,8 @@ export const ActivityLogListScope = {
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
+ KnowledgeSource: 'KnowledgeSource',
+ KnowledgeLibrary: 'KnowledgeLibrary',
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
@@ -1671,6 +1675,8 @@ export const ActivityLogListScope = {
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
+ * * `KnowledgeSource` - KnowledgeSource
+ * * `KnowledgeLibrary` - KnowledgeLibrary
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
@@ -1767,6 +1773,8 @@ export const ActivityLogListScopesItem = {
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
+ KnowledgeSource: 'KnowledgeSource',
+ KnowledgeLibrary: 'KnowledgeLibrary',
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 16faa09a81c0..d0ee584579cf 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1771,7 +1771,7 @@
"feature_flag": "product-business-knowledge"
},
"business-knowledge-documents-search": {
- "description": "Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use for any question about the team's own product, policies, domain knowledge, or internal docs. Set rerank=true for a listwise LLM rerank pass when top-result precision matters.",
+ "description": "Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use for any question about the team's own product, policies, domain knowledge, or internal docs. Set rerank=true for a listwise LLM rerank pass when top-result precision matters. Pass library_id to search one library, and pass that same id to repository search and file read. Omit library_id to search every ready source.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Search business knowledge",
@@ -1785,8 +1785,83 @@
},
"feature_flag": "product-business-knowledge"
},
+ "business-knowledge-libraries-create": {
+ "description": "Create a library. It does not copy sources. Add sources with business-knowledge-sources-partial-update library_ids, then pass the library id to document search, repository search, and file read.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Create a business knowledge library",
+ "title": "Create a business knowledge library",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-destroy": {
+ "description": "Delete a library and its links. Sources, documents, chunks, and selected repositories stay. Search without a library id still sees them.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Delete a business knowledge library",
+ "title": "Delete a business knowledge library",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-list": {
+ "description": "List libraries in this project. A library limits document search, repository search, and file read to its members. Pass the same library id to all three. The default library is first. Omit a library id on those tools to search everything.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "List business knowledge libraries",
+ "title": "List business knowledge libraries",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-partial-update": {
+ "description": "Rename a library, replace its sources, or replace this environment's repositories in it. Send only the fields to change. source_ids replaces every source. repos replaces repositories this environment allows and leaves repositories that only another environment allows.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Update a business knowledge library",
+ "title": "Update a business knowledge library",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-retrieve": {
+ "description": "Get one library by id, including how many sources it has and which selected repositories it includes for this environment.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Get a business knowledge library",
+ "title": "Get a business knowledge library",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "product-business-knowledge"
+ },
"business-knowledge-repositories-file-retrieve": {
- "description": "Read one file from a GitHub repository selected for business knowledge. The path must come from business-knowledge-repositories-search. Returns the file text and a permalink. Does not search file contents.",
+ "description": "Read one file from a GitHub repository selected for business knowledge. The path must come from business-knowledge-repositories-search. Returns the file text and a permalink. Does not search file contents. Pass library_id to read a repository in that library, using the same id as document search and repository search. Omit library_id to read any selected repository.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Read a file from a selected repository",
@@ -1801,7 +1876,7 @@
"feature_flag": "business-knowledge-github-repos"
},
"business-knowledge-repositories-search": {
- "description": "Search file paths and README text in the GitHub repositories selected for business knowledge. Call this when business knowledge document search returns nothing. Pass file names or identifiers, not a full sentence. Each repository in the response includes its GitHub description. When a description says the repository holds a handbook or docs, search that repository for those words and read the file. Does not search inside file contents and does not call GitHub code search.",
+ "description": "Search file paths and README text in the GitHub repositories selected for business knowledge. Call this when business knowledge document search returns nothing. Pass file names or identifiers, not a full sentence. Each repository in the response includes its GitHub description. When a description says the repository holds a handbook or docs, search that repository for those words and read the file. Does not search inside file contents and does not call GitHub code search. Pass library_id to search repositories in that library, using the same id as document search and file read. Omit library_id to search every selected repository.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Search selected repositories",
@@ -1831,7 +1906,7 @@
"feature_flag": "product-business-knowledge"
},
"business-knowledge-sources-partial-update": {
- "description": "Update an existing business knowledge source by ID. Change its name, replace the text content (text sources only — triggers a re-chunk), or toggle `always_include`. Set `always_include: true` to inject this source's content into every support reply as general guidance (tone, policies, company direction); set false to make it retrieval-only again. Only the fields you pass are changed.",
+ "description": "Update an existing business knowledge source by ID. Change its name, replace the text content (text sources only — triggers a re-chunk), or toggle `always_include`. Set `always_include: true` to inject this source's content into every support reply as general guidance (tone, policies, company direction); set false to make it retrieval-only again. Pass library_ids to replace the libraries this source belongs to. An empty list removes it from every library. Omit library_ids to leave membership unchanged. Only the fields you pass are changed.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Update business knowledge source",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d920b12fe438..97b694cdd65a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1786,7 +1786,7 @@
"feature_flag": "product-business-knowledge"
},
"business-knowledge-documents-search": {
- "description": "Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use for any question about the team's own product, policies, domain knowledge, or internal docs. Set rerank=true for a listwise LLM rerank pass when top-result precision matters.",
+ "description": "Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use for any question about the team's own product, policies, domain knowledge, or internal docs. Set rerank=true for a listwise LLM rerank pass when top-result precision matters. Pass library_id to search one library, and pass that same id to repository search and file read. Omit library_id to search every ready source.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Search business knowledge",
@@ -1800,8 +1800,83 @@
},
"feature_flag": "product-business-knowledge"
},
+ "business-knowledge-libraries-create": {
+ "description": "Create a library. It does not copy sources. Add sources with business-knowledge-sources-partial-update library_ids, then pass the library id to document search, repository search, and file read.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Create a business knowledge library",
+ "title": "Create a business knowledge library",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-destroy": {
+ "description": "Delete a library and its links. Sources, documents, chunks, and selected repositories stay. Search without a library id still sees them.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Delete a business knowledge library",
+ "title": "Delete a business knowledge library",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-list": {
+ "description": "List libraries in this project. A library limits document search, repository search, and file read to its members. Pass the same library id to all three. The default library is first. Omit a library id on those tools to search everything.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "List business knowledge libraries",
+ "title": "List business knowledge libraries",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-partial-update": {
+ "description": "Rename a library, replace its sources, or replace this environment's repositories in it. Send only the fields to change. source_ids replaces every source. repos replaces repositories this environment allows and leaves repositories that only another environment allows.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Update a business knowledge library",
+ "title": "Update a business knowledge library",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
+ "business-knowledge-libraries-retrieve": {
+ "description": "Get one library by id, including how many sources it has and which selected repositories it includes for this environment.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Get a business knowledge library",
+ "title": "Get a business knowledge library",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "product-business-knowledge"
+ },
"business-knowledge-repositories-file-retrieve": {
- "description": "Read one file from a GitHub repository selected for business knowledge. The path must come from business-knowledge-repositories-search. Returns the file text and a permalink. Does not search file contents.",
+ "description": "Read one file from a GitHub repository selected for business knowledge. The path must come from business-knowledge-repositories-search. Returns the file text and a permalink. Does not search file contents. Pass library_id to read a repository in that library, using the same id as document search and repository search. Omit library_id to read any selected repository.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Read a file from a selected repository",
@@ -1816,7 +1891,7 @@
"feature_flag": "business-knowledge-github-repos"
},
"business-knowledge-repositories-search": {
- "description": "Search file paths and README text in the GitHub repositories selected for business knowledge. Call this when business knowledge document search returns nothing. Pass file names or identifiers, not a full sentence. Each repository in the response includes its GitHub description. When a description says the repository holds a handbook or docs, search that repository for those words and read the file. Does not search inside file contents and does not call GitHub code search.",
+ "description": "Search file paths and README text in the GitHub repositories selected for business knowledge. Call this when business knowledge document search returns nothing. Pass file names or identifiers, not a full sentence. Each repository in the response includes its GitHub description. When a description says the repository holds a handbook or docs, search that repository for those words and read the file. Does not search inside file contents and does not call GitHub code search. Pass library_id to search repositories in that library, using the same id as document search and file read. Omit library_id to search every selected repository.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Search selected repositories",
@@ -1846,7 +1921,7 @@
"feature_flag": "product-business-knowledge"
},
"business-knowledge-sources-partial-update": {
- "description": "Update an existing business knowledge source by ID. Change its name, replace the text content (text sources only — triggers a re-chunk), or toggle `always_include`. Set `always_include: true` to inject this source's content into every support reply as general guidance (tone, policies, company direction); set false to make it retrieval-only again. Only the fields you pass are changed.",
+ "description": "Update an existing business knowledge source by ID. Change its name, replace the text content (text sources only — triggers a re-chunk), or toggle `always_include`. Set `always_include: true` to inject this source's content into every support reply as general guidance (tone, policies, company direction); set false to make it retrieval-only again. Pass library_ids to replace the libraries this source belongs to. An empty list removes it from every library. Omit library_ids to leave membership unchanged. Only the fields you pass are changed.",
"category": "Business knowledge",
"feature": "business_knowledge",
"summary": "Update business knowledge source",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fe2f92086069..1d3c1ae6414b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -61127,6 +61127,27 @@ export namespace Schemas {
readonly created_at: string;
}
+ export interface KnowledgeLibrary {
+ /** Library id. */
+ id: string;
+ /** Library name. Unique in this project, ignoring case. */
+ name: string;
+ /** True for the library new learned sources join. There is at most one. */
+ is_default: boolean;
+ /** How many sources are in this library. */
+ source_count: number;
+ /** Selected repositories in this library that this environment is allowed to read. */
+ repos: string[];
+ }
+
+ export interface KnowledgeLibraryCreate {
+ /**
+ * Name for the new library.
+ * @maxLength 255
+ */
+ name: string;
+ }
+
/**
* One ranked chunk from a business knowledge search.
*
@@ -61268,6 +61289,8 @@ export namespace Schemas {
/** @nullable */
readonly file_size_bytes: number | null;
readonly always_include: boolean;
+ /** Libraries this source belongs to. Empty when the source is in none. */
+ readonly library_ids: readonly string[];
}
/**
@@ -82161,6 +82184,18 @@ export namespace Schemas {
js_snippet_version?: string | null;
}
+ export interface PatchedKnowledgeLibraryUpdate {
+ /**
+ * New name. Omit to keep the current name.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Replaces every source in this library. Omit to leave sources unchanged. An empty list removes them all. */
+ source_ids?: string[];
+ /** Replaces this environment's repositories in the library. Omit to leave them unchanged. Repositories only another environment allows stay. */
+ repos?: string[];
+ }
+
/**
* JSON object with model parameters or any agent configuration to store with this version. If omitted, the current version's config is carried forward; pass null to clear it. Can be combined with either prompt or edits. Don't store secrets here: config is returned to anyone who can read the prompt.
* @nullable
@@ -86986,6 +87021,8 @@ export namespace Schemas {
text?: string;
/** When true, this source's content is injected into every support reply prompt as general context. */
always_include?: boolean;
+ /** Replaces the libraries this source belongs to. Omit to leave membership unchanged. An empty list removes it from every library. */
+ library_ids?: string[];
}
/**
@@ -119311,6 +119348,8 @@ export namespace Schemas {
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
+ * * `KnowledgeSource` - KnowledgeSource
+ * * `KnowledgeLibrary` - KnowledgeLibrary
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
@@ -119420,6 +119459,8 @@ export namespace Schemas {
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
+ KnowledgeSource: 'KnowledgeSource',
+ KnowledgeLibrary: 'KnowledgeLibrary',
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
@@ -119515,6 +119556,8 @@ export namespace Schemas {
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
+ * * `KnowledgeSource` - KnowledgeSource
+ * * `KnowledgeLibrary` - KnowledgeLibrary
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
@@ -119612,6 +119655,8 @@ export namespace Schemas {
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
+ KnowledgeSource: 'KnowledgeSource',
+ KnowledgeLibrary: 'KnowledgeLibrary',
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
@@ -120439,6 +120484,10 @@ export namespace Schemas {
};
export type BusinessKnowledgeDocumentsSearchListParams = {
+ /**
+ * Limit retrieval to sources in this library. Pass the same id to repository search and file read. Omit to search every ready source.
+ */
+ library_id?: string;
/**
* Maximum number of ranked chunks to return. Defaults to 10, capped at 20.
*/
@@ -120469,6 +120518,10 @@ export namespace Schemas {
};
export type BusinessKnowledgeRepositoriesFileRetrieveParams = {
+ /**
+ * Require the repository to be in this library. Pass the same id used for document search and repository search. Omit to read any selected repository.
+ */
+ library_id?: string;
/**
* File path returned by the repository search.
* @minLength 1
@@ -120482,6 +120535,10 @@ export namespace Schemas {
};
export type BusinessKnowledgeRepositoriesSearchParams = {
+ /**
+ * Limit the search to repositories in this library. Pass the same id to document search and file read. Omit to search every selected repository.
+ */
+ library_id?: string;
/**
* File names, path fragments, or identifiers to match. Not a full sentence.
* @minLength 1
@@ -120498,6 +120555,10 @@ export namespace Schemas {
* Filter by who added the source: human (you added it) or learned (from a resolved support ticket).
*/
added_by?: BusinessKnowledgeSourcesListAddedBy;
+ /**
+ * Return only sources in this library. Do not combine with unfiled.
+ */
+ library_id?: string;
/**
* Number of results to return per page.
*/
@@ -120514,6 +120575,10 @@ export namespace Schemas {
* Filter to a single source type (text, url, or file).
*/
source_type?: BusinessKnowledgeSourcesListSourceType;
+ /**
+ * When true, return only sources that are in no library. Do not combine with library_id.
+ */
+ unfiled?: boolean;
};
export type BusinessKnowledgeSourcesListAddedBy = typeof BusinessKnowledgeSourcesListAddedBy[keyof typeof BusinessKnowledgeSourcesListAddedBy];
diff --git a/services/mcp/src/generated/business_knowledge/api.ts b/services/mcp/src/generated/business_knowledge/api.ts
index 4fde406f5ba7..c686cb572fd1 100644
--- a/services/mcp/src/generated/business_knowledge/api.ts
+++ b/services/mcp/src/generated/business_knowledge/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 13 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -44,6 +44,12 @@ export const BusinessKnowledgeDocumentsSearchListParams = () => zod.object({
})
export const BusinessKnowledgeDocumentsSearchListQueryParams = () => zod.object({
+ library_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Limit retrieval to sources in this library. Pass the same id to repository search and file read. Omit to search every ready source.'
+ ),
limit: zod.number().optional().describe('Maximum number of ranked chunks to return. Defaults to 10, capped at 20.'),
query: zod
.string()
@@ -58,6 +64,95 @@ export const BusinessKnowledgeDocumentsSearchListQueryParams = () => zod.object(
),
})
+/**
+ * Libraries in this project. The default library is first.
+ * @summary List business knowledge libraries
+ */
+export const BusinessKnowledgeLibrariesListParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+/**
+ * @summary Create a business knowledge library
+ */
+export const BusinessKnowledgeLibrariesCreateParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const businessKnowledgeLibrariesCreateBodyNameMax = 255
+
+export const BusinessKnowledgeLibrariesCreateBody = () => zod.object({
+ name: zod.string().max(businessKnowledgeLibrariesCreateBodyNameMax).describe('Name for the new library.'),
+})
+
+/**
+ * @summary Get a business knowledge library
+ */
+export const BusinessKnowledgeLibrariesRetrieveParams = () => zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+/**
+ * Send only the fields you want to change. `source_ids` replaces every source in the library. `repos` replaces this environment's repositories and leaves repositories that only another environment allows.
+ * @summary Rename a library or replace its sources and repositories
+ */
+export const BusinessKnowledgeLibrariesPartialUpdateParams = () => zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const businessKnowledgeLibrariesPartialUpdateBodyNameMax = 255
+
+export const BusinessKnowledgeLibrariesPartialUpdateBody = () => zod.object({
+ name: zod
+ .string()
+ .max(businessKnowledgeLibrariesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('New name. Omit to keep the current name.'),
+ source_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Replaces every source in this library. Omit to leave sources unchanged. An empty list removes them all.'
+ ),
+ repos: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "Replaces this environment's repositories in the library. Omit to leave them unchanged. Repositories only another environment allows stay."
+ ),
+})
+
+/**
+ * Removes the library and its links. Sources, documents, and selected repositories stay.
+ * @summary Delete a business knowledge library
+ */
+export const BusinessKnowledgeLibrariesDestroyParams = () => zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
/**
* Reads one file whose path is in the cached file list, at the cached commit. The path must come from the repository search.
* @summary Read a file from a selected GitHub repository
@@ -71,6 +166,12 @@ export const BusinessKnowledgeRepositoriesFileRetrieveParams = () => zod.object(
})
export const BusinessKnowledgeRepositoriesFileRetrieveQueryParams = () => zod.object({
+ library_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Require the repository to be in this library. Pass the same id used for document search and repository search. Omit to read any selected repository.'
+ ),
path: zod.string().min(1).describe('File path returned by the repository search.'),
repo: zod.string().min(1).describe('owner\/repo to read. It must already be selected.'),
})
@@ -88,6 +189,12 @@ export const BusinessKnowledgeRepositoriesSearchParams = () => zod.object({
})
export const BusinessKnowledgeRepositoriesSearchQueryParams = () => zod.object({
+ library_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Limit the search to repositories in this library. Pass the same id to document search and file read. Omit to search every selected repository.'
+ ),
query: zod.string().min(1).describe('File names, path fragments, or identifiers to match. Not a full sentence.'),
repo: zod
.string()
@@ -110,6 +217,7 @@ export const BusinessKnowledgeSourcesListQueryParams = () => zod.object({
.enum(['human', 'learned'])
.optional()
.describe('Filter by who added the source: human (you added it) or learned (from a resolved support ticket).'),
+ library_id: zod.string().optional().describe('Return only sources in this library. Do not combine with unfiled.'),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
search: zod.string().optional().describe('Case-insensitive substring match against the source name and URL.'),
@@ -117,6 +225,10 @@ export const BusinessKnowledgeSourcesListQueryParams = () => zod.object({
.enum(['file', 'text', 'url'])
.optional()
.describe('Filter to a single source type (text, url, or file).'),
+ unfiled: zod
+ .boolean()
+ .optional()
+ .describe('When true, return only sources that are in no library. Do not combine with library_id.'),
})
export const BusinessKnowledgeSourcesCreateParams = () => zod.object({
@@ -183,6 +295,12 @@ export const BusinessKnowledgeSourcesPartialUpdateBody = () => zod
.describe(
"When true, this source's content is injected into every support reply prompt as general context."
),
+ library_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Replaces the libraries this source belongs to. Omit to leave membership unchanged. An empty list removes it from every library.'
+ ),
})
.describe(
'PATCH payload for text sources. All fields optional, at least one\nrequired. `text` triggers a re-chunk; `name` or `always_include` alone does not.'
diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.ts
index 025746a2e380..237e8315a11c 100644
--- a/services/mcp/src/tools/generated/business_knowledge.ts
+++ b/services/mcp/src/tools/generated/business_knowledge.ts
@@ -57,6 +57,7 @@ const businessKnowledgeDocumentsSearch = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/documents/search/`,
query: {
+ library_id: params.library_id,
limit: params.limit,
query: params.query,
rerank: params.rerank,
@@ -66,6 +67,130 @@ const businessKnowledgeDocumentsSearch = (): ToolBase<
},
})
+const BusinessKnowledgeLibrariesCreateSchema = () => {
+ const BusinessKnowledgeLibrariesCreateBody = orvalSchemas.BusinessKnowledgeLibrariesCreateBody()
+ return BusinessKnowledgeLibrariesCreateBody
+}
+
+const businessKnowledgeLibrariesCreate = (): ToolBase<
+ ReturnType<typeof BusinessKnowledgeLibrariesCreateSchema>,
+ Schemas.KnowledgeLibrary
+> => ({
+ name: 'business-knowledge-libraries-create',
+ schema: BusinessKnowledgeLibrariesCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof BusinessKnowledgeLibrariesCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ const result = await context.api.request<Schemas.KnowledgeLibrary>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/libraries/`,
+ body,
+ })
+ return result
+ },
+})
+
+const BusinessKnowledgeLibrariesDestroySchema = () => {
+ const BusinessKnowledgeLibrariesDestroyParams = orvalSchemas.BusinessKnowledgeLibrariesDestroyParams()
+ return BusinessKnowledgeLibrariesDestroyParams.omit({ project_id: true })
+}
+
+const businessKnowledgeLibrariesDestroy = (): ToolBase<
+ ReturnType<typeof BusinessKnowledgeLibrariesDestroySchema>,
+ unknown
+> => ({
+ name: 'business-knowledge-libraries-destroy',
+ schema: BusinessKnowledgeLibrariesDestroySchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof BusinessKnowledgeLibrariesDestroySchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/libraries/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const BusinessKnowledgeLibrariesListSchema = () => z.object({})
+
+const businessKnowledgeLibrariesList = (): ToolBase<
+ ReturnType<typeof BusinessKnowledgeLibrariesListSchema>,
+ WithPostHogUrl<Schemas.KnowledgeLibrary[]>
+> => ({
+ name: 'business-knowledge-libraries-list',
+ schema: BusinessKnowledgeLibrariesListSchema(),
+ handler: async (context: Context, _params: z.infer<ReturnType<typeof BusinessKnowledgeLibrariesListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.KnowledgeLibrary[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/libraries/`,
+ })
+ return await withPostHogUrl(context, result, '/business-knowledge')
+ },
+})
+
+const BusinessKnowledgeLibrariesPartialUpdateSchema = () => {
+ const BusinessKnowledgeLibrariesPartialUpdateBody = orvalSchemas.BusinessKnowledgeLibrariesPartialUpdateBody()
+ const BusinessKnowledgeLibrariesPartialUpdateParams = orvalSchemas.BusinessKnowledgeLibrariesPartialUpdateParams()
+ return BusinessKnowledgeLibrariesPartialUpdateParams.omit({ project_id: true }).extend(
+ BusinessKnowledgeLibrariesPartialUpdateBody.shape
+ )
+}
+
+const businessKnowledgeLibrariesPartialUpdate = (): ToolBase<
+ ReturnType<typeof BusinessKnowledgeLibrariesPartialUpdateSchema>,
+ Schemas.KnowledgeLibrary
+> => ({
+ name: 'business-knowledge-libraries-partial-update',
+ schema: BusinessKnowledgeLibrariesPartialUpdateSchema(),
+ handler: async (
+ context: Context,
+ params: z.infer<ReturnType<typeof BusinessKnowledgeLibrariesPartialUpdateSchema>>
+ ) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.source_ids !== undefined) {
+ body['source_ids'] = params.source_ids
+ }
+ if (params.repos !== undefined) {
+ body['repos'] = params.repos
+ }
+ const result = await context.api.request<Schemas.KnowledgeLibrary>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/libraries/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+const BusinessKnowledgeLibrariesRetrieveSchema = () => {
+ const BusinessKnowledgeLibrariesRetrieveParams = orvalSchemas.BusinessKnowledgeLibrariesRetrieveParams()
+ return BusinessKnowledgeLibrariesRetrieveParams.omit({ project_id: true })
+}
+
+const businessKnowledgeLibrariesRetrieve = (): ToolBase<
+ ReturnType<typeof BusinessKnowledgeLibrariesRetrieveSchema>,
+ Schemas.KnowledgeLibrary
+> => ({
+ name: 'business-knowledge-libraries-retrieve',
+ schema: BusinessKnowledgeLibrariesRetrieveSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof BusinessKnowledgeLibrariesRetrieveSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.KnowledgeLibrary>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/libraries/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
const BusinessKnowledgeRepositoriesFileRetrieveSchema = () => {
const BusinessKnowledgeRepositoriesFileRetrieveQueryParams =
orvalSchemas.BusinessKnowledgeRepositoriesFileRetrieveQueryParams()
@@ -87,6 +212,7 @@ const businessKnowledgeRepositoriesFileRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/repositories/file/`,
query: {
+ library_id: params.library_id,
path: params.path,
repo: params.repo,
},
@@ -115,6 +241,7 @@ const businessKnowledgeRepositoriesSearch = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/repositories/search/`,
query: {
+ library_id: params.library_id,
query: params.query,
repo: params.repo,
},
@@ -141,10 +268,12 @@ const businessKnowledgeSourcesList = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/`,
query: {
added_by: params.added_by,
+ library_id: params.library_id,
limit: params.limit,
offset: params.offset,
search: params.search,
source_type: params.source_type,
+ unfiled: params.unfiled,
},
})
const filtered = {
@@ -165,6 +294,7 @@ const businessKnowledgeSourcesList = (): ToolBase<
'next_refresh_at',
'created_at',
'updated_at',
+ 'library_ids',
])
),
} as typeof result
@@ -212,6 +342,9 @@ const businessKnowledgeSourcesPartialUpdate = (): ToolBase<
if (params.always_include !== undefined) {
body['always_include'] = params.always_include
}
+ if (params.library_ids !== undefined) {
+ body['library_ids'] = params.library_ids
+ }
const result = await context.api.request<Schemas.KnowledgeSource>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/${encodeURIComponent(String(params.id))}/`,
@@ -297,6 +430,11 @@ const businessKnowledgeSourcesUrlCreate = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'business-knowledge-document-window-retrieve': businessKnowledgeDocumentWindowRetrieve,
'business-knowledge-documents-search': businessKnowledgeDocumentsSearch,
+ 'business-knowledge-libraries-create': businessKnowledgeLibrariesCreate,
+ 'business-knowledge-libraries-destroy': businessKnowledgeLibrariesDestroy,
+ 'business-knowledge-libraries-list': businessKnowledgeLibrariesList,
+ 'business-knowledge-libraries-partial-update': businessKnowledgeLibrariesPartialUpdate,
+ 'business-knowledge-libraries-retrieve': businessKnowledgeLibrariesRetrieve,
'business-knowledge-repositories-file-retrieve': businessKnowledgeRepositoriesFileRetrieve,
'business-knowledge-repositories-search': businessKnowledgeRepositoriesSearch,
'business-knowledge-sources-list': businessKnowledgeSourcesList,