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(bk): add always-on business knowledge context for support replies (#65244)

Alex V176e4db06734
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.py
index 4ae7e4fe58b3..797a44e6d3f8 100644
--- a/products/business_knowledge/backend/api/serializers.py
+++ b/products/business_knowledge/backend/api/serializers.py
@@ -131,6 +131,7 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):
"original_filename",
"file_content_type",
"file_size_bytes",
+ "always_include",
]
read_only_fields = fields
@@ -184,6 +185,11 @@ class CreateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
"or wait for URL/file support in Stage 2/3."
),
)
+ always_include = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction).",
+ )
def validate_text(self, value: str) -> str:
if not value.strip():
@@ -202,8 +208,8 @@ class CreateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
class UpdateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
"""
- PATCH payload for text sources. Both fields optional, at least one
- required. `text` triggers a re-chunk; `name` alone does not.
+ PATCH payload for text sources. All fields optional, at least one
+ required. `text` triggers a re-chunk; `name` or `always_include` alone does not.
"""
name = serializers.CharField(
@@ -216,6 +222,10 @@ class UpdateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
trim_whitespace=False,
help_text="Replacement text. Omit to keep the existing content.",
)
+ always_include = serializers.BooleanField(
+ required=False,
+ help_text="When true, this source's content is injected into every support reply prompt as general context.",
+ )
def validate_text(self, value: str) -> str:
if not value.strip():
@@ -227,8 +237,8 @@ class UpdateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):
return value
def validate(self, attrs: dict) -> dict:
- if "name" not in attrs and "text" not in attrs:
- raise serializers.ValidationError("Provide at least one of `name` or `text`.")
+ 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`.")
return attrs
@@ -258,6 +268,10 @@ class UpdateUrlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, seria
required=False,
help_text="How often to auto-refresh this source in the background. `manual` disables auto-refresh. Changing it alone does not trigger a re-crawl.",
)
+ always_include = serializers.BooleanField(
+ required=False,
+ help_text="When true, this source's content is injected into every support reply prompt as general context.",
+ )
include_globs = _GlobListField(
required=False,
help_text="URL path globs to include.",
@@ -326,6 +340,11 @@ class CreateUrlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, seria
default=RefreshInterval.MANUAL,
help_text="How often to auto-refresh this source in the background. `manual` disables auto-refresh.",
)
+ always_include = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="When true, this source's content is injected into every support reply prompt as general context.",
+ )
def to_internal_value(self, data: dict) -> dict:
attrs = super().to_internal_value(data)
@@ -360,6 +379,11 @@ class CreateCrawlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, ser
default=RefreshInterval.MANUAL,
help_text="How often to auto-refresh this source in the background. `manual` disables auto-refresh.",
)
+ always_include = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="When true, this source's content is injected into every support reply prompt as general context.",
+ )
include_globs = _GlobListField(
required=False,
default=list,
@@ -497,6 +521,11 @@ class CreateFileSourceSerializer(_NameValidationMixin, serializers.Serializer):
f"PDF, DOCX, Markdown (.md), CSV, or plain text (.txt) file. Max {MAX_FILE_SIZE_BYTES // (1024 * 1024)} MB."
),
)
+ always_include = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="When true, this source's content is injected into every support reply prompt as general context.",
+ )
def validate_file(self, value: UploadedFile) -> UploadedFile: # noqa: F821
if value.size and value.size > MAX_FILE_SIZE_BYTES:
diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.py
index c590b0191e47..925b22064430 100644
--- a/products/business_knowledge/backend/api/views.py
+++ b/products/business_knowledge/backend/api/views.py
@@ -99,6 +99,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
created_by_id=user.id,
name=serializer.validated_data["name"],
text=serializer.validated_data["text"],
+ always_include=serializer.validated_data.get("always_include", False),
)
except logic.TextTooLargeError:
raise exceptions.ValidationError({"text": "Text exceeds the maximum allowed size."})
@@ -117,6 +118,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
name=serializer.validated_data["name"],
url=serializer.validated_data["url"],
refresh_interval=serializer.validated_data.get("refresh_interval"),
+ always_include=serializer.validated_data.get("always_include", False),
)
except logic.SourceBusyError:
raise _ConflictError("Another source is already being processed. Please wait and try again.")
@@ -139,6 +141,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
crawl_mode=serializer.validated_data["crawl_mode"],
crawl_config=serializer.validated_data["crawl_config"],
refresh_interval=serializer.validated_data.get("refresh_interval"),
+ always_include=serializer.validated_data.get("always_include", False),
)
except logic.SourceBusyError:
raise _ConflictError("Another source is already being processed. Please wait and try again.")
@@ -193,6 +196,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
name=serializer.validated_data["name"],
file_data=file_data,
original_filename=uploaded.name or "unnamed",
+ always_include=serializer.validated_data.get("always_include", False),
)
except FileParseError as exc:
raise exceptions.ValidationError({"file": str(exc) or "Unable to parse the uploaded file."})
@@ -246,6 +250,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
team_id=self.team_id,
name=serializer.validated_data.get("name"),
text=None,
+ always_include=serializer.validated_data.get("always_include"),
)
except logic.QuotaExceededError:
raise exceptions.PermissionDenied(detail="Knowledge source quota exceeded for this project.")
@@ -262,6 +267,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
team_id=self.team_id,
name=serializer.validated_data.get("name"),
text=serializer.validated_data.get("text"),
+ always_include=serializer.validated_data.get("always_include"),
)
except logic.TextTooLargeError:
raise exceptions.ValidationError({"text": "Text exceeds the maximum allowed size."})
@@ -283,6 +289,7 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
crawl_mode=serializer.validated_data.get("crawl_mode"),
crawl_config=serializer.validated_data.get("crawl_config"),
refresh_interval=serializer.validated_data.get("refresh_interval"),
+ always_include=serializer.validated_data.get("always_include"),
)
except logic.InvalidUrlError:
raise exceptions.ValidationError({"url": "URL is not reachable."})
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index 8009601a4b12..22393e1e7893 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -181,6 +181,11 @@ BK_RERANK_SNIPPET_CHARS = 500
# embedding service is slow, FTS alone fires (graceful degradation).
BK_QUERY_EMBEDDING_TIMEOUT = 5.0
+# --- Always-on context cap ---
+# Hard char cap for always-on sources injected into every support prompt.
+# These bypass query filtering, so unbounded injection blows the token budget.
+MAX_ALWAYS_ON_CONTEXT_CHARS = 20_000
+
# --- Drill-down (agentic read) tunables ---
# Default chunk radius for get_document_window: returns center +/- radius
# chunks (up to 2*radius+1 = 11 chunks ~= 13k chars at typical size).
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index ab4ebb2f305f..1cbdae1cee20 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -60,6 +60,7 @@ from .constants import (
DEFAULT_MAX_PAGES,
EMBEDDING_STABLE_TS_MAX_AGE,
EMBEDDING_TTL_REFRESH_WINDOW,
+ MAX_ALWAYS_ON_CONTEXT_CHARS,
MAX_CHUNKS_PER_TEAM,
MAX_SOURCES_PER_TEAM,
MAX_TEXT_SIZE_BYTES,
@@ -396,6 +397,7 @@ def create_text_source(
created_by_id: int | None,
name: str,
text: str,
+ always_include: bool = False,
) -> KnowledgeSource:
"""
Create source + 1 document + N chunks synchronously.
@@ -413,6 +415,7 @@ def create_text_source(
name=name,
source_type=SourceType.TEXT,
status=SourceStatus.PROCESSING,
+ always_include=always_include,
)
# One text source == one document. Stable_id is the document's own UUID,
@@ -460,6 +463,7 @@ def update_text_source(
team_id: int,
name: str | None,
text: str | None,
+ always_include: bool | None = None,
) -> KnowledgeSource | None:
"""
Edit path.
@@ -479,6 +483,9 @@ def update_text_source(
except KnowledgeSource.DoesNotExist:
return None
+ if always_include is not None:
+ source.always_include = always_include
+
if text is not None:
if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:
raise TextTooLargeError(f"Text exceeds {MAX_TEXT_SIZE_BYTES} bytes.")
@@ -494,6 +501,8 @@ def update_text_source(
if name is not None:
source.name = name
update_fields.append("name")
+ if always_include is not None:
+ update_fields.append("always_include")
source.save(update_fields=update_fields)
KnowledgeChunk.objects.filter(team_id=team_id, source_id=source_id).delete()
@@ -518,9 +527,14 @@ def update_text_source(
_bulk_create_chunks(source=source, document=document, team_id=team_id, chunks=chunks)
source.status = SourceStatus.READY
source.save(update_fields=["status", "updated_at"])
- elif name is not None:
- source.name = name
- source.save(update_fields=["name", "updated_at"])
+ elif name is not None or always_include is not None:
+ update_fields = ["updated_at"]
+ if name is not None:
+ source.name = name
+ update_fields.append("name")
+ if always_include is not None:
+ update_fields.append("always_include")
+ source.save(update_fields=update_fields)
return get_for_team(source.id, team_id) or source
@@ -535,6 +549,7 @@ def update_url_source(
crawl_mode: str | None = None,
crawl_config: dict | None = None,
refresh_interval: str | None = None,
+ always_include: bool | None = None,
) -> KnowledgeSource | None:
"""
Update a URL source's metadata and optionally re-crawl.
@@ -563,6 +578,10 @@ def update_url_source(
source.refresh_interval = refresh_interval
update_fields.append("refresh_interval")
+ if always_include is not None and always_include != source.always_include:
+ source.always_include = always_include
+ update_fields.append("always_include")
+
if url is not None and url != source.source_url:
normalized = _validate_url(url)
old_values["source_url"] = source.source_url
@@ -623,6 +642,7 @@ def create_file_source(
name: str,
file_data: bytes,
original_filename: str,
+ always_include: bool = False,
) -> KnowledgeSource:
"""
Detect type → parse → chunk. Inline, not Temporal.
@@ -658,6 +678,7 @@ def create_file_source(
original_filename=file_parse.sanitize_filename(original_filename),
file_content_type=parsed.content_type,
file_size_bytes=len(file_data),
+ always_include=always_include,
)
if _count_chunks(team_id) + len(chunks) > MAX_CHUNKS_PER_TEAM:
@@ -835,6 +856,7 @@ def claim_url_source(
crawl_mode: str | None = None,
crawl_config: dict | None = None,
refresh_interval: str | None = None,
+ always_include: bool = False,
) -> KnowledgeSource:
"""
Create the PROCESSING claim row for a URL/crawl source *without* fetching.
@@ -859,6 +881,7 @@ def claim_url_source(
crawl_mode=crawl_mode or CrawlMode.SINGLE,
crawl_config=crawl_config or {},
refresh_interval=refresh_interval or RefreshInterval.MANUAL,
+ always_include=always_include,
)
return source
@@ -1546,6 +1569,57 @@ def has_ready_sources(team_id: int) -> bool:
return KnowledgeSource.objects.filter(team_id=team_id, status=SourceStatus.READY).exists()
+@with_team_scope(canonical=True)
+def get_always_on_context(team_id: int) -> "list[KnowledgeSearchResult]":
+ """Return all SAFE/READY chunks from always_include sources, hard-capped by chars.
+
+ Same safety gate as search — fails closed for UNKNOWN/unsafe/tombstoned/non-READY.
+ Output is truncated to MAX_ALWAYS_ON_CONTEXT_CHARS worth of chunk content so
+ always-on injection can't blow the prompt budget.
+ """
+ chunks = (
+ _safe_chunks_qs(team_id)
+ .filter(source__always_include=True)
+ .select_related("source", "document")
+ .only(
+ "id",
+ "source_id",
+ "document_id",
+ "heading_path",
+ "ordinal",
+ "content",
+ "source__name",
+ "source__source_type",
+ "document__title",
+ )
+ .order_by("source_id", "document_id", "ordinal")
+ )
+
+ results: list[KnowledgeSearchResult] = []
+ total_chars = 0
+ for c in chunks:
+ # Account for the "\n\n" separator the caller joins chunks with, so the
+ # assembled text honors the cap precisely (no mid-sentence slice downstream).
+ separator = 2 if results else 0
+ if total_chars + separator + len(c.content) > MAX_ALWAYS_ON_CONTEXT_CHARS:
+ break
+ total_chars += separator + len(c.content)
+ results.append(
+ KnowledgeSearchResult(
+ chunk_id=c.id,
+ source_id=c.source_id,
+ source_name=c.source.name,
+ source_type=c.source.source_type,
+ document_id=c.document_id,
+ document_title=c.document.title,
+ heading_path=c.heading_path,
+ ordinal=c.ordinal,
+ content=c.content,
+ )
+ )
+ return results
+
+
def has_feature_flag(team: Team) -> bool:
"""The `product-business-knowledge` flag check, org-keyed. Canonical home for the
check — `ee/hogai/utils/feature_flags.py` delegates here."""
diff --git a/products/business_knowledge/backend/migrations/0012_knowledgesource_always_include.py b/products/business_knowledge/backend/migrations/0012_knowledgesource_always_include.py
new file mode 100644
index 000000000000..c561b0d29b5e
--- /dev/null
+++ b/products/business_knowledge/backend/migrations/0012_knowledgesource_always_include.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("business_knowledge", "0011_bk_doc_embed_state_index"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="knowledgesource",
+ name="always_include",
+ field=models.BooleanField(default=False),
+ ),
+ ]
diff --git a/products/business_knowledge/backend/migrations/0013_bk_source_always_include_index.py b/products/business_knowledge/backend/migrations/0013_bk_source_always_include_index.py
new file mode 100644
index 000000000000..973eff5564ca
--- /dev/null
+++ b/products/business_knowledge/backend/migrations/0013_bk_source_always_include_index.py
@@ -0,0 +1,34 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("business_knowledge", "0012_knowledgesource_always_include"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="knowledgesource",
+ index=models.Index(
+ fields=["team"],
+ condition=models.Q(always_include=True),
+ name="bk_source_always_include",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="bk_source_always_include",
+ table_name="posthog_business_knowledge_knowledgesource",
+ columns="(team_id)",
+ where="WHERE always_include = true",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txt
index e2ae8f15757b..66a568d272c0 100644
--- a/products/business_knowledge/backend/migrations/max_migration.txt
+++ b/products/business_knowledge/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_bk_doc_embed_state_index
+0013_bk_source_always_include_index
diff --git a/products/business_knowledge/backend/models/knowledge_source.py b/products/business_knowledge/backend/models/knowledge_source.py
index 1be4c5955a50..848cbd4a3de7 100644
--- a/products/business_knowledge/backend/models/knowledge_source.py
+++ b/products/business_knowledge/backend/models/knowledge_source.py
@@ -54,6 +54,12 @@ class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields,
# re-reads with safe defaults.
crawl_config = models.JSONField(default=dict, blank=True)
+ # --- Always-on context ---
+ # When True, all SAFE/READY chunks from this source are injected into every
+ # support reply prompt (tone, policies, company direction) without requiring
+ # a query match. Same safety gate as search — fails closed until classified.
+ always_include = models.BooleanField(default=False)
+
# --- Stage 3: file-source metadata (all nullable — additive) ---
# Sanitized original filename from the upload. Never used as a path.
original_filename = models.CharField(max_length=255, blank=True, default="")
@@ -73,6 +79,8 @@ class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields,
models.Index(fields=["team", "source_type"], name="bk_source_team_type"),
# Cross-team due-source scan by the background refresh coordinator.
models.Index(fields=["refresh_interval", "last_refresh_at"], name="bk_source_refresh_due"),
+ # Fast lookup for always-on context injection (only flagged sources).
+ models.Index(fields=["team"], condition=models.Q(always_include=True), name="bk_source_always_include"),
]
def __str__(self) -> str:
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index 582d56ddf065..c28bfca85b43 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -115,6 +115,30 @@ class TestKnowledgeSourceAPI(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED
assert response.json()["source_type"] == "text"
+ def test_create_text_source_with_always_include(self, _ff) -> None:
+ response = self.client.post(
+ self.url,
+ {"name": "Tone guide", "text": "Be friendly.", "always_include": True},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ assert response.json()["always_include"] is True
+
+ def test_patch_always_include_without_text(self, _ff) -> None:
+ create_resp = self.client.post(
+ self.url,
+ {"name": "Policy", "text": "Be nice."},
+ format="json",
+ )
+ source_id = create_resp.json()["id"]
+ patch_resp = self.client.patch(
+ f"{self.url}{source_id}/",
+ {"always_include": True},
+ format="json",
+ )
+ assert patch_resp.status_code == status.HTTP_200_OK, patch_resp.content
+ assert patch_resp.json()["always_include"] is True
+
@patch("posthoganalytics.feature_enabled", return_value=True)
class TestEmbeddingStatusAPI(APIBaseTest):
diff --git a/products/business_knowledge/backend/tests/test_logic.py b/products/business_knowledge/backend/tests/test_logic.py
index f986d0c6a3ab..30834bc8ef4c 100644
--- a/products/business_knowledge/backend/tests/test_logic.py
+++ b/products/business_knowledge/backend/tests/test_logic.py
@@ -5,15 +5,22 @@ from unittest.mock import patch
from parameterized import parameterized
-from products.business_knowledge.backend.constants import CHUNK_HARD_MAX_CHARS
+from products.business_knowledge.backend.constants import CHUNK_HARD_MAX_CHARS, MAX_ALWAYS_ON_CONTEXT_CHARS
from products.business_knowledge.backend.logic import (
QuotaExceededError,
TextTooLargeError,
_chunk_id,
chunk_text,
create_text_source,
+ get_always_on_context,
+)
+from products.business_knowledge.backend.models import (
+ KnowledgeChunk,
+ KnowledgeDocument,
+ KnowledgeSource,
+ SafetyVerdict,
+ SourceStatus,
)
-from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, SourceStatus
class TestChunker(BaseTest):
@@ -132,3 +139,87 @@ class TestCreateTextSource(BaseTest):
assert len(logic.list_for_team(self.team.id)) == 1
assert len(logic.list_for_team(other_team.id)) == 0
+
+
+class TestGetAlwaysOnContext(BaseTest):
+ def _create_source(
+ self, *, always_include: bool = False, status: str = SourceStatus.READY, safe: bool = True
+ ) -> KnowledgeSource:
+ source = KnowledgeSource.objects.unscoped().create(
+ team_id=self.team.id,
+ name="test",
+ source_type="text",
+ status=status,
+ always_include=always_include,
+ )
+ doc = KnowledgeDocument.objects.unscoped().create(
+ team_id=self.team.id,
+ source=source,
+ stable_id=str(uuid.uuid4()),
+ title="doc",
+ content="chunk content here",
+ content_hash="abc",
+ safety_verdict=SafetyVerdict.SAFE if safe else SafetyVerdict.UNKNOWN,
+ )
+ KnowledgeChunk.objects.unscoped().create(
+ id=uuid.uuid4(),
+ team_id=self.team.id,
+ source=source,
+ document=doc,
+ ordinal=0,
+ content="chunk content here",
+ char_count=18,
+ )
+ return source
+
+ def test_returns_chunks_from_always_include_sources(self) -> None:
+ self._create_source(always_include=True)
+ self._create_source(always_include=False)
+ results = get_always_on_context(self.team.id)
+ assert len(results) == 1
+ assert results[0].content == "chunk content here"
+
+ def test_excludes_unsafe_documents(self) -> None:
+ self._create_source(always_include=True, safe=False)
+ results = get_always_on_context(self.team.id)
+ assert len(results) == 0
+
+ def test_excludes_non_ready_sources(self) -> None:
+ self._create_source(always_include=True, status=SourceStatus.PROCESSING)
+ results = get_always_on_context(self.team.id)
+ assert len(results) == 0
+
+ def test_respects_char_cap(self) -> None:
+ source = KnowledgeSource.objects.unscoped().create(
+ team_id=self.team.id,
+ name="big",
+ source_type="text",
+ status=SourceStatus.READY,
+ always_include=True,
+ )
+ doc = KnowledgeDocument.objects.unscoped().create(
+ team_id=self.team.id,
+ source=source,
+ stable_id=str(uuid.uuid4()),
+ title="big doc",
+ content="x",
+ content_hash="def",
+ safety_verdict=SafetyVerdict.SAFE,
+ )
+ # Create chunks that together exceed the cap
+ chunk_size = MAX_ALWAYS_ON_CONTEXT_CHARS // 2 + 1
+ for i in range(3):
+ KnowledgeChunk.objects.unscoped().create(
+ id=uuid.uuid4(),
+ team_id=self.team.id,
+ source=source,
+ document=doc,
+ ordinal=i,
+ content="x" * chunk_size,
+ char_count=chunk_size,
+ )
+ results = get_always_on_context(self.team.id)
+ total = sum(len(r.content) for r in results)
+ assert total <= MAX_ALWAYS_ON_CONTEXT_CHARS
+ # Should have gotten at most 1 chunk (2nd would exceed cap)
+ assert len(results) == 1
diff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.ts
index dcbf3f4a1d0b..bfb4c8227b65 100644
--- a/products/business_knowledge/frontend/api.ts
+++ b/products/business_knowledge/frontend/api.ts
@@ -27,6 +27,7 @@ export interface CreateUrlSourcePayload {
max_pages?: number
max_depth?: number
refresh_interval?: RefreshIntervalValue
+ always_include?: boolean
}
export interface UpdateSourcePayload {
@@ -39,6 +40,7 @@ export interface UpdateSourcePayload {
max_pages?: number
max_depth?: number
refresh_interval?: RefreshIntervalValue
+ always_include?: boolean
}
export async function listSources(): Promise<KnowledgeSourceApi[]> {
@@ -51,8 +53,12 @@ export async function getSourceText(id: string): Promise<{ id: string; text: str
return { id, text: response.text ?? '' }
}
-export async function createTextSource(name: string, text: string): Promise<KnowledgeSourceApi> {
- return await businessKnowledgeSourcesCreate(String(getCurrentTeamId()), { name, text })
+export async function createTextSource(
+ name: string,
+ text: string,
+ always_include: boolean = false
+): Promise<KnowledgeSourceApi> {
+ return await businessKnowledgeSourcesCreate(String(getCurrentTeamId()), { name, text, always_include })
}
export async function createUrlSource(payload: CreateUrlSourcePayload): Promise<KnowledgeSourceApi> {
diff --git a/products/business_knowledge/frontend/components/AlwaysIncludeField.tsx b/products/business_knowledge/frontend/components/AlwaysIncludeField.tsx
new file mode 100644
index 000000000000..9611e71968ca
--- /dev/null
+++ b/products/business_knowledge/frontend/components/AlwaysIncludeField.tsx
@@ -0,0 +1,22 @@
+import { LemonCheckbox } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+export function AlwaysIncludeField(): JSX.Element {
+ return (
+ <LemonField
+ name="always_include"
+ info="When on, this source's content is injected into every reply as general guidance (tone, policies, company direction) — not just when it matches the question. Still gated by the same safety checks as search."
+ >
+ {({ value, onChange }) => (
+ <LemonCheckbox
+ checked={!!value}
+ onChange={onChange}
+ label="Always include in replies"
+ bordered
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )
+}
diff --git a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx
index da4b4cadd990..addbcb3c3f89 100644
--- a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx
+++ b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx
@@ -11,6 +11,7 @@ import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import type { RefreshIntervalOption } from '../api'
import { CreateTab, businessKnowledgeLogic } from '../scenes/businessKnowledgeLogic'
+import { AlwaysIncludeField } from './AlwaysIncludeField'
import { CrawlConfigFields } from './CrawlConfigFields'
import { CrawlModeHelp } from './CrawlModeHelp'
@@ -77,6 +78,7 @@ export function CreateKnowledgeSourceModal({
Text is chunked paragraph-by-paragraph and stored in Postgres. The support agent can
find it via SQL — no embeddings or vector DB in this stage.
</p>
+ <AlwaysIncludeField />
</Form>
),
},
@@ -122,6 +124,7 @@ export function CreateKnowledgeSourceModal({
>
<LemonSelect options={refreshIntervalOptions} />
</LemonField>
+ <AlwaysIncludeField />
</Form>
),
},
@@ -153,6 +156,7 @@ export function CreateKnowledgeSourceModal({
PDF, DOCX, Markdown, CSV, or plain text. Max 50 MB. The file is parsed into text and
chunked — the original file is not stored.
</p>
+ <AlwaysIncludeField />
</Form>
),
},
diff --git a/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
index a4ab52264ff4..30a0ff35bffc 100644
--- a/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
+++ b/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
@@ -10,6 +10,7 @@ import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import type { RefreshIntervalOption } from '../api'
import { businessKnowledgeLogic } from '../scenes/businessKnowledgeLogic'
+import { AlwaysIncludeField } from './AlwaysIncludeField'
import { CrawlConfigFields } from './CrawlConfigFields'
export function EditKnowledgeSourceModal({
@@ -73,6 +74,7 @@ export function EditKnowledgeSourceModal({
>
<LemonSelect options={refreshIntervalOptions} />
</LemonField>
+ <AlwaysIncludeField />
<p className="text-xs text-muted">Changing the URL or crawl settings will trigger a re-crawl.</p>
</Form>
) : editingSource?.source_type === 'text' && editingSourceTextLoading ? (
@@ -102,6 +104,7 @@ export function EditKnowledgeSourceModal({
until they refresh their prompt.
</p>
)}
+ <AlwaysIncludeField />
</Form>
)}
</LemonModal>
diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.ts
index a75623a93119..98308e1bf52e 100644
--- a/products/business_knowledge/frontend/generated/api.schemas.ts
+++ b/products/business_knowledge/frontend/generated/api.schemas.ts
@@ -174,6 +174,7 @@ export interface KnowledgeSourceApi {
readonly file_content_type: string
/** @nullable */
readonly file_size_bytes: number | null
+ readonly always_include: boolean
}
export interface PaginatedKnowledgeSourceListApi {
@@ -193,11 +194,13 @@ export interface CreateTextSourceApi {
name: string
/** Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL/file support in Stage 2/3. */
text: string
+ /** When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction). */
+ always_include?: boolean
}
/**
- * PATCH payload for text sources. Both fields optional, at least one
- * required. `text` triggers a re-chunk; `name` alone does not.
+ * PATCH payload for text sources. All fields optional, at least one
+ * required. `text` triggers a re-chunk; `name` or `always_include` alone does not.
*/
export interface PatchedUpdateTextSourceApi {
/**
@@ -207,6 +210,8 @@ export interface PatchedUpdateTextSourceApi {
name?: string
/** Replacement text. Omit to keep the existing content. */
text?: string
+ /** When true, this source's content is injected into every support reply prompt as general context. */
+ always_include?: boolean
}
export type BusinessKnowledgeDocumentsWindowListParams = {
diff --git a/products/business_knowledge/frontend/generated/api.zod.ts b/products/business_knowledge/frontend/generated/api.zod.ts
index 8a82257124a4..be8c0a86c6ca 100644
--- a/products/business_knowledge/frontend/generated/api.zod.ts
+++ b/products/business_knowledge/frontend/generated/api.zod.ts
@@ -11,6 +11,8 @@ import * as zod from 'zod'
export const businessKnowledgeSourcesCreateBodyNameMax = 255
+export const businessKnowledgeSourcesCreateBodyAlwaysIncludeDefault = false
+
export const BusinessKnowledgeSourcesCreateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -21,6 +23,12 @@ export const BusinessKnowledgeSourcesCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL\/file support in Stage 2\/3.'
),
+ always_include: zod
+ .boolean()
+ .default(businessKnowledgeSourcesCreateBodyAlwaysIncludeDefault)
+ .describe(
+ "When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction)."
+ ),
})
export const businessKnowledgeSourcesPartialUpdateBodyNameMax = 255
@@ -33,9 +41,15 @@ export const BusinessKnowledgeSourcesPartialUpdateBody = /* @__PURE__ */ zod
.optional()
.describe('New human label for the source.'),
text: zod.string().optional().describe('Replacement text. Omit to keep the existing content.'),
+ always_include: zod
+ .boolean()
+ .optional()
+ .describe(
+ "When true, this source's content is injected into every support reply prompt as general context."
+ ),
})
.describe(
- 'PATCH payload for text sources. Both fields optional, at least one\nrequired. `text` triggers a re-chunk; `name` alone does not.'
+ 'PATCH payload for text sources. All fields optional, at least one\nrequired. `text` triggers a re-chunk; `name` or `always_include` alone does not.'
)
export const BusinessKnowledgeSourcesRefreshCreateBody = /* @__PURE__ */ zod.looseObject({})
diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
index 33d3778a0c63..290b3b9c9e48 100644
--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
@@ -24,6 +24,7 @@ export type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'
export interface TextSourceFormValues {
name: string
text: string
+ always_include: boolean
}
export interface UrlSourceFormValues {
@@ -38,11 +39,13 @@ export interface UrlSourceFormValues {
max_depth: number
// Background auto-refresh cadence, sent on both create and edit.
refresh_interval: RefreshIntervalValue
+ always_include: boolean
}
export interface FileSourceFormValues {
name: string
file: File | null
+ always_include: boolean
}
export type CreateTab = 'text' | 'url' | 'file'
@@ -161,11 +164,11 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
})),
forms(({ actions, values }) => ({
textSource: {
- defaults: { name: '', text: '' } as TextSourceFormValues,
+ defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,
errors: validateText,
- submit: async ({ name, text }: TextSourceFormValues) => {
+ submit: async ({ name, text, always_include }: TextSourceFormValues) => {
try {
- const created = await createTextSource(name, text)
+ const created = await createTextSource(name, text, always_include)
lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
actions.closeCreateModal()
actions.resetTextSource()
@@ -190,6 +193,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
max_pages: 50,
max_depth: 2,
refresh_interval: 'manual',
+ always_include: false,
} as UrlSourceFormValues,
errors: validateUrl,
submit: async (values: UrlSourceFormValues) => {
@@ -200,6 +204,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
source_type: 'url',
crawl_mode: values.crawl_mode,
refresh_interval: values.refresh_interval,
+ always_include: values.always_include,
...(values.crawl_mode !== 'single' && {
// Only send include_globs when the user explicitly set them;
// otherwise the backend auto-derives scope from the entry URL path.
@@ -229,7 +234,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
},
},
fileSource: {
- defaults: { name: '', file: null } as FileSourceFormValues,
+ defaults: { name: '', file: null, always_include: false } as FileSourceFormValues,
errors: ({ name, file }: FileSourceFormValues) => ({
name: !name.trim() ? 'Give the source a short name' : undefined,
file: !file
@@ -238,7 +243,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
? 'File exceeds the 50 MB cap'
: undefined,
}),
- submit: async ({ name, file }: FileSourceFormValues) => {
+ submit: async ({ name, file, always_include }: FileSourceFormValues) => {
if (!file) {
return
}
@@ -246,6 +251,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
formData.append('name', name)
formData.append('file', file)
formData.append('source_type', 'file')
+ formData.append('always_include', String(always_include))
try {
const created = await createFileSource(formData)
lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
@@ -264,7 +270,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
},
},
editSource: {
- defaults: { name: '', text: '' } as TextSourceFormValues,
+ defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,
errors: ({ name, text }: TextSourceFormValues) => {
const isText = values.editingSource?.source_type === 'text'
return {
@@ -278,13 +284,13 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
: undefined,
}
},
- submit: async ({ name, text }: TextSourceFormValues) => {
+ submit: async ({ name, text, always_include }: TextSourceFormValues) => {
const current = values.editingSource
if (!current) {
return
}
const isText = current.source_type === 'text'
- const payload: UpdateSourcePayload = { name, ...(isText && { text }) }
+ const payload: UpdateSourcePayload = { name, always_include, ...(isText && { text }) }
try {
const updated = await updateSource(current.id, payload)
const msg = isText
@@ -315,6 +321,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
max_pages: 50,
max_depth: 2,
refresh_interval: 'manual',
+ always_include: false,
} as UrlSourceFormValues,
errors: validateUrl,
submit: async (vals: UrlSourceFormValues) => {
@@ -328,6 +335,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
url: vals.url,
crawl_mode: vals.crawl_mode,
refresh_interval: vals.refresh_interval,
+ always_include: vals.always_include,
...(vals.crawl_mode !== 'single' && {
...(editIncludeGlobs.length > 0 && { include_globs: editIncludeGlobs }),
exclude_globs: splitGlobs(vals.exclude_globs),
@@ -413,9 +421,14 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
max_pages: cfg.max_pages ?? 50,
max_depth: cfg.max_depth ?? 2,
refresh_interval: (source.refresh_interval || 'manual') as RefreshIntervalValue,
+ always_include: source.always_include ?? false,
})
} else {
- actions.setEditSourceValues({ name: source.name, text: '' })
+ actions.setEditSourceValues({
+ name: source.name,
+ text: '',
+ always_include: source.always_include ?? false,
+ })
if (source.source_type === 'text') {
actions.loadEditingSourceText({ id: source.id })
}
diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yaml
index a221ac5d064b..5eab3ae1bf6e 100644
--- a/products/business_knowledge/mcp/tools.yaml
+++ b/products/business_knowledge/mcp/tools.yaml
@@ -68,13 +68,27 @@ tools:
- chunk_count
- source_url
- has_unsafe_documents
+ - always_include
- refresh_interval
- next_refresh_at
- created_at
- updated_at
business-knowledge-sources-partial-update:
operation: business_knowledge_sources_partial_update
- enabled: false
+ enabled: true
+ scopes:
+ - business_knowledge:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update business knowledge source
+ 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.
+ feature_flag: product-business-knowledge
business-knowledge-sources-refresh-create:
operation: business_knowledge_sources_refresh_create
enabled: false
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
index dddacf8406c4..e01e9602dba1 100644
--- a/products/conversations/backend/temporal/pipeline.py
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -24,7 +24,9 @@ with workflow.unsafe.imports_passed_through():
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.utils import close_db_connections
+ from products.business_knowledge.backend.constants import MAX_ALWAYS_ON_CONTEXT_CHARS
from products.business_knowledge.backend.logic import (
+ get_always_on_context,
get_chunks_by_ids,
get_document_window,
rerank_chunks,
@@ -86,6 +88,7 @@ class SupportReplyInput:
class BuildContextOutput:
ticket_context: str
ticket_title: str
+ always_on_context: str = ""
@dataclass
@@ -124,6 +127,7 @@ class DraftInput:
# instead of re-rolling blind (which tends to drift to a worse, less-grounded answer).
prior_reply: str = ""
prior_missing: list[str] = field(default_factory=list)
+ always_on_context: str = ""
@dataclass
@@ -205,7 +209,11 @@ def _build_context_sync(team_id: int, ticket_id: str) -> BuildContextOutput:
)
context = _build_ticket_context(ticket, comments, team)[:MAX_TICKET_CONTEXT_CHARS]
title = getattr(ticket, "title", "") or f"Ticket {ticket_id}"
- return BuildContextOutput(ticket_context=context, ticket_title=title)
+
+ always_on_chunks = get_always_on_context(team_id)
+ always_on_text = "\n\n".join(c.content for c in always_on_chunks) if always_on_chunks else ""
+
+ return BuildContextOutput(ticket_context=context, ticket_title=title, always_on_context=always_on_text)
@activity.defn
@@ -322,7 +330,12 @@ async def draft_activity(input: DraftInput) -> DraftOutput:
"""Run a sandbox session with read-only MCP to draft a reply."""
async with Heartbeater():
return await _draft_async(
- input.team_id, input.ticket_context, input.chunk_ids, input.prior_reply, input.prior_missing
+ input.team_id,
+ input.ticket_context,
+ input.chunk_ids,
+ input.prior_reply,
+ input.prior_missing,
+ input.always_on_context,
)
@@ -332,6 +345,7 @@ async def _draft_async(
chunk_ids: list[str],
prior_reply: str = "",
prior_missing: list[str] | None = None,
+ always_on_context: str = "",
) -> DraftOutput:
chunks = await database_sync_to_async(_hydrate_chunks, thread_sensitive=False)(team_id, chunk_ids)
user_id = await database_sync_to_async(resolve_user_id_for_support, thread_sensitive=False)(team_id)
@@ -367,6 +381,14 @@ Keep everything in the previous reply that was correct and grounded. Fix the fla
searching for sources that close those gaps, and REMOVE any claim you cannot back with a source
excerpt. Do not introduce new unsupported information."""
+ company_context_block = ""
+ if always_on_context:
+ company_context_block = f"""
+COMPANY CONTEXT (always-on guidance — tone, policies, direction):
+{always_on_context[:MAX_ALWAYS_ON_CONTEXT_CHARS]}
+
+"""
+
prompt = f"""You are a support agent drafting a reply to a customer ticket.
SECURITY:
@@ -383,6 +405,7 @@ TICKET CONTEXT (untrusted data):
{ticket_context[:6000]}
</ticket_context>
+{company_context_block}
KNOWLEDGE BASE RESULTS:
{chunks_text[:12000]}{refinement}
@@ -607,6 +630,7 @@ class SupportReplyWorkflow:
chunk_ids=retrieve_output.chunk_ids,
prior_reply=prior_reply,
prior_missing=missing,
+ always_on_context=ctx_output.always_on_context,
),
start_to_close_timeout=timedelta(minutes=15),
retry_policy=RetryPolicy(maximum_attempts=2),
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index 2120c80194d0..0a36406e2a69 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -484,3 +484,63 @@ class TestValidateActivity:
assert result.grounded is False
assert result.confidence == 0.0
assert "parse_failure" in result.missing
+
+
+@patch(f"{PIPELINE_MODULE}._persist_reply_sync")
+@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._draft_async", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._retrieve_sync")
+@patch(f"{PIPELINE_MODULE}._refine_queries", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._build_context_sync")
+async def test_always_on_context_plumbed_to_draft(
+ mock_build,
+ mock_refine,
+ mock_retrieve,
+ mock_draft,
+ mock_validate,
+ mock_persist,
+ workflow_input,
+ sample_chunk_ids,
+):
+ from temporalio.testing import WorkflowEnvironment
+ from temporalio.worker import Worker
+
+ mock_build.return_value = BuildContextOutput(
+ ticket_context="ticket text",
+ ticket_title="Help",
+ always_on_context="Be friendly and professional.",
+ )
+ mock_refine.return_value = RefineQueriesOutput(queries=["test query"])
+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)
+ mock_draft.return_value = DraftOutput(
+ reply="Hi!",
+ citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
+ confidence=0.95,
+ )
+ mock_validate.return_value = ValidateOutput(grounded=True, coverage=0.95, confidence=0.95, missing=[])
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue="test-queue",
+ workflows=[SupportReplyWorkflow],
+ activities=[
+ build_context_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ draft_activity,
+ validate_activity,
+ persist_reply_activity,
+ ],
+ ):
+ await env.client.execute_workflow(
+ SupportReplyWorkflow.run,
+ workflow_input,
+ id="test-always-on",
+ task_queue="test-queue",
+ )
+
+ # always_on_context is the 6th positional arg to _draft_async
+ assert mock_draft.call_args[0][5] == "Be friendly and professional."
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 0135be28096f..99593628aa9b 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1203,6 +1203,21 @@
},
"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.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Update business knowledge source",
+ "title": "Update business knowledge source",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
"business-knowledge-sources-retrieve": {
"description": "Get a single business knowledge source by ID, including processing status, document/chunk counts, and refresh metadata.",
"category": "Business knowledge",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 12f0f97a063e..cd6133e42059 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1233,6 +1233,21 @@
},
"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.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Update business knowledge source",
+ "title": "Update business knowledge source",
+ "required_scopes": ["business_knowledge:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "product-business-knowledge"
+ },
"business-knowledge-sources-retrieve": {
"description": "Get a single business knowledge source by ID, including processing status, document/chunk counts, and refresh metadata.",
"category": "Business knowledge",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 02ecf8c4dcd2..6f8707543da4 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -50,6 +50,11 @@
"description": "How often to auto-refresh this source in the background. Defaults to \"manual\" (no auto-refresh).",
"type": "string",
"enum": ["manual", "1h", "6h", "24h", "7d"]
+ },
+ "always_include": {
+ "default": false,
+ "description": "When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction), not just when it matches a query.",
+ "type": "boolean"
}
},
"required": ["name", "url"]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b48dcf3e8256..fd77bc2e30f6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13913,6 +13913,8 @@ export namespace Schemas {
name: string;
/** Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL/file support in Stage 2/3. */
text: string;
+ /** When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction). */
+ always_include?: boolean;
}
export interface TileLayoutBox {
@@ -26482,6 +26484,7 @@ export namespace Schemas {
readonly file_content_type: string;
/** @nullable */
readonly file_size_bytes: number | null;
+ readonly always_include: boolean;
}
export interface LLMModelInfo {
@@ -40070,8 +40073,8 @@ export namespace Schemas {
}
/**
- * PATCH payload for text sources. Both fields optional, at least one
- * required. `text` triggers a re-chunk; `name` alone does not.
+ * PATCH payload for text sources. All fields optional, at least one
+ * required. `text` triggers a re-chunk; `name` or `always_include` alone does not.
*/
export interface PatchedUpdateTextSource {
/**
@@ -40081,6 +40084,8 @@ export namespace Schemas {
name?: string;
/** Replacement text. Omit to keep the existing content. */
text?: string;
+ /** When true, this source's content is injected into every support reply prompt as general context. */
+ always_include?: boolean;
}
/**
diff --git a/services/mcp/src/generated/business_knowledge/api.ts b/services/mcp/src/generated/business_knowledge/api.ts
index 84aa9e5560c0..3b8ae7bda8ae 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 5 enabled ops
+ * PostHog API - MCP 6 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -81,6 +81,8 @@ export const BusinessKnowledgeSourcesCreateParams = /* @__PURE__ */ zod.object({
export const businessKnowledgeSourcesCreateBodyNameMax = 255
+export const businessKnowledgeSourcesCreateBodyAlwaysIncludeDefault = false
+
export const BusinessKnowledgeSourcesCreateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -91,6 +93,12 @@ export const BusinessKnowledgeSourcesCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL/file support in Stage 2/3.'
),
+ always_include: zod
+ .boolean()
+ .default(businessKnowledgeSourcesCreateBodyAlwaysIncludeDefault)
+ .describe(
+ "When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction)."
+ ),
})
export const BusinessKnowledgeSourcesRetrieveParams = /* @__PURE__ */ zod.object({
@@ -101,3 +109,33 @@ export const BusinessKnowledgeSourcesRetrieveParams = /* @__PURE__ */ zod.object
"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 BusinessKnowledgeSourcesPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this knowledge source.'),
+ 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 businessKnowledgeSourcesPartialUpdateBodyNameMax = 255
+
+export const BusinessKnowledgeSourcesPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(businessKnowledgeSourcesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('New human label for the source.'),
+ text: zod.string().optional().describe('Replacement text. Omit to keep the existing content.'),
+ always_include: zod
+ .boolean()
+ .optional()
+ .describe(
+ "When true, this source's content is injected into every support reply prompt as general context."
+ ),
+ })
+ .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/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 52c022b848e9..d52d99a69cc1 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -16,6 +16,13 @@ export const BusinessKnowledgeUrlSourceCreateSchema = z.object({
.optional()
.default('manual')
.describe('How often to auto-refresh this source in the background. Defaults to "manual" (no auto-refresh).'),
+ always_include: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(
+ "When true, this source's content is injected into every support reply prompt as general context (tone, policies, direction), not just when it matches a query."
+ ),
})
export const AgentResolveResourceSchema = z.object({
diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.ts
index 81095e4d74d1..b1736d6b493c 100644
--- a/services/mcp/src/tools/generated/business_knowledge.ts
+++ b/services/mcp/src/tools/generated/business_knowledge.ts
@@ -8,6 +8,8 @@ import {
BusinessKnowledgeDocumentsWindowListQueryParams,
BusinessKnowledgeSourcesCreateBody,
BusinessKnowledgeSourcesListQueryParams,
+ BusinessKnowledgeSourcesPartialUpdateBody,
+ BusinessKnowledgeSourcesPartialUpdateParams,
BusinessKnowledgeSourcesRetrieveParams,
} from '@/generated/business_knowledge/api'
import { BusinessKnowledgeUrlSourceCreateSchema } from '@/schema/tool-inputs'
@@ -92,6 +94,7 @@ const businessKnowledgeSourcesList = (): ToolBase<
'chunk_count',
'source_url',
'has_unsafe_documents',
+ 'always_include',
'refresh_interval',
'next_refresh_at',
'created_at',
@@ -103,6 +106,37 @@ const businessKnowledgeSourcesList = (): ToolBase<
},
})
+const BusinessKnowledgeSourcesPartialUpdateSchema = BusinessKnowledgeSourcesPartialUpdateParams.omit({
+ project_id: true,
+}).extend(BusinessKnowledgeSourcesPartialUpdateBody.shape)
+
+const businessKnowledgeSourcesPartialUpdate = (): ToolBase<
+ typeof BusinessKnowledgeSourcesPartialUpdateSchema,
+ Schemas.KnowledgeSource
+> => ({
+ name: 'business-knowledge-sources-partial-update',
+ schema: BusinessKnowledgeSourcesPartialUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeSourcesPartialUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.text !== undefined) {
+ body['text'] = params.text
+ }
+ if (params.always_include !== undefined) {
+ body['always_include'] = params.always_include
+ }
+ const result = await context.api.request<Schemas.KnowledgeSource>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
const BusinessKnowledgeSourcesRetrieveSchema = BusinessKnowledgeSourcesRetrieveParams.omit({ project_id: true })
const businessKnowledgeSourcesRetrieve = (): ToolBase<
@@ -138,6 +172,9 @@ const businessKnowledgeSourcesTextCreate = (): ToolBase<
if (params.text !== undefined) {
body['text'] = params.text
}
+ if (params.always_include !== undefined) {
+ body['always_include'] = params.always_include
+ }
const result = await context.api.request<Schemas.KnowledgeSource>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/`,
@@ -171,6 +208,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'business-knowledge-document-window-retrieve': businessKnowledgeDocumentWindowRetrieve,
'business-knowledge-documents-search': businessKnowledgeDocumentsSearch,
'business-knowledge-sources-list': businessKnowledgeSourcesList,
+ 'business-knowledge-sources-partial-update': businessKnowledgeSourcesPartialUpdate,
'business-knowledge-sources-retrieve': businessKnowledgeSourcesRetrieve,
'business-knowledge-sources-text-create': businessKnowledgeSourcesTextCreate,
'business-knowledge-sources-url-create': businessKnowledgeSourcesUrlCreate,