:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(customer-analytics): isolate behind facade, contracts and presentation (#64336)
Arthur Moreira de Deusaae1166c9e1c
diff --git a/ee/billing/queue/BillingConsumer.py b/ee/billing/queue/BillingConsumer.pyindex 472e63a92374..97d679eaaec0 100644--- a/ee/billing/queue/BillingConsumer.py+++ b/ee/billing/queue/BillingConsumer.py@@ -9,7 +9,7 @@ from posthog.cloud_utils import get_cached_instance_licensefrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.organization import Organization-from products.customer_analytics.backend.services.usage_spike_notifications import notify_managers_of_usage_spike+from products.customer_analytics.backend.facade.api import notify_managers_of_usage_spikefrom ee.billing.billing_manager import BillingManagerfrom ee.sqs.SQSConsumer import SQSConsumerdiff --git a/ee/hogai/context/account/context.py b/ee/hogai/context/account/context.pyindex ed078b6841f3..b3f4ba486260 100644--- a/ee/hogai/context/account/context.py+++ b/ee/hogai/context/account/context.py@@ -1,16 +1,16 @@-from django.core.exceptions import ObjectDoesNotExist, ValidationError+from django.core.exceptions import ObjectDoesNotExist-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.models.group.util import get_group_by_key-from posthog.models.tagged_item import TaggedItem+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_async-from products.customer_analytics.backend.constants import (+from products.customer_analytics.backend.facade.api import get_account_context_data+from products.customer_analytics.backend.facade.constants import (BILLING_SPEND_INSIGHT_SHORT_IDS,BILLING_USAGE_INSIGHT_SHORT_IDS,)-from products.customer_analytics.backend.models import Account-from products.notebooks.backend.models import Notebook, ResourceNotebook+from products.customer_analytics.backend.facade.contracts import AccountContextDatafrom .prompts import (ACCOUNT_ANALYSIS_CONNECTED_TEMPLATE,@@ -44,27 +44,30 @@ class AccountContext:agent can scope usage and event analysis to the right group."""- def __init__(self, team: Team, account_id: str | None = None, external_id: str | None = None):+ def __init__(self, team: Team, user: User, account_id: str | None = None, external_id: str | None = None):self._team = team+ self._user = userself._account_id = account_idself._external_id = external_id- async def aget_account(self) -> Account | None:- try:- if self._account_id:- return await Account.objects.unscoped().aget(id=self._account_id, team=self._team)- if self._external_id:- return await Account.objects.unscoped().aget(external_id=self._external_id, team=self._team)- return None- except (Account.DoesNotExist, ValidationError, ValueError):- return None+ @property+ def user_access_control(self) -> UserAccessControl:+ return UserAccessControl(user=self._user, team=self._team, organization_id=str(self._team.organization_id))++ async def aget_account(self) -> AccountContextData | None:+ return await database_sync_to_async(get_account_context_data)(+ team_id=self._team.id,+ account_id=self._account_id,+ external_id=self._external_id,+ user_access_control=self.user_access_control,+ )def get_not_found_message(self) -> str:identifier = f"id={self._account_id}" if self._account_id else f"external_id={self._external_id}"return ACCOUNT_NOT_FOUND_TEMPLATE.format(identifier=identifier)@database_sync_to_async- def format_account(self, account: Account) -> str:+ def format_account(self, account: AccountContextData) -> str:return ACCOUNT_CONTEXT_TEMPLATE.format(name=account.name,account_id=str(account.id),@@ -83,7 +86,7 @@ class AccountContext:return self.get_not_found_message()return await self.format_account(account)- def _roles_section(self, account: Account) -> str:+ def _roles_section(self, account: AccountContextData) -> str:properties = account.propertieslines = [f"- {label}: {assignment.email} (user {assignment.id})"@@ -94,35 +97,25 @@ class AccountContext:return ""return "\n" + ACCOUNT_ROLES_TEMPLATE.format(roles_list="\n".join(lines))- def _external_ids_section(self, account: Account) -> str:+ def _external_ids_section(self, account: AccountContextData) -> str:properties = account.propertieslines = [f"- {label}: {value}" for label, field in _EXTERNAL_ID_LABELS if (value := getattr(properties, field))]if not lines:return ""return "\n" + ACCOUNT_EXTERNAL_IDS_TEMPLATE.format(ids_list="\n".join(lines))- def _tags_section(self, account: Account) -> str:- tags = sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))- if not tags:+ def _tags_section(self, account: AccountContextData) -> str:+ if not account.tags:return ""- return "\n" + ACCOUNT_TAGS_TEMPLATE.format(tags_list=", ".join(tags))-- def _notes_section(self, account: Account) -> str:- links = (- ResourceNotebook.objects.filter(- account=account,- notebook__deleted=False,- notebook__visibility=Notebook.Visibility.INTERNAL,- )- .select_related("notebook")- .order_by("-notebook__last_modified_at")- )- lines = [f'- "{link.notebook.title}" (short_id: {link.notebook.short_id})' for link in links]+ return "\n" + ACCOUNT_TAGS_TEMPLATE.format(tags_list=", ".join(account.tags))++ def _notes_section(self, account: AccountContextData) -> str:+ lines = [f'- "{note.title}" (short_id: {note.short_id})' for note in account.notes]if not lines:return ""return "\n" + ACCOUNT_NOTES_TEMPLATE.format(notes_list="\n".join(lines))- def _analysis_section(self, account: Account) -> str:+ def _analysis_section(self, account: AccountContextData) -> str:group_type_index = self._account_group_type_index()if group_type_index is None:return ACCOUNT_ANALYSIS_NOT_CONFIGURED_TEMPLATE@@ -130,7 +123,7 @@ class AccountContext:return ACCOUNT_ANALYSIS_NO_EXTERNAL_ID_TEMPLATEgroup = get_group_by_key(- team_id=account.team_id, group_type_index=group_type_index, group_key=account.external_id+ team_id=self._team.id, group_type_index=group_type_index, group_key=account.external_id)if group is None:return ACCOUNT_ANALYSIS_GROUP_NOT_FOUND_TEMPLATE.format(group_key=account.external_id)diff --git a/ee/hogai/context/account/test/test_context.py b/ee/hogai/context/account/test/test_context.pyindex 671f0df0c52d..f4ea38917b10 100644--- a/ee/hogai/context/account/test/test_context.py+++ b/ee/hogai/context/account/test/test_context.py@@ -1,17 +1,23 @@import uuid+from typing import TYPE_CHECKINGfrom posthog.test.base import NonAtomicBaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, PropertyMock, patch+from django.apps import appsfrom django.core.exceptions import ObjectDoesNotExistfrom asgiref.sync import sync_to_asyncfrom posthog.api.tagged_item import set_tags_on_object-from products.customer_analytics.backend.models import Accountfrom products.notebooks.backend.models import Notebook, ResourceNotebook+if TYPE_CHECKING:+ from products.customer_analytics.backend.models import Account+else:+ Account = apps.get_model("customer_analytics", "Account")+from ee.hogai.context.account.context import AccountContext@@ -24,7 +30,7 @@ class TestAccountContext(NonAtomicBaseTest):async def test_aget_account_by_id(self):account = await self._create_account(name="Acme Corp", external_id="acme-1")- fetched = await AccountContext(team=self.team, account_id=str(account.id)).aget_account()+ fetched = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).aget_account()assert fetched is not Noneassert fetched.id == account.id@@ -32,23 +38,37 @@ class TestAccountContext(NonAtomicBaseTest):async def test_aget_account_by_external_id(self):account = await self._create_account(name="Acme Corp", external_id="acme-1")- fetched = await AccountContext(team=self.team, external_id="acme-1").aget_account()+ fetched = await AccountContext(team=self.team, user=self.user, external_id="acme-1").aget_account()assert fetched is not Noneassert fetched.id == account.idasync def test_aget_account_invalid_id_returns_none(self):- assert await AccountContext(team=self.team, account_id="not-a-uuid").aget_account() is None+ assert await AccountContext(team=self.team, user=self.user, account_id="not-a-uuid").aget_account() is None++ async def test_aget_account_denied_by_access_control_is_not_found(self):+ # An account the caller can't read object-level must be indistinguishable from a missing one.+ account = await self._create_account(name="Acme Corp", external_id="acme-1")+ context = AccountContext(team=self.team, user=self.user, account_id=str(account.id))++ with patch.object(AccountContext, "user_access_control", new_callable=PropertyMock) as mock_uac:+ mock_uac.return_value.check_access_level_for_resource.return_value = True+ mock_uac.return_value.filter_queryset_by_access_level.side_effect = lambda qs: qs.none()++ assert await context.aget_account() is None+ result = await context.execute_and_format()++ assert "was not found" in resultasync def test_execute_and_format_not_found(self):- result = await AccountContext(team=self.team, account_id=str(uuid.uuid4())).execute_and_format()+ result = await AccountContext(team=self.team, user=self.user, account_id=str(uuid.uuid4())).execute_and_format()assert "was not found" in resultasync def test_format_includes_basics(self):account = await self._create_account(name="Acme Corp", external_id="acme-1")- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()assert "## Account: Acme Corp" in resultassert str(account.id) in result@@ -57,7 +77,7 @@ class TestAccountContext(NonAtomicBaseTest):async def test_format_external_id_not_set(self):account = await self._create_account(name="Acme Corp")- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()assert "**External ID:** Not set" in result@@ -67,7 +87,7 @@ class TestAccountContext(NonAtomicBaseTest):_properties={"csm": {"id": 42, "email": "[email protected]"}},)- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()assert "### Roles" in resultassert "CSM: [email protected] (user 42)" in result@@ -75,7 +95,7 @@ class TestAccountContext(NonAtomicBaseTest):async def test_format_includes_external_system_ids(self):account = await self._create_account(name="Acme Corp", _properties={"stripe_customer_id": "cus_123"})- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()assert "### External-system ids" in resultassert "Stripe customer id: cus_123" in result@@ -84,7 +104,7 @@ class TestAccountContext(NonAtomicBaseTest):account = await self._create_account(name="Acme Corp")await sync_to_async(set_tags_on_object)(["enterprise", "priority"], account)- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()assert "### Tags" in resultassert "enterprise, priority" in result@@ -100,7 +120,7 @@ class TestAccountContext(NonAtomicBaseTest):)await ResourceNotebook.objects.acreate(notebook=notebook, account=account)- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()assert "### Saved notes" in resultassert "Q3 kickoff recap" in result@@ -113,7 +133,9 @@ class TestAccountContext(NonAtomicBaseTest):patch.object(AccountContext, "_account_group_type_index", return_value=2),patch("ee.hogai.context.account.context.get_group_by_key", return_value=MagicMock()) as mock_lookup,):- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(+ team=self.team, user=self.user, account_id=str(account.id)+ ).execute_and_format()mock_lookup.assert_called_once()assert "<account_analysis_context>" in result@@ -123,7 +145,7 @@ class TestAccountContext(NonAtomicBaseTest):async def test_billing_insights_clause_lists_configured_short_ids(self):# Pins the real short_ids: fails if the constants are deleted, emptied, or changed by accident.assert (- AccountContext(team=self.team)._billing_insights_clause()+ AccountContext(team=self.team, user=self.user)._billing_insights_clause()== " (Usage insight short ids: fiJDsKLp; Spend insight short ids: o4I9sdFE, Tjo4bsux)")@@ -134,7 +156,9 @@ class TestAccountContext(NonAtomicBaseTest):patch.object(AccountContext, "_account_group_type_index", return_value=None),patch("ee.hogai.context.account.context.get_group_by_key") as mock_lookup,):- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(+ team=self.team, user=self.user, account_id=str(account.id)+ ).execute_and_format()mock_lookup.assert_not_called()assert "isn't connected to a group type" in result@@ -146,7 +170,9 @@ class TestAccountContext(NonAtomicBaseTest):patch.object(AccountContext, "_account_group_type_index", return_value=2),patch("ee.hogai.context.account.context.get_group_by_key") as mock_lookup,):- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(+ team=self.team, user=self.user, account_id=str(account.id)+ ).execute_and_format()mock_lookup.assert_not_called()assert "has no external ID" in result@@ -158,7 +184,9 @@ class TestAccountContext(NonAtomicBaseTest):patch.object(AccountContext, "_account_group_type_index", return_value=2),patch("ee.hogai.context.account.context.get_group_by_key", return_value=None),):- result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)+ result = await AccountContext(+ team=self.team, user=self.user, account_id=str(account.id)+ ).execute_and_format()assert "doesn't match any known group" in result@@ -166,7 +194,7 @@ class TestAccountContext(NonAtomicBaseTest):team = MagicMock()team.customer_analytics_config.account_group_type_index = 7- assert AccountContext(team=team)._account_group_type_index() == 7+ assert AccountContext(team=team, user=self.user)._account_group_type_index() == 7async def test_group_type_index_none_when_config_missing(self):class _TeamWithoutConfig:@@ -174,4 +202,4 @@ class TestAccountContext(NonAtomicBaseTest):def customer_analytics_config(self):raise ObjectDoesNotExist- assert AccountContext(team=_TeamWithoutConfig())._account_group_type_index() is None # type: ignore[arg-type]+ assert AccountContext(team=_TeamWithoutConfig(), user=self.user)._account_group_type_index() is None # type: ignore[arg-type]diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex 0de77a2fd5d1..5f521f2adf08 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -1,10 +1,10 @@-from collections.abc import Iterable, Mapping+from collections.abc import Iterablefrom datetime import timedeltafrom enum import StrEnumfrom typing import Any, Literalfrom django.conf import settings-from django.db.models import Max, Q, QuerySet+from django.db.models import Maxfrom django.utils import timezonefrom pydantic import ValidationError@@ -23,8 +23,9 @@ from posthog.sync import database_sync_to_asyncfrom products.actions.backend.models.action import Actionfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.cohorts.backend.models.cohort import Cohort-from products.customer_analytics.backend.account_urls import build_account_deeplink-from products.customer_analytics.backend.models import Account+from products.customer_analytics.backend.facade import api as customer_analytics_facade+from products.customer_analytics.backend.facade.api import build_account_deeplink+from products.customer_analytics.backend.facade.contracts import AccountReffrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flag_status import (@@ -368,21 +369,13 @@ class EntitySearchContext:return all_entities, total_count- def _accounts_queryset(self) -> QuerySet[Account]:- """Base accounts queryset. Uses the unscoped manager since Account is fail-closed."""- if not self.user_access_control.check_access_level_for_resource("account", "viewer"):- return Account.objects.unscoped().none()- return self.user_access_control.filter_queryset_by_access_level(- Account.objects.unscoped().filter(team=self._team)- )-@staticmethod- def _account_entities(accounts: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:+ def _account_entities(accounts: Iterable[AccountRef]) -> list[dict[str, Any]]:return [{"type": "account",- "result_id": str(account["id"]),- "extra_fields": {"name": account["name"], "external_id": account["external_id"]},+ "result_id": account.id,+ "extra_fields": {"name": account.name, "external_id": account.external_id},}for account in accounts]@@ -455,9 +448,9 @@ class EntitySearchContext:return await database_sync_to_async(self._search_accounts_sync, thread_sensitive=False)(query)def _search_accounts_sync(self, query: str) -> tuple[list[dict[str, Any]], int]:- queryset = self._accounts_queryset().filter(Q(name__icontains=query) | Q(external_id__icontains=query))- total_count = queryset.count()- accounts = list(queryset.order_by("name")[:SEARCH_LIMIT].values("id", "name", "external_id"))+ accounts, total_count = customer_analytics_facade.search_accounts(+ self._team.id, query, self.user_access_control, SEARCH_LIMIT+ )return self._account_entities(accounts), total_countasync def _list_accounts(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:@@ -465,9 +458,9 @@ class EntitySearchContext:return await database_sync_to_async(self._list_accounts_sync, thread_sensitive=False)(limit, offset)def _list_accounts_sync(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:- queryset = self._accounts_queryset().order_by("-created_at")- total_count = queryset.count()- accounts = list(queryset[offset : offset + limit].values("id", "name", "external_id"))+ accounts, total_count = customer_analytics_facade.list_accounts(+ self._team.id, offset, limit, self.user_access_control+ )return self._account_entities(accounts), total_countdef _get_entity_row_values(self, result: dict, extra_columns: list[str], include_type: bool) -> list[str]:diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex a1df8b635f76..d4f2d346c828 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -1,9 +1,11 @@from datetime import timedelta+from typing import TYPE_CHECKINGimport pytestfrom posthog.test.base import NonAtomicBaseTestfrom unittest.mock import AsyncMock, MagicMock, PropertyMock, patch+from django.apps import appsfrom django.conf import settingsfrom django.utils import timezone@@ -15,7 +17,6 @@ from posthog.models import Teamfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort-from products.customer_analytics.backend.models import Accountfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -26,6 +27,11 @@ from ee.hogai.context import AssistantContextManagerfrom ee.hogai.context.entity_search import EntitySearchContextfrom ee.models.rbac.access_control import AccessControl+if TYPE_CHECKING:+ from products.customer_analytics.backend.models import Account+else:+ Account = apps.get_model("customer_analytics", "Account")+class TestEntitySearchContext(NonAtomicBaseTest):CLASS_DATA_LEVEL_SETUP = Falsediff --git a/ee/hogai/core/agent_modes/presets/customer_analytics.py b/ee/hogai/core/agent_modes/presets/customer_analytics.pyindex f57089511ee5..e65b69317941 100644--- a/ee/hogai/core/agent_modes/presets/customer_analytics.py+++ b/ee/hogai/core/agent_modes/presets/customer_analytics.py@@ -2,7 +2,7 @@ from typing import TYPE_CHECKINGfrom posthog.schema import AgentMode-from products.customer_analytics.backend.max_tools import UpsertAccountNotebookTool, UpsertAccountTool+from products.customer_analytics.backend.facade.max_tools import UpsertAccountNotebookTool, UpsertAccountToolfrom ee.hogai.chat_agent.executables import ChatAgentExecutable, ChatAgentToolsExecutablefrom ee.hogai.tools.todo_write import TodoWriteExamplediff --git a/ee/hogai/tools/full_text_search/test/test_tool.py b/ee/hogai/tools/full_text_search/test/test_tool.pyindex f920d244cf16..40c07d3c7732 100644--- a/ee/hogai/tools/full_text_search/test/test_tool.py+++ b/ee/hogai/tools/full_text_search/test/test_tool.py@@ -1,13 +1,20 @@+from typing import TYPE_CHECKING+from posthog.test.base import NonAtomicBaseTestfrom unittest.mock import ANY, patch-from langchain_core.runnables import RunnableConfig+from django.apps import apps-from products.customer_analytics.backend.models import Account+from langchain_core.runnables import RunnableConfigfrom ee.hogai.context import AssistantContextManagerfrom ee.hogai.context.entity_search.context import ENTITY_MAPfrom ee.hogai.core.shared_prompts import HYPERLINK_USAGE_INSTRUCTIONS++if TYPE_CHECKING:+ from products.customer_analytics.backend.models import Account+else:+ Account = apps.get_model("customer_analytics", "Account")from ee.hogai.tools.full_text_search.tool import EntityKind, EntitySearchToolfrom ee.hogai.utils.types.base import AssistantStatediff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 8b22538f46bc..df808e96e57c 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -1,10 +1,12 @@-from typing import Literal+from typing import TYPE_CHECKING, Literalfrom uuid import uuid4import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.apps import apps+from parameterized import parameterizedfrom posthog.schema import (@@ -22,7 +24,6 @@ from products.ai_observability.backend.summarization.llm.schema import (SummarizationResponse,SummaryBullet,)-from products.customer_analytics.backend.models import Accountfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -39,6 +40,11 @@ from ee.hogai.tools.read_data.tool import ReadDataToolfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessage, NodePath+if TYPE_CHECKING:+ from products.customer_analytics.backend.models import Account+else:+ Account = apps.get_model("customer_analytics", "Account")+def _make_trace_data(trace_id: str = "trace-1",diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex 1dcbd3d036f0..3ef91707f609 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -709,15 +709,18 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):context = AccountContext(team=self._team,+ user=self._user,account_id=account_id,external_id=external_id,)+ # Object-level access is enforced inside the facade (AccountContextData is a+ # contract, not a model, so check_object_access can't gate it here); a denied+ # account comes back as None and is reported as not found.account = await context.aget_account()if account is None:raise MaxToolRetryableError(context.get_not_found_message())- await self.check_object_access(account, "viewer", resource="account", action="read")return await context.format_account(account)async def _read_activity_log(diff --git a/posthog/api/team.py b/posthog/api/team.pyindex e087f59972ff..f3a4ba71da20 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -87,7 +87,7 @@ from posthog.utils import (safe_cache_set,)-from products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig+from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfigfrom products.feature_flags.backend.models import TeamFeatureFlagDefaultsConfigfrom products.feature_flags.backend.models.evaluation_context import (EvaluationContext,diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 937fedc40860..6ea3c04b51bf 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -1,7 +1,10 @@import uuid+from typing import TYPE_CHECKINGfrom posthog.test.base import BaseTest, NonAtomicBaseTest+from django.apps import apps+from parameterized import parameterizedfrom posthog.hogql.context import HogQLContext@@ -29,7 +32,6 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohortfrom products.conversations.backend.models import Ticket-from products.customer_analytics.backend.models.account import Accountfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.models.data_modeling_job import DataModelingJob@@ -51,6 +53,11 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.models.table import DataWarehouseTable as DataWarehouseTableModelfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow+if TYPE_CHECKING:+ from products.customer_analytics.backend.models.account import Account+else:+ Account = apps.get_model("customer_analytics", "Account")+ALL_SYSTEM_TABLE_NAMES = sorted(SystemTables().children.keys())# {table_name: "sql_alias.column_name"} for team_id filter assertiondiff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 69995679ef67..74e4874658cc 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -1014,7 +1014,7 @@ def get_query_runner()if kind == "UsageMetricsQuery":- from products.customer_analytics.backend.hogql_queries.usage_metrics_query_runner import UsageMetricsQueryRunner+ from products.customer_analytics.backend.facade.queries import UsageMetricsQueryRunnerreturn UsageMetricsQueryRunner(query=query,@@ -1026,7 +1026,7 @@ def get_query_runner()if kind == "AccountsQuery":- from products.customer_analytics.backend.hogql_queries.accounts_query_runner import AccountsQueryRunner+ from products.customer_analytics.backend.facade.queries import AccountsQueryRunnerreturn AccountsQueryRunner(query=query,diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 493fe3cc92e9..718658c3fa53 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -66,7 +66,7 @@ except ImportError:passfrom posthog.slo.types import SloOutcome-from products.customer_analytics.backend.constants import DEFAULT_ACTIVITY_EVENT+from products.customer_analytics.backend.facade.constants import DEFAULT_ACTIVITY_EVENTfrom products.revenue_analytics.backend.hogql_queries.test.data.structure import REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENTMARKETING_ANALYTICS_SOURCES_MAP_SAMPLE = {diff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex 876d8fec4e95..220434180c0b 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -37,7 +37,7 @@ from posthog.rbac.decorators import field_access_controlfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom posthog.settings.utils import get_list-from products.customer_analytics.backend.constants import DEFAULT_ACTIVITY_EVENT+from products.customer_analytics.backend.facade.constants import DEFAULT_ACTIVITY_EVENTfrom ...hogql.modifiers import set_default_modifier_valuesfrom ...schema_enums import CurrencyCode, PersonsOnEventsMode@@ -736,9 +736,7 @@ class Team(UUIDTClassicModel):@cached_propertydef customer_analytics_config(self):- from products.customer_analytics.backend.models.team_customer_analytics_config import (- TeamCustomerAnalyticsConfig,- )+ from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfigreturn get_or_create_team_extension(self, TeamCustomerAnalyticsConfig, defaults={"activity_event": DEFAULT_ACTIVITY_EVENT}diff --git a/posthog/urls.py b/posthog/urls.pyindex d10e4d45a8d7..6237b01044ed 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -278,7 +278,7 @@ urlpatterns = [),path("api/sdk_health/", sdk_health),path("api/conversations/", include("products.conversations.backend.api.urls")),- path("api/customer_analytics/", include("products.customer_analytics.backend.api.urls")),+ path("api/customer_analytics/", include("products.customer_analytics.backend.presentation.views.urls")),path("api/environments/<int:parent_lookup_team_id>/mcp_analytics/",include("products.mcp_analytics.backend.presentation.urls"),diff --git a/products/customer_analytics/backend/api/__init__.py b/products/customer_analytics/backend/facade/__init__.pysimilarity index 100%rename from products/customer_analytics/backend/api/__init__.pyrename to products/customer_analytics/backend/facade/__init__.pydiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pynew file mode 100644index 000000000000..dc2d77fd71cf--- /dev/null+++ b/products/customer_analytics/backend/facade/api.py@@ -0,0 +1,198 @@+"""+Facade API for customer_analytics.++This is the data surface other apps import. Registry/wiring couplings live in+sibling submodules (``queries``, ``max_tools``, ``team_extension``, ``constants``)+to keep this module free of heavy imports (HogQL, ``ee.hogai.tool``) so config-only+consumers don't drag them onto the ``django.setup()`` path.++Responsibilities:+- Read product models, return contracts (never ORM instances or QuerySets)+- Stay thin and stable++Do NOT:+- Implement business rules here (use logic.py)+- Import DRF, serializers, or HTTP concerns+"""++from typing import TYPE_CHECKING++from django.core.exceptions import ValidationError+from django.db.models import Q++from posthog.models.tagged_item import TaggedItem++from products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplink+from products.customer_analytics.backend.logic.usage_spike_notifications import (+ notify_managers_of_usage_spike as notify_managers_of_usage_spike,+)+from products.customer_analytics.backend.models import Account+from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties+from products.notebooks.backend.models import Notebook, ResourceNotebook++from . import contracts++if TYPE_CHECKING:+ from posthog.rbac.user_access_control import UserAccessControl+++def _to_assignment(assignment) -> contracts.AccountAssignment | None:+ if assignment is None:+ return None+ return contracts.AccountAssignment(id=assignment.id, email=assignment.email)+++def _to_account_properties(properties: _ModelAccountProperties) -> contracts.AccountProperties:+ return contracts.AccountProperties(+ csm=_to_assignment(properties.csm),+ account_executive=_to_assignment(properties.account_executive),+ account_owner=_to_assignment(properties.account_owner),+ stripe_customer_id=properties.stripe_customer_id,+ hubspot_deal_id=properties.hubspot_deal_id,+ billing_id=properties.billing_id,+ sfdc_id=properties.sfdc_id,+ zendesk_id=properties.zendesk_id,+ slack_channel_id=properties.slack_channel_id,+ usage_dashboard_link=properties.usage_dashboard_link,+ )+++def _to_account_ref(row: dict) -> contracts.AccountRef:+ return contracts.AccountRef(id=str(row["id"]), name=row["name"], external_id=row["external_id"])+++def _account_tags(account: Account) -> list[str]:+ return sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))+++def _account_notes(account: Account) -> list[contracts.AccountNote]:+ links = (+ ResourceNotebook.objects.filter(+ account=account,+ notebook__deleted=False,+ notebook__visibility=Notebook.Visibility.INTERNAL,+ )+ .select_related("notebook")+ .order_by("-notebook__last_modified_at")+ )+ return [contracts.AccountNote(title=link.notebook.title, short_id=link.notebook.short_id) for link in links]+++def get_account_context_data(+ team_id: int,+ account_id: str | None = None,+ external_id: str | None = None,+ *,+ user_access_control: "UserAccessControl",+) -> contracts.AccountContextData | None:+ """Fetch one account (by id or external_id, scoped to the team) with the tags+ and internal notes the assistant context renders, gated by the caller's access.++ Returns None when no account matches, the identifier is malformed, or the caller+ lacks object-level read access — so a denied account is indistinguishable from a+ missing one to the caller.+ """+ account = _resolve_accessible_account(team_id, user_access_control, account_id=account_id, external_id=external_id)+ if account is None:+ return None+ return contracts.AccountContextData(+ id=account.id,+ name=account.name,+ external_id=account.external_id,+ created_at=account.created_at,+ properties=_to_account_properties(account.properties),+ tags=_account_tags(account),+ notes=_account_notes(account),+ )+++def _resolve_account(team_id: int, account_id: str | None = None, external_id: str | None = None) -> Account | None:+ try:+ if account_id:+ return Account.objects.for_team(team_id).get(id=account_id)+ if external_id:+ return Account.objects.for_team(team_id).get(external_id=external_id)+ return None+ except (Account.DoesNotExist, ValidationError, ValueError):+ return None+++def search_accounts(+ team_id: int, query: str, user_access_control: "UserAccessControl", limit: int+) -> tuple[list[contracts.AccountRef], int]:+ """Accounts matching `query` by name or external id, access-filtered for the caller.++ Returns `(rows, total_count)` where `total_count` is the pre-limit match count.+ """+ queryset = _accounts_queryset(team_id, user_access_control).filter(+ Q(name__icontains=query) | Q(external_id__icontains=query)+ )+ total_count = queryset.count()+ rows = list(queryset.order_by("name")[:limit].values("id", "name", "external_id"))+ return [_to_account_ref(row) for row in rows], total_count+++def list_accounts(+ team_id: int, offset: int, limit: int, user_access_control: "UserAccessControl"+) -> tuple[list[contracts.AccountRef], int]:+ """Accounts for the team, newest first, access-filtered for the caller.++ Returns `(rows, total_count)` where `total_count` is the full (unpaginated) count.+ """+ queryset = _accounts_queryset(team_id, user_access_control).order_by("-created_at")+ total_count = queryset.count()+ rows = list(queryset[offset : offset + limit].values("id", "name", "external_id"))+ return [_to_account_ref(row) for row in rows], total_count+++def _accounts_queryset(team_id: int, user_access_control: "UserAccessControl"):+ """Base accounts queryset, gated and object-level filtered by the caller's access.++ Account uses a fail-closed manager, so the unscoped manager is used with an+ explicit team filter (mirroring the prior in-consumer behavior).+ """+ if not user_access_control.check_access_level_for_resource("account", "viewer"):+ return Account.objects.unscoped().none()+ return user_access_control.filter_queryset_by_access_level(Account.objects.unscoped().filter(team_id=team_id))+++def _resolve_accessible_account(+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ account_id: str | None = None,+ external_id: str | None = None,+) -> Account | None:+ """Resolve one account the caller is allowed to read, or None.++ Goes through the access-gated queryset so an account the caller can't read is+ returned as None rather than leaked — unlike ``_resolve_account``, which is+ team-scoped only.+ """+ if account_id:+ lookup = {"id": account_id}+ elif external_id:+ lookup = {"external_id": external_id}+ else:+ return None+ try:+ return _accounts_queryset(team_id, user_access_control).filter(**lookup).first()+ except (ValidationError, ValueError):+ return None+++def get_account(+ team_id: int, account_id: str | None = None, external_id: str | None = None+) -> contracts.Account | None:+ """Fetch one account (by id or external_id, scoped to the team) as a contract."""+ account = _resolve_account(team_id, account_id=account_id, external_id=external_id)+ if account is None:+ return None+ return contracts.Account(+ id=account.id,+ team_id=account.team_id,+ external_id=account.external_id,+ name=account.name,+ properties=_to_account_properties(account.properties),+ created_at=account.created_at,+ )diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.pynew file mode 100644index 000000000000..a04011964d3d--- /dev/null+++ b/products/customer_analytics/backend/facade/constants.py@@ -0,0 +1,20 @@+"""Facade re-exports for customer_analytics constants.++These constants are pure, framework-free values (no heavy imports), reached+cross-boundary only through the facade. The internal ``backend.constants`` module+stays as the source of truth.+"""++from products.customer_analytics.backend.constants import (+ BILLING_SPEND_INSIGHT_SHORT_IDS,+ BILLING_USAGE_INSIGHT_SHORT_IDS,+ CUSTOMER_ANALYTICS_CSP_FLAG,+ DEFAULT_ACTIVITY_EVENT,+)++__all__ = [+ "BILLING_SPEND_INSIGHT_SHORT_IDS",+ "BILLING_USAGE_INSIGHT_SHORT_IDS",+ "CUSTOMER_ANALYTICS_CSP_FLAG",+ "DEFAULT_ACTIVITY_EVENT",+]diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pynew file mode 100644index 000000000000..e98e5db40e4d--- /dev/null+++ b/products/customer_analytics/backend/facade/contracts.py@@ -0,0 +1,95 @@+"""+Contract types for customer_analytics.++Stable, framework-free frozen dataclasses that define what this product exposes to+the rest of the codebase. No Django imports.++These use ``pydantic.dataclasses.dataclass`` rather than the stdlib variant — same+syntax and ``is_dataclass()`` compatibility, but with runtime validation on+construction, so structural mistakes from mappers surface at the facade boundary+instead of producing a malformed payload deeper in a caller.+"""++from dataclasses import field+from datetime import datetime+from uuid import UUID++from pydantic.dataclasses import dataclass+++@dataclass(frozen=True)+class AccountAssignment:+ """A user assigned to an account role (CSM, account executive, account owner)."""++ id: int+ email: str+++@dataclass(frozen=True)+class AccountProperties:+ """Typed account properties — assignment roles and external-system identifiers.++ Mirrors ``models.account.AccountProperties`` as a stable, framework-free shape.+ """++ csm: AccountAssignment | None = None+ account_executive: AccountAssignment | None = None+ account_owner: AccountAssignment | None = None+ stripe_customer_id: str | None = None+ hubspot_deal_id: str | None = None+ billing_id: str | None = None+ sfdc_id: str | None = None+ zendesk_id: str | None = None+ slack_channel_id: str | None = None+ usage_dashboard_link: str | None = None+++@dataclass(frozen=True)+class Account:+ """A customer-analytics account."""++ id: UUID+ team_id: int+ external_id: str | None+ name: str+ properties: AccountProperties+ created_at: datetime | None+++@dataclass(frozen=True)+class AccountRef:+ """Lightweight account reference for search/list result rows.++ ``id`` is the stringified UUID — entity-search rows are emitted as plain dicts+ keyed by string ids.+ """++ id: str+ name: str+ external_id: str | None+++@dataclass(frozen=True)+class AccountNote:+ """An internal note (notebook) attached to an account."""++ title: str | None+ short_id: str+++@dataclass(frozen=True)+class AccountContextData:+ """The account fields plus cross-cutting reads (tags, internal notes) the+ assistant's account-context formatter renders for one account.++ The configured group-type index stays with the consumer — it reads the core+ ``Team.customer_analytics_config`` property, not product internals.+ """++ id: UUID+ name: str+ external_id: str | None+ created_at: datetime | None+ properties: AccountProperties+ tags: list[str] = field(default_factory=list)+ notes: list[AccountNote] = field(default_factory=list)diff --git a/products/customer_analytics/backend/facade/max_tools.py b/products/customer_analytics/backend/facade/max_tools.pynew file mode 100644index 000000000000..c7009859b8ac--- /dev/null+++ b/products/customer_analytics/backend/facade/max_tools.py@@ -0,0 +1,14 @@+"""Facade re-exports for customer_analytics Max tools.++The assistant's agent-mode presets register these tool classes. Re-exporting them+in a dedicated submodule keeps ``facade/api.py`` free of the heavy ``ee.hogai.tool``+import so config-only consumers don't drag it onto the ``django.setup()`` path.+"""++from products.customer_analytics.backend.max_tools import OpenAccountTool, UpsertAccountNotebookTool, UpsertAccountTool++__all__ = [+ "OpenAccountTool",+ "UpsertAccountNotebookTool",+ "UpsertAccountTool",+]diff --git a/products/customer_analytics/backend/facade/queries.py b/products/customer_analytics/backend/facade/queries.pynew file mode 100644index 000000000000..47c2c70b63af--- /dev/null+++ b/products/customer_analytics/backend/facade/queries.py@@ -0,0 +1,16 @@+"""Facade re-exports for customer_analytics HogQL query runners.++Core's query-runner registry (``posthog/hogql_queries/query_runner.py``) dispatches+on query ``kind`` and constructs these runners by class identity. Re-exporting the+classes keeps that registry coupling at the facade boundary while the heavy HogQL+imports stay out of ``facade/api.py`` so config-only consumers don't drag them onto+the ``django.setup()`` path.+"""++from products.customer_analytics.backend.hogql_queries.accounts_query_runner import AccountsQueryRunner+from products.customer_analytics.backend.hogql_queries.usage_metrics_query_runner import UsageMetricsQueryRunner++__all__ = [+ "AccountsQueryRunner",+ "UsageMetricsQueryRunner",+]diff --git a/products/customer_analytics/backend/facade/team_extension.py b/products/customer_analytics/backend/facade/team_extension.pynew file mode 100644index 000000000000..6bb6abcbdcca--- /dev/null+++ b/products/customer_analytics/backend/facade/team_extension.py@@ -0,0 +1,12 @@+"""Facade re-export for the customer_analytics team-extension model.++Core's ``Team.customer_analytics_config`` accessor and ``posthog/api/team.py``+register/read this extension by class identity through+``get_or_create_team_extension``. Re-exporting the model class keeps that+registry coupling at the facade boundary without exposing the internal models+package.+"""++from products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig++__all__ = ["TeamCustomerAnalyticsConfig"]diff --git a/products/customer_analytics/backend/logic/__init__.py b/products/customer_analytics/backend/logic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/customer_analytics/backend/services/usage_spike_notifications.py b/products/customer_analytics/backend/logic/usage_spike_notifications.pysimilarity index 100%rename from products/customer_analytics/backend/services/usage_spike_notifications.pyrename to products/customer_analytics/backend/logic/usage_spike_notifications.pydiff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.pynew file mode 100644index 000000000000..2103c098abf7--- /dev/null+++ b/products/customer_analytics/backend/max_tools.py@@ -0,0 +1,434 @@+from textwrap import dedent+from typing import TYPE_CHECKING, Any, Literal, Union++from django.core.exceptions import ValidationError+from django.db import IntegrityError, transaction+from django.utils import timezone++from asgiref.sync import sync_to_async+from pydantic import BaseModel, ConfigDict, Field++from posthog.api.tagged_item import set_tags_on_object+from posthog.exceptions_capture import capture_exception+from posthog.rbac.user_access_control import AccessControlLevel+from posthog.scopes import APIScopeObject++from products.customer_analytics.backend.models import Account+from products.notebooks.backend.models import Notebook, ResourceNotebook++from ee.hogai.tool import MaxTool+from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes++if TYPE_CHECKING:+ from posthog.models import Team+++async def _aget_account_by_id(team: "Team", account_id: str) -> Account | None:+ """Resolve an account by id within a team. Account is fail-closed, so the+ unscoped manager is used with an explicit team filter."""+ account_id = str(account_id).strip()+ if not account_id:+ return None+ try:+ return await Account.objects.unscoped().aget(id=account_id, team=team)+ except (Account.DoesNotExist, ValidationError, ValueError):+ return None+++OPEN_ACCOUNT_TOOL_DESCRIPTION = dedent("""+ Open an account in the Accounts list and jump to one of its tabs — Notes, Users, or Usage.++ Use this to show the user an account's existing usage (the Usage tab) instead of building a new+ insight, or to surface its notes or related users. Identify the account by name or external id;+ `tab` defaults to usage. The account must be in the list the user is currently viewing.+ """).strip()+++class OpenAccountToolArgs(BaseModel):+ account: str = Field(description="The account to open — its name or external id.")+ tab: Literal["notes", "users", "usage"] = Field(+ default="usage",+ description="Which tab to open: notes, users, or usage. Defaults to usage.",+ )+++class OpenAccountTool(MaxTool):+ name: str = "open_account"+ description: str = OPEN_ACCOUNT_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = OpenAccountToolArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("account", "viewer")]++ async def _arun_impl(self, account: str, tab: str = "usage") -> tuple[str, dict[str, Any]]:+ resolved = await self._resolve_account(account)+ if resolved is None:+ return f"Couldn't find an account matching '{account}'.", {"error": "account_not_found"}+ await self.check_object_access(resolved, "viewer", resource="account", action="read")+ return (+ f"Opened {resolved.name}'s {tab} tab.",+ {+ "account_id": str(resolved.id),+ "account_name": resolved.name,+ "external_id": resolved.external_id,+ "tab": tab,+ },+ )++ async def _resolve_account(self, account: str) -> Account | None:+ account = account.strip()+ if not account:+ return None+ accounts = Account.objects.unscoped().filter(team=self._team)+ try:+ match = await accounts.filter(external_id=account).afirst()+ if match is None:+ match = await accounts.filter(name__iexact=account).afirst()+ return match+ except (ValidationError, ValueError):+ return None+++UPSERT_ACCOUNT_TOOL_DESCRIPTION = dedent("""+ Use this tool to create a new customer account or update an existing one.++ An account represents a customer organization. Its `external_id` must be the id PostHog uses to+ identify that organization in group analytics (its group key) — this is what links the account to+ its usage and activity data, so it must match exactly. Do NOT put a CRM or billing id here; record+ those with the dedicated properties (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,+ zendesk_id).++ # Actions+ - **create**: Create a new account (requires `name`).+ - **update**: Edit an existing account (requires `account_id`; all other fields optional).++ # Finding an account to update+ Resolve `account_id` (a UUID) first via `read_data`/`list_data` with the account kind.++ # Properties+ `properties` carries typed fields. Assignment fields (csm, account_executive, account_owner) take+ an object `{id, email}` (the PostHog user id and email) or null to clear. External-system ids+ (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id) are strings.+ On **update**, only the property keys you pass are changed (others are preserved); pass a key as+ null to clear it.++ # Tags+ Pass `tags` to set the account's tags. On update this REPLACES the existing tag set.++ # Examples+ - "Add an account for Acme Corp whose PostHog group key is acme-123": action=create, name="Acme Corp", external_id="acme-123"+ - "Assign Jane (user 42, [email protected]) as CSM for that account": action=update, account_id=<uuid>,+ properties={csm: {id: 42, email: "[email protected]"}}+ - "Tag it enterprise and priority": action=update, account_id=<uuid>, tags=["enterprise", "priority"]+ """).strip()+++class AccountAssignment(BaseModel):+ model_config = ConfigDict(extra="forbid")+ id: int = Field(description="PostHog user id of the assignee")+ email: str = Field(description="Email of the assignee")+++class AccountPropertiesInput(BaseModel):+ model_config = ConfigDict(extra="forbid")+ csm: AccountAssignment | None = Field(default=None, description="Customer success manager assignment")+ account_executive: AccountAssignment | None = Field(default=None, description="Account executive assignment")+ account_owner: AccountAssignment | None = Field(default=None, description="Account owner assignment")+ stripe_customer_id: str | None = Field(default=None, description="Stripe customer id")+ hubspot_deal_id: str | None = Field(default=None, description="HubSpot deal id")+ billing_id: str | None = Field(default=None, description="Billing system id")+ sfdc_id: str | None = Field(default=None, description="Salesforce id")+ zendesk_id: str | None = Field(default=None, description="Zendesk id")+++class CreateAccountAction(BaseModel):+ action: Literal["create"] = "create"+ name: str = Field(description="Human-readable account name, e.g. 'Acme Corp'")+ external_id: str | None = Field(+ default=None,+ description=(+ "The id PostHog uses to identify this organization in group analytics (its group key). "+ "Links the account to its usage and activity data, so it must match exactly. Do not put a "+ "CRM/billing id here — record those with the properties fields. Optional but strongly "+ "recommended."+ ),+ )+ tags: list[str] | None = Field(default=None, description="Tag names to attach to the account")+ properties: AccountPropertiesInput | None = Field(default=None, description="Typed account properties")+++class UpdateAccountAction(BaseModel):+ action: Literal["update"] = "update"+ account_id: str = Field(description="UUID of the account to update")+ name: str | None = Field(default=None, description="New account name")+ external_id: str | None = Field(+ default=None,+ description="New external id — the organization's group key in PostHog, not a CRM/billing id.",+ )+ tags: list[str] | None = Field(default=None, description="Replaces the account's existing tags")+ properties: AccountPropertiesInput | None = Field(+ default=None, description="Property keys to merge; pass a key as null to clear it"+ )+++UpsertAccountAction = Union[CreateAccountAction, UpdateAccountAction]+++class UpsertAccountToolArgs(BaseModel):+ action: UpsertAccountAction = Field(+ description="Create a new account or update an existing one.",+ discriminator="action",+ )+++class UpsertAccountTool(MaxTool):+ name: str = "upsert_account"+ description: str = UPSERT_ACCOUNT_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = UpsertAccountToolArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("account", "editor")]++ async def _arun_impl(self, action: UpsertAccountAction) -> tuple[str, dict[str, Any]]:+ if isinstance(action, CreateAccountAction):+ return await self._handle_create(action)+ return await self._handle_update(action)++ async def _handle_create(self, action: CreateAccountAction) -> tuple[str, dict[str, Any]]:+ properties = action.properties.model_dump(exclude_unset=True) if action.properties is not None else {}+ try:+ account = await self._create_account(action, properties)+ except IntegrityError:+ return f"An account with external_id '{action.external_id}' already exists for this team.", {+ "error": "duplicate_external_id",+ }+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to create account: {str(e)}", {"error": "creation_failed", "details": str(e)}++ return (+ f"Account '{account.name}' created successfully.",+ self._artifact(account),+ )++ async def _handle_update(self, action: UpdateAccountAction) -> tuple[str, dict[str, Any]]:+ account = await _aget_account_by_id(self._team, action.account_id)+ if account is None:+ return f"Account '{action.account_id}' not found.", {"error": "account_not_found"}++ await self.check_object_access(account, "editor", resource="account", action="edit")++ if action.name is None and action.external_id is None and action.tags is None and action.properties is None:+ return "No changes provided. Specify at least one field to update.", {"error": "no_changes"}++ try:+ account = await self._update_account(account, action)+ except IntegrityError:+ return f"An account with external_id '{action.external_id}' already exists for this team.", {+ "error": "duplicate_external_id",+ }+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to update account: {str(e)}", {"error": "update_failed", "details": str(e)}++ return (+ f"Account '{account.name}' updated successfully.",+ self._artifact(account),+ )++ @staticmethod+ def _artifact(account: Account) -> dict[str, Any]:+ return {+ "account_id": str(account.id),+ "name": account.name,+ "external_id": account.external_id,+ }++ @sync_to_async+ def _create_account(self, action: CreateAccountAction, properties: dict[str, Any]) -> Account:+ with transaction.atomic():+ account = Account.objects.create_account(+ team=self._team,+ created_by=self._user,+ name=action.name,+ external_id=(action.external_id or None),+ properties=properties,+ )+ if action.tags is not None:+ set_tags_on_object(action.tags, account)+ return account++ @sync_to_async+ def _update_account(self, account: Account, action: UpdateAccountAction) -> Account:+ update_kwargs: dict[str, Any] = {}+ if action.name is not None:+ update_kwargs["name"] = action.name+ if action.external_id is not None:+ update_kwargs["external_id"] = action.external_id or None+ if action.properties is not None:+ properties = account.properties.model_dump(mode="json")+ properties.update(action.properties.model_dump(exclude_unset=True))+ update_kwargs["properties"] = properties+ with transaction.atomic():+ account = Account.objects.update_account(account, **update_kwargs)+ if action.tags is not None:+ set_tags_on_object(action.tags, account)+ return account+++UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION = dedent("""+ Create or update a note attached to a customer account — a call recap, a meeting summary, an+ investigation timeline, or any free-form context worth persisting. Notes appear under the+ account's Notes tab in the Accounts list. Write the note body (`content`) in Markdown.++ # Actions+ - **create**: Add a new note to an account (requires `account_id`, a UUID). If you only have a+ name, resolve the account first with read_data/list_data using the account kind.+ - **update**: Revise an existing note (requires `notebook_short_id`). Pass a new `title` and/or+ `content`; `content` REPLACES the existing body, so send the full updated note, not just the+ change. Use the short_id returned when the note was created.+ """).strip()+++def _tiptap_doc(markdown: str) -> dict[str, Any]:+ return {"type": "doc", "content": markdown_to_tiptap_nodes(markdown) or [{"type": "paragraph"}]}+++class CreateAccountNotebookAction(BaseModel):+ action: Literal["create"] = "create"+ account_id: str = Field(description="UUID of the account to attach the note to.")+ title: str = Field(description="Short, descriptive title, e.g. 'Q3 kickoff call recap'.")+ content: str = Field(description="The note body in Markdown.")+++class UpdateAccountNotebookAction(BaseModel):+ action: Literal["update"] = "update"+ notebook_short_id: str = Field(description="short_id of the account note to update.")+ title: str | None = Field(default=None, description="New title; leave unset to keep the current one.")+ content: str | None = Field(+ default=None,+ description="New note body in Markdown; replaces the existing content. Leave unset to keep it.",+ )+++UpsertAccountNotebookAction = Union[CreateAccountNotebookAction, UpdateAccountNotebookAction]+++class UpsertAccountNotebookToolArgs(BaseModel):+ action: UpsertAccountNotebookAction = Field(+ description="Create a new account note or update an existing one.",+ discriminator="action",+ )+++class UpsertAccountNotebookTool(MaxTool):+ name: str = "upsert_account_notebook"+ description: str = UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = UpsertAccountNotebookToolArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("account", "editor")]++ async def _arun_impl(self, action: UpsertAccountNotebookAction) -> tuple[str, dict[str, Any]]:+ if isinstance(action, CreateAccountNotebookAction):+ return await self._handle_create(action)+ return await self._handle_update(action)++ async def _handle_create(self, action: CreateAccountNotebookAction) -> tuple[str, dict[str, Any]]:+ account = await _aget_account_by_id(self._team, action.account_id)+ if account is None:+ return f"Account '{action.account_id}' not found.", {"error": "account_not_found"}++ await self.check_object_access(account, "editor", resource="account", action="edit")++ try:+ notebook = await self._create_notebook(account, action)+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to create the note: {str(e)}", {"error": "creation_failed", "details": str(e)}++ return f"Created the note '{notebook.title}' on {account.name}.", self._artifact(notebook, account)++ async def _handle_update(self, action: UpdateAccountNotebookAction) -> tuple[str, dict[str, Any]]:+ if action.title is None and action.content is None:+ return "No changes provided. Specify a new title or content.", {"error": "no_changes"}++ resolved = await self._resolve_account_notebook(action.notebook_short_id)+ if resolved is None:+ return f"Account note '{action.notebook_short_id}' not found.", {"error": "notebook_not_found"}+ notebook, account = resolved++ await self.check_object_access(account, "editor", resource="account", action="edit")++ try:+ notebook = await self._update_notebook(notebook, action)+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to update the note: {str(e)}", {"error": "update_failed", "details": str(e)}++ return f"Updated the note '{notebook.title}' on {account.name}.", self._artifact(notebook, account)++ @staticmethod+ def _artifact(notebook: Notebook, account: Account) -> dict[str, Any]:+ return {+ "account_id": str(account.id),+ "account_name": account.name,+ "external_id": account.external_id,+ "notebook_short_id": notebook.short_id,+ "title": notebook.title,+ }++ async def _resolve_account_notebook(self, short_id: str) -> tuple[Notebook, Account] | None:+ short_id = str(short_id).strip()+ if not short_id:+ return None+ try:+ link = (+ await ResourceNotebook.objects.filter(+ notebook__short_id=short_id,+ notebook__team=self._team,+ notebook__deleted=False,+ notebook__visibility=Notebook.Visibility.INTERNAL,+ account__isnull=False,+ )+ .select_related("notebook", "account")+ .afirst()+ )+ except (ValidationError, ValueError):+ return None+ if link is None or link.account is None:+ return None+ return link.notebook, link.account++ @sync_to_async+ def _create_notebook(self, account: Account, action: CreateAccountNotebookAction) -> Notebook:+ with transaction.atomic():+ notebook = Notebook.objects.create(+ team=self._team,+ created_by=self._user,+ last_modified_by=self._user,+ visibility=Notebook.Visibility.INTERNAL,+ title=action.title[:256],+ text_content=action.content,+ content=_tiptap_doc(action.content),+ )+ ResourceNotebook.objects.create(notebook=notebook, account=account)+ return notebook++ @sync_to_async+ def _update_notebook(self, notebook: Notebook, action: UpdateAccountNotebookAction) -> Notebook:+ with transaction.atomic():+ locked = Notebook.objects.select_for_update().get(pk=notebook.pk)+ locked.last_modified_at = timezone.now()+ locked.last_modified_by = self._user+ update_fields = ["last_modified_at", "last_modified_by"]+ if action.title is not None:+ locked.title = action.title[:256]+ update_fields.append("title")+ if action.content is not None:+ locked.content = _tiptap_doc(action.content)+ locked.text_content = action.content+ locked.version = locked.version + 1+ update_fields += ["content", "text_content", "version"]+ locked.save(update_fields=update_fields)+ return lockeddiff --git a/products/customer_analytics/backend/max_tools/__init__.py b/products/customer_analytics/backend/max_tools/__init__.pydeleted file mode 100644index 1eda5669328a..000000000000--- a/products/customer_analytics/backend/max_tools/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-from products.customer_analytics.backend.max_tools.open_account import OpenAccountTool-from products.customer_analytics.backend.max_tools.upsert_account import UpsertAccountTool-from products.customer_analytics.backend.max_tools.upsert_account_notebook import UpsertAccountNotebookTool--__all__ = ["OpenAccountTool", "UpsertAccountNotebookTool", "UpsertAccountTool"]diff --git a/products/customer_analytics/backend/max_tools/open_account.py b/products/customer_analytics/backend/max_tools/open_account.pydeleted file mode 100644index 5ed6fb74a491..000000000000--- a/products/customer_analytics/backend/max_tools/open_account.py+++ /dev/null@@ -1,66 +0,0 @@-from textwrap import dedent-from typing import Any, Literal--from django.core.exceptions import ValidationError--from pydantic import BaseModel, Field--from posthog.rbac.user_access_control import AccessControlLevel-from posthog.scopes import APIScopeObject--from products.customer_analytics.backend.models import Account--from ee.hogai.tool import MaxTool--OPEN_ACCOUNT_TOOL_DESCRIPTION = dedent("""- Open an account in the Accounts list and jump to one of its tabs — Notes, Users, or Usage.-- Use this to show the user an account's existing usage (the Usage tab) instead of building a new- insight, or to surface its notes or related users. Identify the account by name or external id;- `tab` defaults to usage. The account must be in the list the user is currently viewing.- """).strip()---class OpenAccountToolArgs(BaseModel):- account: str = Field(description="The account to open — its name or external id.")- tab: Literal["notes", "users", "usage"] = Field(- default="usage",- description="Which tab to open: notes, users, or usage. Defaults to usage.",- )---class OpenAccountTool(MaxTool):- name: str = "open_account"- description: str = OPEN_ACCOUNT_TOOL_DESCRIPTION- args_schema: type[BaseModel] = OpenAccountToolArgs-- def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:- return [("account", "viewer")]-- async def _arun_impl(self, account: str, tab: str = "usage") -> tuple[str, dict[str, Any]]:- resolved = await self._resolve_account(account)- if resolved is None:- return f"Couldn't find an account matching '{account}'.", {"error": "account_not_found"}- await self.check_object_access(resolved, "viewer", resource="account", action="read")- return (- f"Opened {resolved.name}'s {tab} tab.",- {- "account_id": str(resolved.id),- "account_name": resolved.name,- "external_id": resolved.external_id,- "tab": tab,- },- )-- async def _resolve_account(self, account: str) -> Account | None:- account = account.strip()- if not account:- return None- accounts = Account.objects.unscoped().filter(team=self._team)- try:- match = await accounts.filter(external_id=account).afirst()- if match is None:- match = await accounts.filter(name__iexact=account).afirst()- return match- except (ValidationError, ValueError):- return Nonediff --git a/products/customer_analytics/backend/max_tools/upsert_account.py b/products/customer_analytics/backend/max_tools/upsert_account.pydeleted file mode 100644index 64158dd7e2fa..000000000000--- a/products/customer_analytics/backend/max_tools/upsert_account.py+++ /dev/null@@ -1,212 +0,0 @@-from textwrap import dedent-from typing import Any, Literal, Union--from django.core.exceptions import ValidationError-from django.db import IntegrityError, transaction--from asgiref.sync import sync_to_async-from pydantic import BaseModel, ConfigDict, Field--from posthog.api.tagged_item import set_tags_on_object-from posthog.exceptions_capture import capture_exception-from posthog.rbac.user_access_control import AccessControlLevel-from posthog.scopes import APIScopeObject--from products.customer_analytics.backend.models import Account--from ee.hogai.tool import MaxTool--UPSERT_ACCOUNT_TOOL_DESCRIPTION = dedent("""- Use this tool to create a new customer account or update an existing one.-- An account represents a customer organization. Its `external_id` must be the id PostHog uses to- identify that organization in group analytics (its group key) — this is what links the account to- its usage and activity data, so it must match exactly. Do NOT put a CRM or billing id here; record- those with the dedicated properties (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,- zendesk_id).-- # Actions- - **create**: Create a new account (requires `name`).- - **update**: Edit an existing account (requires `account_id`; all other fields optional).-- # Finding an account to update- Resolve `account_id` (a UUID) first via `read_data`/`list_data` with the account kind.-- # Properties- `properties` carries typed fields. Assignment fields (csm, account_executive, account_owner) take- an object `{id, email}` (the PostHog user id and email) or null to clear. External-system ids- (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id) are strings.- On **update**, only the property keys you pass are changed (others are preserved); pass a key as- null to clear it.-- # Tags- Pass `tags` to set the account's tags. On update this REPLACES the existing tag set.-- # Examples- - "Add an account for Acme Corp whose PostHog group key is acme-123": action=create, name="Acme Corp", external_id="acme-123"- - "Assign Jane (user 42, [email protected]) as CSM for that account": action=update, account_id=<uuid>,- properties={csm: {id: 42, email: "[email protected]"}}- - "Tag it enterprise and priority": action=update, account_id=<uuid>, tags=["enterprise", "priority"]- """).strip()---class AccountAssignment(BaseModel):- model_config = ConfigDict(extra="forbid")- id: int = Field(description="PostHog user id of the assignee")- email: str = Field(description="Email of the assignee")---class AccountPropertiesInput(BaseModel):- model_config = ConfigDict(extra="forbid")- csm: AccountAssignment | None = Field(default=None, description="Customer success manager assignment")- account_executive: AccountAssignment | None = Field(default=None, description="Account executive assignment")- account_owner: AccountAssignment | None = Field(default=None, description="Account owner assignment")- stripe_customer_id: str | None = Field(default=None, description="Stripe customer id")- hubspot_deal_id: str | None = Field(default=None, description="HubSpot deal id")- billing_id: str | None = Field(default=None, description="Billing system id")- sfdc_id: str | None = Field(default=None, description="Salesforce id")- zendesk_id: str | None = Field(default=None, description="Zendesk id")---class CreateAccountAction(BaseModel):- action: Literal["create"] = "create"- name: str = Field(description="Human-readable account name, e.g. 'Acme Corp'")- external_id: str | None = Field(- default=None,- description=(- "The id PostHog uses to identify this organization in group analytics (its group key). "- "Links the account to its usage and activity data, so it must match exactly. Do not put a "- "CRM/billing id here — record those with the properties fields. Optional but strongly "- "recommended."- ),- )- tags: list[str] | None = Field(default=None, description="Tag names to attach to the account")- properties: AccountPropertiesInput | None = Field(default=None, description="Typed account properties")---class UpdateAccountAction(BaseModel):- action: Literal["update"] = "update"- account_id: str = Field(description="UUID of the account to update")- name: str | None = Field(default=None, description="New account name")- external_id: str | None = Field(- default=None,- description="New external id — the organization's group key in PostHog, not a CRM/billing id.",- )- tags: list[str] | None = Field(default=None, description="Replaces the account's existing tags")- properties: AccountPropertiesInput | None = Field(- default=None, description="Property keys to merge; pass a key as null to clear it"- )---UpsertAccountAction = Union[CreateAccountAction, UpdateAccountAction]---class UpsertAccountToolArgs(BaseModel):- action: UpsertAccountAction = Field(- description="Create a new account or update an existing one.",- discriminator="action",- )---class UpsertAccountTool(MaxTool):- name: str = "upsert_account"- description: str = UPSERT_ACCOUNT_TOOL_DESCRIPTION- args_schema: type[BaseModel] = UpsertAccountToolArgs-- def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:- return [("account", "editor")]-- async def _arun_impl(self, action: UpsertAccountAction) -> tuple[str, dict[str, Any]]:- if isinstance(action, CreateAccountAction):- return await self._handle_create(action)- return await self._handle_update(action)-- async def _handle_create(self, action: CreateAccountAction) -> tuple[str, dict[str, Any]]:- properties = action.properties.model_dump(exclude_unset=True) if action.properties is not None else {}- try:- account = await self._create_account(action, properties)- except IntegrityError:- return f"An account with external_id '{action.external_id}' already exists for this team.", {- "error": "duplicate_external_id",- }- except Exception as e:- capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})- return f"Failed to create account: {str(e)}", {"error": "creation_failed", "details": str(e)}-- return (- f"Account '{account.name}' created successfully.",- self._artifact(account),- )-- async def _handle_update(self, action: UpdateAccountAction) -> tuple[str, dict[str, Any]]:- account = await self._resolve_account(action.account_id)- if account is None:- return f"Account '{action.account_id}' not found.", {"error": "account_not_found"}-- await self.check_object_access(account, "editor", resource="account", action="edit")-- if action.name is None and action.external_id is None and action.tags is None and action.properties is None:- return "No changes provided. Specify at least one field to update.", {"error": "no_changes"}-- try:- account = await self._update_account(account, action)- except IntegrityError:- return f"An account with external_id '{action.external_id}' already exists for this team.", {- "error": "duplicate_external_id",- }- except Exception as e:- capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})- return f"Failed to update account: {str(e)}", {"error": "update_failed", "details": str(e)}-- return (- f"Account '{account.name}' updated successfully.",- self._artifact(account),- )-- @staticmethod- def _artifact(account: Account) -> dict[str, Any]:- return {- "account_id": str(account.id),- "name": account.name,- "external_id": account.external_id,- }-- async def _resolve_account(self, account_id: str) -> Account | None:- account_id = str(account_id).strip()- if not account_id:- return None- try:- return await Account.objects.unscoped().aget(id=account_id, team=self._team)- except (Account.DoesNotExist, ValidationError, ValueError):- return None-- @sync_to_async- def _create_account(self, action: CreateAccountAction, properties: dict[str, Any]) -> Account:- with transaction.atomic():- account = Account.objects.create_account(- team=self._team,- created_by=self._user,- name=action.name,- external_id=(action.external_id or None),- properties=properties,- )- if action.tags is not None:- set_tags_on_object(action.tags, account)- return account-- @sync_to_async- def _update_account(self, account: Account, action: UpdateAccountAction) -> Account:- update_kwargs: dict[str, Any] = {}- if action.name is not None:- update_kwargs["name"] = action.name- if action.external_id is not None:- update_kwargs["external_id"] = action.external_id or None- if action.properties is not None:- properties = account.properties.model_dump(mode="json")- properties.update(action.properties.model_dump(exclude_unset=True))- update_kwargs["properties"] = properties- with transaction.atomic():- account = Account.objects.update_account(account, **update_kwargs)- if action.tags is not None:- set_tags_on_object(action.tags, account)- return accountdiff --git a/products/customer_analytics/backend/max_tools/upsert_account_notebook.py b/products/customer_analytics/backend/max_tools/upsert_account_notebook.pydeleted file mode 100644index 3cc45d35e528..000000000000--- a/products/customer_analytics/backend/max_tools/upsert_account_notebook.py+++ /dev/null@@ -1,185 +0,0 @@-from textwrap import dedent-from typing import Any, Literal, Union--from django.core.exceptions import ValidationError-from django.db import transaction-from django.utils import timezone--from asgiref.sync import sync_to_async-from pydantic import BaseModel, Field--from posthog.exceptions_capture import capture_exception-from posthog.rbac.user_access_control import AccessControlLevel-from posthog.scopes import APIScopeObject--from products.customer_analytics.backend.models import Account-from products.notebooks.backend.models import Notebook, ResourceNotebook--from ee.hogai.tool import MaxTool-from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes--UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION = dedent("""- Create or update a note attached to a customer account — a call recap, a meeting summary, an- investigation timeline, or any free-form context worth persisting. Notes appear under the- account's Notes tab in the Accounts list. Write the note body (`content`) in Markdown.-- # Actions- - **create**: Add a new note to an account (requires `account_id`, a UUID). If you only have a- name, resolve the account first with read_data/list_data using the account kind.- - **update**: Revise an existing note (requires `notebook_short_id`). Pass a new `title` and/or- `content`; `content` REPLACES the existing body, so send the full updated note, not just the- change. Use the short_id returned when the note was created.- """).strip()---def _tiptap_doc(markdown: str) -> dict[str, Any]:- return {"type": "doc", "content": markdown_to_tiptap_nodes(markdown) or [{"type": "paragraph"}]}---class CreateAccountNotebookAction(BaseModel):- action: Literal["create"] = "create"- account_id: str = Field(description="UUID of the account to attach the note to.")- title: str = Field(description="Short, descriptive title, e.g. 'Q3 kickoff call recap'.")- content: str = Field(description="The note body in Markdown.")---class UpdateAccountNotebookAction(BaseModel):- action: Literal["update"] = "update"- notebook_short_id: str = Field(description="short_id of the account note to update.")- title: str | None = Field(default=None, description="New title; leave unset to keep the current one.")- content: str | None = Field(- default=None,- description="New note body in Markdown; replaces the existing content. Leave unset to keep it.",- )---UpsertAccountNotebookAction = Union[CreateAccountNotebookAction, UpdateAccountNotebookAction]---class UpsertAccountNotebookToolArgs(BaseModel):- action: UpsertAccountNotebookAction = Field(- description="Create a new account note or update an existing one.",- discriminator="action",- )---class UpsertAccountNotebookTool(MaxTool):- name: str = "upsert_account_notebook"- description: str = UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION- args_schema: type[BaseModel] = UpsertAccountNotebookToolArgs-- def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:- return [("account", "editor")]-- async def _arun_impl(self, action: UpsertAccountNotebookAction) -> tuple[str, dict[str, Any]]:- if isinstance(action, CreateAccountNotebookAction):- return await self._handle_create(action)- return await self._handle_update(action)-- async def _handle_create(self, action: CreateAccountNotebookAction) -> tuple[str, dict[str, Any]]:- account = await self._resolve_account(action.account_id)- if account is None:- return f"Account '{action.account_id}' not found.", {"error": "account_not_found"}-- await self.check_object_access(account, "editor", resource="account", action="edit")-- try:- notebook = await self._create_notebook(account, action)- except Exception as e:- capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})- return f"Failed to create the note: {str(e)}", {"error": "creation_failed", "details": str(e)}-- return f"Created the note '{notebook.title}' on {account.name}.", self._artifact(notebook, account)-- async def _handle_update(self, action: UpdateAccountNotebookAction) -> tuple[str, dict[str, Any]]:- if action.title is None and action.content is None:- return "No changes provided. Specify a new title or content.", {"error": "no_changes"}-- resolved = await self._resolve_account_notebook(action.notebook_short_id)- if resolved is None:- return f"Account note '{action.notebook_short_id}' not found.", {"error": "notebook_not_found"}- notebook, account = resolved-- await self.check_object_access(account, "editor", resource="account", action="edit")-- try:- notebook = await self._update_notebook(notebook, action)- except Exception as e:- capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})- return f"Failed to update the note: {str(e)}", {"error": "update_failed", "details": str(e)}-- return f"Updated the note '{notebook.title}' on {account.name}.", self._artifact(notebook, account)-- @staticmethod- def _artifact(notebook: Notebook, account: Account) -> dict[str, Any]:- return {- "account_id": str(account.id),- "account_name": account.name,- "external_id": account.external_id,- "notebook_short_id": notebook.short_id,- "title": notebook.title,- }-- async def _resolve_account(self, account_id: str) -> Account | None:- account_id = str(account_id).strip()- if not account_id:- return None- try:- return await Account.objects.unscoped().aget(id=account_id, team=self._team)- except (Account.DoesNotExist, ValidationError, ValueError):- return None-- async def _resolve_account_notebook(self, short_id: str) -> tuple[Notebook, Account] | None:- short_id = str(short_id).strip()- if not short_id:- return None- try:- link = (- await ResourceNotebook.objects.filter(- notebook__short_id=short_id,- notebook__team=self._team,- notebook__deleted=False,- notebook__visibility=Notebook.Visibility.INTERNAL,- account__isnull=False,- )- .select_related("notebook", "account")- .afirst()- )- except (ValidationError, ValueError):- return None- if link is None or link.account is None:- return None- return link.notebook, link.account-- @sync_to_async- def _create_notebook(self, account: Account, action: CreateAccountNotebookAction) -> Notebook:- with transaction.atomic():- notebook = Notebook.objects.create(- team=self._team,- created_by=self._user,- last_modified_by=self._user,- visibility=Notebook.Visibility.INTERNAL,- title=action.title[:256],- text_content=action.content,- content=_tiptap_doc(action.content),- )- ResourceNotebook.objects.create(notebook=notebook, account=account)- return notebook-- @sync_to_async- def _update_notebook(self, notebook: Notebook, action: UpdateAccountNotebookAction) -> Notebook:- with transaction.atomic():- locked = Notebook.objects.select_for_update().get(pk=notebook.pk)- locked.last_modified_at = timezone.now()- locked.last_modified_by = self._user- update_fields = ["last_modified_at", "last_modified_by"]- if action.title is not None:- locked.title = action.title[:256]- update_fields.append("title")- if action.content is not None:- locked.content = _tiptap_doc(action.content)- locked.text_content = action.content- locked.version = locked.version + 1- update_fields += ["content", "text_content", "version"]- locked.save(update_fields=update_fields)- return lockeddiff --git a/products/customer_analytics/backend/presentation/__init__.py b/products/customer_analytics/backend/presentation/__init__.pynew file mode 100644index 000000000000..82b21af1ef2f--- /dev/null+++ b/products/customer_analytics/backend/presentation/__init__.py@@ -0,0 +1 @@+"""HTTP presentation layer of the customer_analytics product (DRF viewsets and serializers)."""diff --git a/products/customer_analytics/backend/presentation/views/__init__.py b/products/customer_analytics/backend/presentation/views/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/customer_analytics/backend/api/external.py b/products/customer_analytics/backend/presentation/views/external.pysimilarity index 100%rename from products/customer_analytics/backend/api/external.pyrename to products/customer_analytics/backend/presentation/views/external.pydiff --git a/products/customer_analytics/backend/api/organization_members.py b/products/customer_analytics/backend/presentation/views/organization_members.pysimilarity index 94%rename from products/customer_analytics/backend/api/organization_members.pyrename to products/customer_analytics/backend/presentation/views/organization_members.pyindex 1c54b64d0216..ff529bc03483 100644--- a/products/customer_analytics/backend/api/organization_members.py+++ b/products/customer_analytics/backend/presentation/views/organization_members.py@@ -11,8 +11,7 @@ from posthog.models import OrganizationMembershipfrom posthog.permissions import IsStaffUserOrImpersonating, PostHogFeatureFlagPermissionfrom products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAG--from .serializers import AccountOrganizationMemberSerializer+from products.customer_analytics.backend.presentation.views.serializers import AccountOrganizationMemberSerializer# Excluded from the generated OpenAPI clients: this is an INTERNAL, staff-only endpointdiff --git a/products/customer_analytics/backend/api/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pysimilarity index 100%rename from products/customer_analytics/backend/api/serializers.pyrename to products/customer_analytics/backend/presentation/views/serializers.pydiff --git a/products/customer_analytics/backend/api/urls.py b/products/customer_analytics/backend/presentation/views/urls.pysimilarity index 67%rename from products/customer_analytics/backend/api/urls.pyrename to products/customer_analytics/backend/presentation/views/urls.pyindex 8091b369a470..1c2e07b884a4 100644--- a/products/customer_analytics/backend/api/urls.py+++ b/products/customer_analytics/backend/presentation/views/urls.py@@ -2,7 +2,7 @@from django.urls import path-from .external import ExternalAccountView+from products.customer_analytics.backend.presentation.views.external import ExternalAccountViewurlpatterns = [path("external/account", ExternalAccountView.as_view(), name="external-account"),diff --git a/products/customer_analytics/backend/api/utils.py b/products/customer_analytics/backend/presentation/views/utils.pysimilarity index 100%rename from products/customer_analytics/backend/api/utils.pyrename to products/customer_analytics/backend/presentation/views/utils.pydiff --git a/products/customer_analytics/backend/api/views.py b/products/customer_analytics/backend/presentation/views/views.pysimilarity index 98%rename from products/customer_analytics/backend/api/views.pyrename to products/customer_analytics/backend/presentation/views/views.pyindex 1a112fd81c59..c95b2dd13b35 100644--- a/products/customer_analytics/backend/api/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -15,17 +15,16 @@ from posthog.api.utils import log_activity_from_viewsetfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig-from products.notebooks.backend.models import Notebook, ResourceNotebook--from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes--from .serializers import (+from products.customer_analytics.backend.presentation.views.serializers import (AccountNotebookSerializer,AccountSerializer,CustomerJourneySerializer,CustomerProfileConfigSerializer,)-from .utils import log_customer_profile_config_activity+from products.customer_analytics.backend.presentation.views.utils import log_customer_profile_config_activity+from products.notebooks.backend.models import Notebook, ResourceNotebook++from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodesclass CustomerProfileConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex 867012828de6..bf2ecdeff307 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -1,7 +1,9 @@from posthog.api.routing import RouterRegistry-from products.customer_analytics.backend.api.organization_members import OrganizationMembersForAccountViewSet-from products.customer_analytics.backend.api.views import (+from products.customer_analytics.backend.presentation.views.organization_members import (+ OrganizationMembersForAccountViewSet,+)+from products.customer_analytics.backend.presentation.views.views import (AccountNotebookViewSet,AccountViewSet,CustomerJourneyViewSet,diff --git a/products/customer_analytics/backend/api/test_external.py b/products/customer_analytics/backend/test/test_external.pysimilarity index 98%rename from products/customer_analytics/backend/api/test_external.pyrename to products/customer_analytics/backend/test/test_external.pyindex 63ac9fd9ec6c..64bc7bedf296 100644--- a/products/customer_analytics/backend/api/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -22,7 +22,7 @@ class TestExternalAccountAPI(APIBaseTest):self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")self.url = "/api/customer_analytics/external/account"csp_enabled = patch(- "products.customer_analytics.backend.api.external.posthoganalytics.feature_enabled",+ "products.customer_analytics.backend.presentation.views.external.posthoganalytics.feature_enabled",return_value=True,)self.mock_csp_enabled = csp_enabled.start()@@ -197,7 +197,7 @@ class TestExternalAccountAPI(APIBaseTest):def test_patch_rolls_back_role_assignment_when_tags_fail(self):with patch(- "products.customer_analytics.backend.api.external._apply_tags",+ "products.customer_analytics.backend.presentation.views.external._apply_tags",side_effect=Exception("boom"),):response = self._patch(diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pynew file mode 100644index 000000000000..150fd6213a6c--- /dev/null+++ b/products/customer_analytics/backend/test/test_facade.py@@ -0,0 +1,114 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock++from posthog.models.tag import Tag+from posthog.models.tagged_item import TaggedItem+from posthog.rbac.user_access_control import UserAccessControl++from products.customer_analytics.backend.facade import (+ api as facade,+ contracts,+)+from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties+from products.customer_analytics.backend.test.factories import create_account+from products.notebooks.backend.models import Notebook, ResourceNotebook+++class TestCustomerAnalyticsFacade(BaseTest):+ def _uac(self) -> UserAccessControl:+ return UserAccessControl(user=self.user, team=self.team)++ def test_get_account_returns_contract_with_properties(self):+ account = create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-123",+ _properties=AccountProperties(+ csm=AccountAssignment(id=self.user.id, email=self.user.email),+ stripe_customer_id="cus_1",+ ).model_dump(mode="json"),+ )++ result = facade.get_account(self.team.id, account_id=str(account.id))++ assert isinstance(result, contracts.Account)+ assert result.id == account.id+ assert result.team_id == self.team.id+ assert result.external_id == "acme-123"+ assert result.name == "Acme Corp"+ assert result.properties.csm == contracts.AccountAssignment(id=self.user.id, email=self.user.email)+ assert result.properties.stripe_customer_id == "cus_1"++ def test_get_account_by_external_id_and_missing(self):+ create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")++ assert facade.get_account(self.team.id, external_id="acme-123") is not None+ assert facade.get_account(self.team.id, external_id="nope") is None+ assert facade.get_account(self.team.id, account_id="not-a-uuid") is None+ assert facade.get_account(self.team.id) is None++ def test_get_account_context_data_bundles_tags_and_notes(self):+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")+ tag = Tag.objects.create(name="enterprise", team_id=self.team.id)+ TaggedItem.objects.create(tag=tag, account=account)+ notebook = Notebook.objects.create(+ team=self.team,+ created_by=self.user,+ title="Q3 recap",+ visibility=Notebook.Visibility.INTERNAL,+ )+ ResourceNotebook.objects.create(notebook=notebook, account=account)++ data = facade.get_account_context_data(+ self.team.id, account_id=str(account.id), user_access_control=self._uac()+ )++ assert isinstance(data, contracts.AccountContextData)+ assert data.name == "Acme Corp"+ assert data.tags == ["enterprise"]+ assert data.notes == [contracts.AccountNote(title="Q3 recap", short_id=notebook.short_id)]++ def test_get_account_context_data_missing(self):+ assert (+ facade.get_account_context_data(self.team.id, external_id="missing", user_access_control=self._uac())+ is None+ )++ def test_get_account_context_data_denied_object_level_returns_none(self):+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")+ uac = MagicMock()+ uac.check_access_level_for_resource.return_value = True+ uac.filter_queryset_by_access_level.side_effect = lambda qs: qs.none()++ assert (+ facade.get_account_context_data(self.team.id, account_id=str(account.id), user_access_control=uac) is None+ )++ def test_get_account_context_data_denied_resource_level_returns_none(self):+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")+ uac = MagicMock()+ uac.check_access_level_for_resource.return_value = False++ assert (+ facade.get_account_context_data(self.team.id, account_id=str(account.id), user_access_control=uac) is None+ )++ def test_search_accounts_matches_name_and_external_id(self):+ create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")+ create_account(team_id=self.team.id, name="Globex", external_id="globex-9")++ rows, count = facade.search_accounts(self.team.id, "acme", self._uac(), limit=10)++ assert count == 1+ assert [r.name for r in rows] == ["Acme Corp"]+ assert isinstance(rows[0], contracts.AccountRef)+ assert isinstance(rows[0].id, str)++ def test_list_accounts_newest_first_with_count(self):+ create_account(team_id=self.team.id, name="First")+ create_account(team_id=self.team.id, name="Second")++ rows, count = facade.list_accounts(self.team.id, offset=0, limit=10, user_access_control=self._uac())++ assert count == 2+ assert {r.name for r in rows} == {"First", "Second"}diff --git a/products/customer_analytics/backend/max_tools/test_open_account.py b/products/customer_analytics/backend/test/test_open_account.pysimilarity index 96%rename from products/customer_analytics/backend/max_tools/test_open_account.pyrename to products/customer_analytics/backend/test/test_open_account.pyindex 2949f61363b3..eee24655fe15 100644--- a/products/customer_analytics/backend/max_tools/test_open_account.py+++ b/products/customer_analytics/backend/test/test_open_account.py@@ -6,7 +6,7 @@ from langchain_core.runnables import RunnableConfigfrom posthog.models import Team-from products.customer_analytics.backend.max_tools.open_account import OpenAccountTool+from products.customer_analytics.backend.max_tools import OpenAccountToolfrom products.customer_analytics.backend.models import Accountdiff --git a/products/customer_analytics/backend/api/test_organization_members.py b/products/customer_analytics/backend/test/test_organization_members.pysimilarity index 100%rename from products/customer_analytics/backend/api/test_organization_members.pyrename to products/customer_analytics/backend/test/test_organization_members.pydiff --git a/products/customer_analytics/backend/max_tools/test_upsert_account.py b/products/customer_analytics/backend/test/test_upsert_account.pysimilarity index 98%rename from products/customer_analytics/backend/max_tools/test_upsert_account.pyrename to products/customer_analytics/backend/test/test_upsert_account.pyindex cd6f9cb0e0b1..834f63fbada3 100644--- a/products/customer_analytics/backend/max_tools/test_upsert_account.py+++ b/products/customer_analytics/backend/test/test_upsert_account.py@@ -8,7 +8,7 @@ from langchain_core.runnables import RunnableConfigfrom posthog.models import TaggedItem, Team-from products.customer_analytics.backend.max_tools.upsert_account import (+from products.customer_analytics.backend.max_tools import (AccountAssignment,AccountPropertiesInput,CreateAccountAction,diff --git a/products/customer_analytics/backend/max_tools/test_upsert_account_notebook.py b/products/customer_analytics/backend/test/test_upsert_account_notebook.pysimilarity index 98%rename from products/customer_analytics/backend/max_tools/test_upsert_account_notebook.pyrename to products/customer_analytics/backend/test/test_upsert_account_notebook.pyindex c9ea0fff979b..2d25faa969db 100644--- a/products/customer_analytics/backend/max_tools/test_upsert_account_notebook.py+++ b/products/customer_analytics/backend/test/test_upsert_account_notebook.py@@ -8,7 +8,7 @@ from langchain_core.runnables import RunnableConfigfrom posthog.models import Team-from products.customer_analytics.backend.max_tools.upsert_account_notebook import (+from products.customer_analytics.backend.max_tools import (CreateAccountNotebookAction,UpdateAccountNotebookAction,UpsertAccountNotebookTool,diff --git a/products/customer_analytics/backend/test/test_usage_spike_notifications.py b/products/customer_analytics/backend/test/test_usage_spike_notifications.pyindex 3c7752a80747..8752119f68c7 100644--- a/products/customer_analytics/backend/test/test_usage_spike_notifications.py+++ b/products/customer_analytics/backend/test/test_usage_spike_notifications.py@@ -5,11 +5,11 @@ from parameterized import parameterizedfrom posthog.models import Team-from products.customer_analytics.backend.services.usage_spike_notifications import notify_managers_of_usage_spike+from products.customer_analytics.backend.logic.usage_spike_notifications import notify_managers_of_usage_spikefrom products.customer_analytics.backend.test.factories import create_accountfrom products.notifications.backend.facade.enums import NotificationType, Priority, SourceType, TargetType-SERVICE = "products.customer_analytics.backend.services.usage_spike_notifications"+SERVICE = "products.customer_analytics.backend.logic.usage_spike_notifications"SPIKES = [{"metric": "events", "factor": 3.2, "direction": "up", "percent_change": 220}]diff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/test/test_views.pysimilarity index 100%rename from products/customer_analytics/backend/api/test_views.pyrename to products/customer_analytics/backend/test/test_views.pydiff --git a/products/customer_analytics/tsconfig.json b/products/customer_analytics/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/customer_analytics/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/pyproject.toml b/pyproject.tomlindex 7cf4110fc239..21c64aed93f4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -569,6 +569,16 @@ ignore_imports = ["products.logs.backend.presentation.views.api -> products.exports.backend.models.exported_asset","products.logs.backend.presentation.views.alerts_api -> products.cdp.backend.api.hog_function","products.logs.backend.presentation.views.alerts_api -> products.cdp.backend.models.hog_functions.hog_function",+ # TODO: customer_analytics presentation wave — these views still reach internals directly.+ # Thin each view to parse -> facade -> serialize and delete its entry. backend:contract-check+ # stays off until this list is empty.+ "products.customer_analytics.backend.presentation.views.external -> products.customer_analytics.backend.constants",+ "products.customer_analytics.backend.presentation.views.external -> products.customer_analytics.backend.models",+ "products.customer_analytics.backend.presentation.views.external -> products.customer_analytics.backend.models.account",+ "products.customer_analytics.backend.presentation.views.organization_members -> products.customer_analytics.backend.constants",+ "products.customer_analytics.backend.presentation.views.serializers -> products.customer_analytics.backend.models",+ "products.customer_analytics.backend.presentation.views.utils -> products.customer_analytics.backend.models",+ "products.customer_analytics.backend.presentation.views.views -> products.customer_analytics.backend.models",][tool.ty.rules]diff --git a/tach.toml b/tach.tomlindex e0cbb807420b..5df719a65d34 100644--- a/tach.toml+++ b/tach.toml@@ -690,7 +690,7 @@ expose = ["backend\\.routes.*",]from = [- "products\\.(error_tracking|experiments|mcp_analytics|mcp_store|metrics|notifications|streamlit_apps|tracing|user_interviews|visual_review)",+ "products\\.(customer_analytics|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notifications|streamlit_apps|tracing|user_interviews|visual_review)",]# TODO: Experiments-specific temporary interface